diff --git a/Geometry/boombox.glb b/Geometry/boombox.glb new file mode 100644 index 0000000000..fea645856e Binary files /dev/null and b/Geometry/boombox.glb differ diff --git a/Geometry/chess_set.glb b/Geometry/chess_set.glb new file mode 100644 index 0000000000..c3b1770bd1 Binary files /dev/null and b/Geometry/chess_set.glb differ diff --git a/Geometry/shaderball.glb b/Geometry/shaderball.glb new file mode 100644 index 0000000000..ce6d5a3cf7 Binary files /dev/null and b/Geometry/shaderball.glb differ diff --git a/Images/brass_color.jpg b/Images/brass_color.jpg new file mode 100644 index 0000000000..047f1619bc Binary files /dev/null and b/Images/brass_color.jpg differ diff --git a/Images/brass_roughness.jpg b/Images/brass_roughness.jpg new file mode 100644 index 0000000000..2f0054013d Binary files /dev/null and b/Images/brass_roughness.jpg differ diff --git a/Images/brick_base_gray.jpg b/Images/brick_base_gray.jpg new file mode 100644 index 0000000000..1db93cfaf9 Binary files /dev/null and b/Images/brick_base_gray.jpg differ diff --git a/Images/brick_dirt_mask.jpg b/Images/brick_dirt_mask.jpg new file mode 100644 index 0000000000..a1f6a9c687 Binary files /dev/null and b/Images/brick_dirt_mask.jpg differ diff --git a/Images/brick_mask.jpg b/Images/brick_mask.jpg new file mode 100644 index 0000000000..7432ba422c Binary files /dev/null and b/Images/brick_mask.jpg differ diff --git a/Images/brick_normal.jpg b/Images/brick_normal.jpg new file mode 100644 index 0000000000..07b18cb770 Binary files /dev/null and b/Images/brick_normal.jpg differ diff --git a/Images/brick_roughness.jpg b/Images/brick_roughness.jpg new file mode 100644 index 0000000000..78ba144aa9 Binary files /dev/null and b/Images/brick_roughness.jpg differ diff --git a/Images/brick_variation_mask.jpg b/Images/brick_variation_mask.jpg new file mode 100644 index 0000000000..880a0b77d8 Binary files /dev/null and b/Images/brick_variation_mask.jpg differ diff --git a/Images/cloth.bmp b/Images/cloth.bmp new file mode 100644 index 0000000000..b6191de952 Binary files /dev/null and b/Images/cloth.bmp differ diff --git a/Images/cloth.gif b/Images/cloth.gif new file mode 100644 index 0000000000..d9cd2b48bc Binary files /dev/null and b/Images/cloth.gif differ diff --git a/Images/cloth.jpg b/Images/cloth.jpg new file mode 100644 index 0000000000..c01e382310 Binary files /dev/null and b/Images/cloth.jpg differ diff --git a/Images/cloth.png b/Images/cloth.png new file mode 100644 index 0000000000..05ff747df9 Binary files /dev/null and b/Images/cloth.png differ diff --git a/Images/cloth.tga b/Images/cloth.tga new file mode 100644 index 0000000000..bd38dd95b6 Binary files /dev/null and b/Images/cloth.tga differ diff --git a/Images/greysphere_calibration.png b/Images/greysphere_calibration.png new file mode 100644 index 0000000000..f3e455a34b Binary files /dev/null and b/Images/greysphere_calibration.png differ diff --git a/Images/grid.png b/Images/grid.png new file mode 100644 index 0000000000..def064928b Binary files /dev/null and b/Images/grid.png differ diff --git a/Images/marble.png b/Images/marble.png new file mode 100644 index 0000000000..9e962bb49c Binary files /dev/null and b/Images/marble.png differ diff --git a/Images/mesh_wire_norm.png b/Images/mesh_wire_norm.png new file mode 100644 index 0000000000..bd7ef5e4f2 Binary files /dev/null and b/Images/mesh_wire_norm.png differ diff --git a/Images/plain_heightmap.png b/Images/plain_heightmap.png new file mode 100644 index 0000000000..e997f4f811 Binary files /dev/null and b/Images/plain_heightmap.png differ diff --git a/Images/wood_color.jpg b/Images/wood_color.jpg new file mode 100644 index 0000000000..c61b13a0fd Binary files /dev/null and b/Images/wood_color.jpg differ diff --git a/Images/wood_roughness.jpg b/Images/wood_roughness.jpg new file mode 100644 index 0000000000..af292bdd36 Binary files /dev/null and b/Images/wood_roughness.jpg differ diff --git a/JsMaterialXCore.js b/JsMaterialXCore.js new file mode 100644 index 0000000000..d95e76ca26 --- /dev/null +++ b/JsMaterialXCore.js @@ -0,0 +1,21 @@ + +var MaterialX = (function() { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; + return ( +function(MaterialX) { + MaterialX = MaterialX || {}; + +var Module=typeof MaterialX!=="undefined"?MaterialX:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!=="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var STACK_ALIGN=16;function alignMemory(size,factor){if(!factor)factor=STACK_ALIGN;return Math.ceil(size/factor)*factor}var tempRet0=0;var setTempRet0=function(value){tempRet0=value};var getTempRet0=function(){return tempRet0};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!=="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}var UTF8Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}var UTF16Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf-16le"):undefined;function UTF16ToString(ptr,maxBytesToRead){var endPtr=ptr;var idx=endPtr>>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder){return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr))}else{var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str}}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i=55296&&codeUnit<=57343)++i;len+=4}return len}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.init.initialized)FS.init();TTY.init();callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}function isFileURI(filename){return filename.startsWith("file://")}var wasmBinaryFile="JsMaterialXCore.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["Ra"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["Ua"];addOnInit(Module["asm"]["Sa"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){var result=WebAssembly.instantiate(binary,info);return result}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiationResult,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiationResult)})})}else{return instantiateArrayBuffer(receiveInstantiationResult)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}var tempDouble;var tempI64;var ASM_CONSTS={129708:function(){Module["TreeIterator"]["prototype"][Symbol.iterator]=function(){return this}},129792:function(){Module["GraphIterator"]["prototype"][Symbol.iterator]=function(){return this}},129877:function(){Module["InheritanceIterator"]["prototype"][Symbol.iterator]=function(){return this}}};function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){wasmTable.get(func)()}else{wasmTable.get(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}function ___assert_fail(condition,filename,line,func){abort("Assertion failed: "+UTF8ToString(condition)+", at: "+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"])}var ExceptionInfoAttrs={DESTRUCTOR_OFFSET:0,REFCOUNT_OFFSET:4,TYPE_OFFSET:8,CAUGHT_OFFSET:12,RETHROWN_OFFSET:13,SIZE:16};function ___cxa_allocate_exception(size){return _malloc(size+ExceptionInfoAttrs.SIZE)+ExceptionInfoAttrs.SIZE}function ExceptionInfo(excPtr){this.excPtr=excPtr;this.ptr=excPtr-ExceptionInfoAttrs.SIZE;this.set_type=function(type){HEAP32[this.ptr+ExceptionInfoAttrs.TYPE_OFFSET>>2]=type};this.get_type=function(){return HEAP32[this.ptr+ExceptionInfoAttrs.TYPE_OFFSET>>2]};this.set_destructor=function(destructor){HEAP32[this.ptr+ExceptionInfoAttrs.DESTRUCTOR_OFFSET>>2]=destructor};this.get_destructor=function(){return HEAP32[this.ptr+ExceptionInfoAttrs.DESTRUCTOR_OFFSET>>2]};this.set_refcount=function(refcount){HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=refcount};this.set_caught=function(caught){caught=caught?1:0;HEAP8[this.ptr+ExceptionInfoAttrs.CAUGHT_OFFSET>>0]=caught};this.get_caught=function(){return HEAP8[this.ptr+ExceptionInfoAttrs.CAUGHT_OFFSET>>0]!=0};this.set_rethrown=function(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+ExceptionInfoAttrs.RETHROWN_OFFSET>>0]=rethrown};this.get_rethrown=function(){return HEAP8[this.ptr+ExceptionInfoAttrs.RETHROWN_OFFSET>>0]!=0};this.init=function(type,destructor){this.set_type(type);this.set_destructor(destructor);this.set_refcount(0);this.set_caught(false);this.set_rethrown(false)};this.add_ref=function(){var value=HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2];HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=value+1};this.release_ref=function(){var prev=HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2];HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=prev-1;return prev===1}}function CatchInfo(ptr){this.free=function(){_free(this.ptr);this.ptr=0};this.set_base_ptr=function(basePtr){HEAP32[this.ptr>>2]=basePtr};this.get_base_ptr=function(){return HEAP32[this.ptr>>2]};this.set_adjusted_ptr=function(adjustedPtr){var ptrSize=4;HEAP32[this.ptr+ptrSize>>2]=adjustedPtr};this.get_adjusted_ptr=function(){var ptrSize=4;return HEAP32[this.ptr+ptrSize>>2]};this.get_exception_ptr=function(){var isPointer=___cxa_is_pointer_type(this.get_exception_info().get_type());if(isPointer){return HEAP32[this.get_base_ptr()>>2]}var adjusted=this.get_adjusted_ptr();if(adjusted!==0)return adjusted;return this.get_base_ptr()};this.get_exception_info=function(){return new ExceptionInfo(this.get_base_ptr())};if(ptr===undefined){this.ptr=_malloc(8);this.set_adjusted_ptr(0)}else{this.ptr=ptr}}var exceptionCaught=[];function exception_addRef(info){info.add_ref()}var uncaughtExceptionCount=0;function ___cxa_begin_catch(ptr){var catchInfo=new CatchInfo(ptr);var info=catchInfo.get_exception_info();if(!info.get_caught()){info.set_caught(true);uncaughtExceptionCount--}info.set_rethrown(false);exceptionCaught.push(catchInfo);exception_addRef(info);return catchInfo.get_exception_ptr()}var exceptionLast=0;function ___cxa_free_exception(ptr){return _free(new ExceptionInfo(ptr).ptr)}function exception_decRef(info){if(info.release_ref()&&!info.get_rethrown()){var destructor=info.get_destructor();if(destructor){wasmTable.get(destructor)(info.excPtr)}___cxa_free_exception(info.excPtr)}}function ___cxa_end_catch(){_setThrew(0);var catchInfo=exceptionCaught.pop();exception_decRef(catchInfo.get_exception_info());catchInfo.free();exceptionLast=0}function ___resumeException(catchInfoPtr){var catchInfo=new CatchInfo(catchInfoPtr);var ptr=catchInfo.get_base_ptr();if(!exceptionLast){exceptionLast=ptr}catchInfo.free();throw ptr}function ___cxa_find_matching_catch_2(){var thrown=exceptionLast;if(!thrown){setTempRet0(0);return 0|0}var info=new ExceptionInfo(thrown);var thrownType=info.get_type();var catchInfo=new CatchInfo;catchInfo.set_base_ptr(thrown);if(!thrownType){setTempRet0(0);return catchInfo.ptr|0}var typeArray=Array.prototype.slice.call(arguments);var stackTop=stackSave();var exceptionThrowBuf=stackAlloc(4);HEAP32[exceptionThrowBuf>>2]=thrown;for(var i=0;i>2];if(thrown!==adjusted){catchInfo.set_adjusted_ptr(adjusted)}setTempRet0(caughtType);return catchInfo.ptr|0}}stackRestore(stackTop);setTempRet0(thrownType);return catchInfo.ptr|0}function ___cxa_find_matching_catch_3(){var thrown=exceptionLast;if(!thrown){setTempRet0(0);return 0|0}var info=new ExceptionInfo(thrown);var thrownType=info.get_type();var catchInfo=new CatchInfo;catchInfo.set_base_ptr(thrown);if(!thrownType){setTempRet0(0);return catchInfo.ptr|0}var typeArray=Array.prototype.slice.call(arguments);var stackTop=stackSave();var exceptionThrowBuf=stackAlloc(4);HEAP32[exceptionThrowBuf>>2]=thrown;for(var i=0;i>2];if(thrown!==adjusted){catchInfo.set_adjusted_ptr(adjusted)}setTempRet0(caughtType);return catchInfo.ptr|0}}stackRestore(stackTop);setTempRet0(thrownType);return catchInfo.ptr|0}function ___cxa_find_matching_catch_4(){var thrown=exceptionLast;if(!thrown){setTempRet0(0);return 0|0}var info=new ExceptionInfo(thrown);var thrownType=info.get_type();var catchInfo=new CatchInfo;catchInfo.set_base_ptr(thrown);if(!thrownType){setTempRet0(0);return catchInfo.ptr|0}var typeArray=Array.prototype.slice.call(arguments);var stackTop=stackSave();var exceptionThrowBuf=stackAlloc(4);HEAP32[exceptionThrowBuf>>2]=thrown;for(var i=0;i>2];if(thrown!==adjusted){catchInfo.set_adjusted_ptr(adjusted)}setTempRet0(caughtType);return catchInfo.ptr|0}}stackRestore(stackTop);setTempRet0(thrownType);return catchInfo.ptr|0}function ___cxa_rethrow(){var catchInfo=exceptionCaught.pop();if(!catchInfo){abort("no exception to throw")}var info=catchInfo.get_exception_info();var ptr=catchInfo.get_base_ptr();if(!info.get_rethrown()){exceptionCaught.push(catchInfo);info.set_rethrown(true);info.set_caught(false);uncaughtExceptionCount++}else{catchInfo.free()}exceptionLast=ptr;throw ptr}function ___cxa_throw(ptr,type,destructor){var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw ptr}function ___cxa_uncaught_exceptions(){return uncaughtExceptionCount}function setErrNo(value){HEAP32[___errno_location()>>2]=value;return value}var PATH={splitPath:function(filename){var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:function(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:function(path){var isAbsolute=path.charAt(0)==="/",trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:function(path){var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:function(path){if(path==="/")return"/";path=PATH.normalize(path);path=path.replace(/\/$/,"");var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},extname:function(path){return PATH.splitPath(path)[3]},join:function(){var paths=Array.prototype.slice.call(arguments,0);return PATH.normalize(paths.join("/"))},join2:function(l,r){return PATH.normalize(l+"/"+r)}};function getRandomDevice(){if(typeof crypto==="object"&&typeof crypto["getRandomValues"]==="function"){var randomBuffer=new Uint8Array(1);return function(){crypto.getRandomValues(randomBuffer);return randomBuffer[0]}}else if(ENVIRONMENT_IS_NODE){try{var crypto_module=require("crypto");return function(){return crypto_module["randomBytes"](1)[0]}}catch(e){}}return function(){abort("randomDevice")}}var PATH_FS={resolve:function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:FS.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:function(from,to){from=PATH_FS.resolve(from).substr(1);to=PATH_FS.resolve(to).substr(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i0){result=buf.slice(0,bytesRead).toString("utf-8")}else{result=null}}else if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else if(typeof readline=="function"){result=readline();if(result!==null){result+="\n"}}if(!result){return null}tty.input=intArrayFromString(result,true)}return tty.input.shift()},put_char:function(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){out(UTF8ArrayToString(tty.output,0));tty.output=[]}}},default_tty1_ops:{put_char:function(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output,0));tty.output=[]}}}};function mmapAlloc(size){var alignedSize=alignMemory(size,65536);var ptr=_malloc(alignedSize);while(size=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage:function(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr:function(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.timestamp);attr.mtime=new Date(node.timestamp);attr.ctime=new Date(node.timestamp);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr:function(node,attr){if(attr.mode!==undefined){node.mode=attr.mode}if(attr.timestamp!==undefined){node.timestamp=attr.timestamp}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup:function(parent,name){throw FS.genericErrors[44]},mknod:function(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename:function(old_node,new_dir,new_name){if(FS.isDir(old_node.mode)){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}}delete old_node.parent.contents[old_node.name];old_node.parent.timestamp=Date.now();old_node.name=new_name;new_dir.contents[new_name]=old_node;new_dir.timestamp=old_node.parent.timestamp;old_node.parent=new_dir},unlink:function(parent,name){delete parent.contents[name];parent.timestamp=Date.now()},rmdir:function(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.timestamp=Date.now()},readdir:function(node){var entries=[".",".."];for(var key in node.contents){if(!node.contents.hasOwnProperty(key)){continue}entries.push(key)}return entries},symlink:function(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink:function(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read:function(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i0||position+length8){throw new FS.ErrnoError(32)}var parts=PATH.normalizeArray(path.split("/").filter(function(p){return!!p}),false);var current=FS.root;var current_path="/";for(var i=0;i40){throw new FS.ErrnoError(32)}}}}return{path:current_path,node:current}},getPath:function(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?mount+"/"+path:mount+path}path=path?node.name+"/"+path:node.name;node=node.parent}},hashName:function(parentid,name){var hash=0;for(var i=0;i>>0)%FS.nameTable.length},hashAddNode:function(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode:function(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode:function(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode,parent)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode:function(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode:function(node){FS.hashRemoveNode(node)},isRoot:function(node){return node===node.parent},isMountpoint:function(node){return!!node.mounted},isFile:function(mode){return(mode&61440)===32768},isDir:function(mode){return(mode&61440)===16384},isLink:function(mode){return(mode&61440)===40960},isChrdev:function(mode){return(mode&61440)===8192},isBlkdev:function(mode){return(mode&61440)===24576},isFIFO:function(mode){return(mode&61440)===4096},isSocket:function(mode){return(mode&49152)===49152},flagModes:{"r":0,"r+":2,"w":577,"w+":578,"a":1089,"a+":1090},modeStringToFlags:function(str){var flags=FS.flagModes[str];if(typeof flags==="undefined"){throw new Error("Unknown file open mode: "+str)}return flags},flagsToPermissionString:function(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions:function(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup:function(dir){var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate:function(dir,name){try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete:function(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen:function(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&512){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},MAX_OPEN_FDS:4096,nextfd:function(fd_start,fd_end){fd_start=fd_start||0;fd_end=fd_end||FS.MAX_OPEN_FDS;for(var fd=fd_start;fd<=fd_end;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStream:function(fd){return FS.streams[fd]},createStream:function(stream,fd_start,fd_end){if(!FS.FSStream){FS.FSStream=function(){};FS.FSStream.prototype={object:{get:function(){return this.node},set:function(val){this.node=val}},isRead:{get:function(){return(this.flags&2097155)!==1}},isWrite:{get:function(){return(this.flags&2097155)!==0}},isAppend:{get:function(){return this.flags&1024}}}}var newStream=new FS.FSStream;for(var p in stream){newStream[p]=stream[p]}stream=newStream;var fd=FS.nextfd(fd_start,fd_end);stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream:function(fd){FS.streams[fd]=null},chrdev_stream_ops:{open:function(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;if(stream.stream_ops.open){stream.stream_ops.open(stream)}},llseek:function(){throw new FS.ErrnoError(70)}},major:function(dev){return dev>>8},minor:function(dev){return dev&255},makedev:function(ma,mi){return ma<<8|mi},registerDevice:function(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:function(dev){return FS.devices[dev]},getMounts:function(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push.apply(check,m.mounts)}return mounts},syncfs:function(populate,callback){if(typeof populate==="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err("warning: "+FS.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work")}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}mounts.forEach(function(mount){if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},mount:function(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type:type,opts:opts,mountpoint:mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount:function(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);Object.keys(FS.nameTable).forEach(function(hash){var current=FS.nameTable[hash];while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}});node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup:function(parent,name){return parent.node_ops.lookup(parent,name)},mknod:function(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name||name==="."||name===".."){throw new FS.ErrnoError(28)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},create:function(path,mode){mode=mode!==undefined?mode:438;mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir:function(path,mode){mode=mode!==undefined?mode:511;mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree:function(path,mode){var dirs=path.split("/");var d="";for(var i=0;ithis.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]};LazyUint8Array.prototype.setDataGetter=function LazyUint8Array_setDataGetter(getter){this.getter=getter};LazyUint8Array.prototype.cacheLength=function LazyUint8Array_cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=function(from,to){if(from>to)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);if(typeof Uint8Array!="undefined")xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}else{return intArrayFromString(xhr.responseText||"",true)}};var lazyArray=this;lazyArray.setDataGetter(function(chunkNum){var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]==="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]==="undefined")throw new Error("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true};if(typeof XMLHttpRequest!=="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;Object.defineProperties(lazyArray,{length:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._length}},chunkSize:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}});var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url:url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};var keys=Object.keys(node.stream_ops);keys.forEach(function(key){var fn=node.stream_ops[key];stream_ops[key]=function forceLoadLazyFile(){FS.forceLoadFile(node);return fn.apply(null,arguments)}});stream_ops.read=function stream_ops_read(stream,buffer,offset,length,position){FS.forceLoadFile(node);var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i>2]=stat.dev;HEAP32[buf+4>>2]=0;HEAP32[buf+8>>2]=stat.ino;HEAP32[buf+12>>2]=stat.mode;HEAP32[buf+16>>2]=stat.nlink;HEAP32[buf+20>>2]=stat.uid;HEAP32[buf+24>>2]=stat.gid;HEAP32[buf+28>>2]=stat.rdev;HEAP32[buf+32>>2]=0;tempI64=[stat.size>>>0,(tempDouble=stat.size,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>2]=tempI64[0],HEAP32[buf+44>>2]=tempI64[1];HEAP32[buf+48>>2]=4096;HEAP32[buf+52>>2]=stat.blocks;HEAP32[buf+56>>2]=stat.atime.getTime()/1e3|0;HEAP32[buf+60>>2]=0;HEAP32[buf+64>>2]=stat.mtime.getTime()/1e3|0;HEAP32[buf+68>>2]=0;HEAP32[buf+72>>2]=stat.ctime.getTime()/1e3|0;HEAP32[buf+76>>2]=0;tempI64=[stat.ino>>>0,(tempDouble=stat.ino,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+80>>2]=tempI64[0],HEAP32[buf+84>>2]=tempI64[1];return 0},doMsync:function(addr,stream,len,flags,offset){var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},doMkdir:function(path,mode){path=PATH.normalize(path);if(path[path.length-1]==="/")path=path.substr(0,path.length-1);FS.mkdir(path,mode,0);return 0},doMknod:function(path,mode,dev){switch(mode&61440){case 32768:case 8192:case 24576:case 4096:case 49152:break;default:return-28}FS.mknod(path,mode,dev);return 0},doReadlink:function(path,buf,bufsize){if(bufsize<=0)return-28;var ret=FS.readlink(path);var len=Math.min(bufsize,lengthBytesUTF8(ret));var endChar=HEAP8[buf+len];stringToUTF8(ret,buf,bufsize+1);HEAP8[buf+len]=endChar;return len},doAccess:function(path,amode){if(amode&~7){return-28}var node;var lookup=FS.lookupPath(path,{follow:true});node=lookup.node;if(!node){return-44}var perms="";if(amode&4)perms+="r";if(amode&2)perms+="w";if(amode&1)perms+="x";if(perms&&FS.nodePermissions(node,perms)){return-2}return 0},doDup:function(path,flags,suggestFD){var suggest=FS.getStream(suggestFD);if(suggest)FS.close(suggest);return FS.open(path,flags,0,suggestFD,suggestFD).fd},doReadv:function(stream,iov,iovcnt,offset){var ret=0;for(var i=0;i>2];var len=HEAP32[iov+(i*8+4)>>2];var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2];var len=HEAP32[iov+(i*8+4)>>2];var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr}return ret},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},getStreamFromFD:function(fd){var stream=FS.getStream(fd);if(!stream)throw new FS.ErrnoError(8);return stream},get64:function(low,high){return low}};function ___sys_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=SYSCALLS.get();if(arg<0){return-28}var newStream;newStream=FS.open(stream.path,stream.flags,0,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=SYSCALLS.get();stream.flags|=arg;return 0}case 12:{var arg=SYSCALLS.get();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0;case 16:case 8:return-28;case 9:setErrNo(28);return-1;default:{return-28}}}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:case 21505:{if(!stream.tty)return-59;return 0}case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:{if(!stream.tty)return-59;return 0}case 21519:{if(!stream.tty)return-59;var argp=SYSCALLS.get();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21531:{var argp=SYSCALLS.get();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;return 0}case 21524:{if(!stream.tty)return-59;return 0}default:abort("bad ioctl syscall "+op)}}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_open(path,flags,varargs){SYSCALLS.varargs=varargs;try{var pathname=SYSCALLS.getStr(path);var mode=varargs?SYSCALLS.get():0;var stream=FS.open(pathname,flags,mode);return stream.fd}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_stat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.stat,path,buf)}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}var tupleRegistrations={};function runDestructors(destructors){while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}}function simpleReadValueFromPointer(pointer){return this["fromWireType"](HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var char_0=48;var char_9=57;function makeLegalFunctionName(name){if(undefined===name){return"_unknown"}name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return"_"+name}else{return name}}function createNamedFunction(name,body){name=makeLegalFunctionName(name);return new Function("body","return function "+name+"() {\n"+' "use strict";'+" return body.apply(this, arguments);\n"+"};\n")(body)}function extendError(baseErrorType,errorName){var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return this.name+": "+this.message}};return errorClass}var InternalError=undefined;function throwInternalError(message){throw new InternalError(message)}function whenDependentTypesAreResolved(myTypes,dependentTypes,getTypeConverters){myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i>shift])},destructorFunction:null})}function ClassHandle_isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right}function shallowCopyInternalPointer(o){return{count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType}}function throwInstanceAlreadyDeleted(obj){function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")}var finalizationGroup=false;function detachFinalizer(handle){}function runDestructor($$){if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}}function releaseClassHandle($$){$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}}function attachFinalizer(handle){if("undefined"===typeof FinalizationGroup){attachFinalizer=function(handle){return handle};return handle}finalizationGroup=new FinalizationGroup(function(iter){for(var result=iter.next();!result.done;result=iter.next()){var $$=result.value;if(!$$.ptr){console.warn("object already deleted: "+$$.ptr)}else{releaseClassHandle($$)}}});attachFinalizer=function(handle){finalizationGroup.register(handle,handle.$$,handle.$$);return handle};detachFinalizer=function(handle){finalizationGroup.unregister(handle.$$)};return attachFinalizer(handle)}function ClassHandle_clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}}function ClassHandle_delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}}function ClassHandle_isDeleted(){return!this.$$.ptr}var delayFunction=undefined;var deletionQueue=[];function flushPendingDeletes(){while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}}function ClassHandle_deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}function init_ClassHandle(){ClassHandle.prototype["isAliasOf"]=ClassHandle_isAliasOf;ClassHandle.prototype["clone"]=ClassHandle_clone;ClassHandle.prototype["delete"]=ClassHandle_delete;ClassHandle.prototype["isDeleted"]=ClassHandle_isDeleted;ClassHandle.prototype["deleteLater"]=ClassHandle_deleteLater}function ClassHandle(){}var registeredPointers={};function ensureOverloadTable(proto,methodName,humanName){if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(){if(!proto[methodName].overloadTable.hasOwnProperty(arguments.length)){throwBindingError("Function '"+humanName+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+proto[methodName].overloadTable+")!")}return proto[methodName].overloadTable[arguments.length].apply(this,arguments)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}}function exposePublicSymbol(name,value,numArguments){if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError("Cannot register public name '"+name+"' twice")}ensureOverloadTable(Module,name,name);if(Module.hasOwnProperty(numArguments)){throwBindingError("Cannot register multiple overloads of a function with the same number of arguments ("+numArguments+")!")}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;if(undefined!==numArguments){Module[name].numArguments=numArguments}}}function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}function upcastPointer(ptr,ptrClass,desiredClass){while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError("Expected null or instance of "+desiredClass.name+", got an instance of "+ptrClass.name)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr}function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,__emval_register(function(){clonedHandle["delete"]()}));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupporting sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+handle.$$.ptrType.name+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function RegisteredPointer_getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr}function RegisteredPointer_destructor(ptr){if(this.rawDestructor){this.rawDestructor(ptr)}}function RegisteredPointer_deleteObject(handle){if(handle!==null){handle["delete"]()}}function downcastPointer(ptr,ptrClass,desiredClass){if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)}function getInheritedInstanceCount(){return Object.keys(registeredInstances).length}function getLiveInheritedInstances(){var rv=[];for(var k in registeredInstances){if(registeredInstances.hasOwnProperty(k)){rv.push(registeredInstances[k])}}return rv}function setDelayFunction(fn){delayFunction=fn;if(deletionQueue.length&&delayFunction){delayFunction(flushPendingDeletes)}}function init_embind(){Module["getInheritedInstanceCount"]=getInheritedInstanceCount;Module["getLiveInheritedInstances"]=getLiveInheritedInstances;Module["flushPendingDeletes"]=flushPendingDeletes;Module["setDelayFunction"]=setDelayFunction}var registeredInstances={};function getBasestPointer(class_,ptr){if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr}function getInheritedInstance(class_,ptr){ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]}function makeClassHandle(prototype,record){if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record}}))}function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr:ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}function init_RegisteredPointer(){RegisteredPointer.prototype.getPointee=RegisteredPointer_getPointee;RegisteredPointer.prototype.destructor=RegisteredPointer_destructor;RegisteredPointer.prototype["argPackAdvance"]=8;RegisteredPointer.prototype["readValueFromPointer"]=simpleReadValueFromPointer;RegisteredPointer.prototype["deleteObject"]=RegisteredPointer_deleteObject;RegisteredPointer.prototype["fromWireType"]=RegisteredPointer_fromWireType}function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this["toWireType"]=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this["toWireType"]=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this["toWireType"]=genericPointerToWireType}}function replacePublicSymbol(name,value,numArguments){if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistant public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}}function dynCallLegacy(sig,ptr,args){var f=Module["dynCall_"+sig];return args&&args.length?f.apply(null,[ptr].concat(args)):f.call(null,ptr)}function dynCall(sig,ptr,args){if(sig.includes("j")){return dynCallLegacy(sig,ptr,args)}return wasmTable.get(ptr).apply(null,args)}function getDynCaller(sig,ptr){var argCache=[];return function(){argCache.length=arguments.length;for(var i=0;i0?", ":"")+argsListWired}invokerFnBody+=(returns?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i>2)+i])}return array}function __embind_register_class_class_function(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,fn){var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName=classType.name+"."+methodName;function unboundTypesHandler(){throwUnboundTypeError("Cannot call "+humanName+" due to unbound types",rawArgTypes)}var proto=classType.registeredClass.constructor;if(undefined===proto[methodName]){unboundTypesHandler.argCount=argCount-1;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-1]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));var func=craftInvokerFunction(humanName,invokerArgsArray,null,rawInvoker,fn);if(undefined===proto[methodName].overloadTable){func.argCount=argCount-1;proto[methodName]=func}else{proto[methodName].overloadTable[argCount-1]=func}return[]});return[]})}function validateThis(this_,classType,humanName){if(!(this_ instanceof Object)){throwBindingError(humanName+' with invalid "this": '+this_)}if(!(this_ instanceof classType.registeredClass.constructor)){throwBindingError(humanName+' incompatible with "this" of type '+this_.constructor.name)}if(!this_.$$.ptr){throwBindingError("cannot call emscripten binding method "+humanName+" on deleted object")}return upcastPointer(this_.$$.ptr,this_.$$.ptrType.registeredClass,classType.registeredClass)}function __embind_register_class_class_property(rawClassType,fieldName,rawFieldType,rawFieldPtr,getterSignature,getter,setterSignature,setter){fieldName=readLatin1String(fieldName);getter=embind__requireFunction(getterSignature,getter);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName=classType.name+"."+fieldName;var desc={get:function(){throwUnboundTypeError("Cannot access "+humanName+" due to unbound types",[rawFieldType])},enumerable:true,configurable:true};if(setter){desc.set=function(){throwUnboundTypeError("Cannot access "+humanName+" due to unbound types",[rawFieldType])}}else{desc.set=function(v){throwBindingError(humanName+" is a read-only property")}}Object.defineProperty(classType.registeredClass.constructor,fieldName,desc);whenDependentTypesAreResolved([],[rawFieldType],function(fieldType){fieldType=fieldType[0];var desc={get:function(){return fieldType["fromWireType"](getter(rawFieldPtr))},enumerable:true};if(setter){setter=embind__requireFunction(setterSignature,setter);desc.set=function(v){var destructors=[];setter(rawFieldPtr,fieldType["toWireType"](destructors,v));runDestructors(destructors)}}Object.defineProperty(classType.registeredClass.constructor,fieldName,desc);return[]});return[]})}function __embind_register_class_constructor(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor){assert(argCount>0);var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);var args=[rawConstructor];var destructors=[];whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName="constructor "+classType.name;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError("Cannot register multiple constructors with identical number of parameters ("+(argCount-1)+") for class '"+classType.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!")}classType.registeredClass.constructor_body[argCount-1]=function unboundTypeHandler(){throwUnboundTypeError("Cannot construct "+classType.name+" due to unbound types",rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){classType.registeredClass.constructor_body[argCount-1]=function constructor_body(){if(arguments.length!==argCount-1){throwBindingError(humanName+" called with "+arguments.length+" arguments, expected "+(argCount-1))}destructors.length=0;args.length=argCount;for(var i=1;i4&&0===--emval_handle_array[handle].refcount){emval_handle_array[handle]=undefined;emval_free_list.push(handle)}}function count_emval_handles(){var count=0;for(var i=5;i>1])};case 2:return function(pointer){var heap=signed?HEAP32:HEAPU32;return this["fromWireType"](heap[pointer>>2])};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_enum(rawType,name,size,isSigned){var shift=getShiftFromSize(size);name=readLatin1String(name);function ctor(){}ctor.values={};registerType(rawType,{name:name,constructor:ctor,"fromWireType":function(c){return this.constructor.values[c]},"toWireType":function(destructors,c){return c.value},"argPackAdvance":8,"readValueFromPointer":enumReadValueFromPointer(name,shift,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor)}function requireRegisteredType(rawType,humanName){var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(humanName+" has unknown type "+getTypeName(rawType))}return impl}function __embind_register_enum_value(rawEnumType,name,enumValue){var enumType=requireRegisteredType(rawEnumType,"enum");name=readLatin1String(name);var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(enumType.name+"_"+name,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value}function _embind_repr(v){if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}}function floatReadValueFromPointer(name,shift){switch(shift){case 2:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 3:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError("Unknown float type: "+name)}}function __embind_register_float(rawType,name,size){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(value){return value},"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}return value},"argPackAdvance":8,"readValueFromPointer":floatReadValueFromPointer(name,shift),destructorFunction:null})}function __embind_register_function(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn){var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=readLatin1String(name);rawInvoker=embind__requireFunction(signature,rawInvoker);exposePublicSymbol(name,function(){throwUnboundTypeError("Cannot call "+name+" due to unbound types",argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,function(argTypes){var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn),argCount-1);return[]})}function integerReadValueFromPointer(name,shift,signed){switch(shift){case 0:return signed?function readS8FromPointer(pointer){return HEAP8[pointer]}:function readU8FromPointer(pointer){return HEAPU8[pointer]};case 1:return signed?function readS16FromPointer(pointer){return HEAP16[pointer>>1]}:function readU16FromPointer(pointer){return HEAPU16[pointer>>1]};case 2:return signed?function readS32FromPointer(pointer){return HEAP32[pointer>>2]}:function readU32FromPointer(pointer){return HEAPU32[pointer>>2]};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_integer(primitiveType,name,size,minRange,maxRange){name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var shift=getShiftFromSize(size);var fromWireType=function(value){return value};if(minRange===0){var bitshift=32-8*size;fromWireType=function(value){return value<>>bitshift}}var isUnsignedType=name.includes("unsigned");registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}if(valuemaxRange){throw new TypeError('Passing a number "'+_embind_repr(value)+'" from JS side to C/C++ side to an argument of type "'+name+'", which is outside the valid range ['+minRange+", "+maxRange+"]!")}return isUnsignedType?value>>>0:value|0},"argPackAdvance":8,"readValueFromPointer":integerReadValueFromPointer(name,shift,minRange!==0),destructorFunction:null})}function __embind_register_memory_view(rawType,dataTypeIndex,name){var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){handle=handle>>2;var heap=HEAPU32;var size=heap[handle];var data=heap[handle+1];return new TA(buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":8,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})}function __embind_register_smart_ptr(rawType,rawPointeeType,name,sharingPolicy,getPointeeSignature,rawGetPointee,constructorSignature,rawConstructor,shareSignature,rawShare,destructorSignature,rawDestructor){name=readLatin1String(name);rawGetPointee=embind__requireFunction(getPointeeSignature,rawGetPointee);rawConstructor=embind__requireFunction(constructorSignature,rawConstructor);rawShare=embind__requireFunction(shareSignature,rawShare);rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);whenDependentTypesAreResolved([rawType],[rawPointeeType],function(pointeeType){pointeeType=pointeeType[0];var registeredPointer=new RegisteredPointer(name,pointeeType.registeredClass,false,false,true,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor);return[registeredPointer]})}function __embind_register_std_string(rawType,name){name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var str;if(stdStringIsUTF8){var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr+4,length+1)}else{if(valueIsOfTypeString){for(var i=0;i255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+4+i]=charCode}}else{for(var i=0;i>2];var HEAP=getHeap();var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||HEAP[currentBytePtr>>shift]==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":function(destructors,value){if(!(typeof value==="string")){throwBindingError("Cannot pass non-string to C++ string type "+name)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length>>shift;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:function(ptr){_free(ptr)}})}function __embind_register_value_array(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor){tupleRegistrations[rawType]={name:readLatin1String(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),elements:[]}}function __embind_register_value_array_element(rawTupleType,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){tupleRegistrations[rawTupleType].elements.push({getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})}function __embind_register_void(rawType,name){name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":function(){return undefined},"toWireType":function(destructors,o){return undefined}})}function requireHandle(handle){if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handle_array[handle].value}function __emval_as(handle,returnType,destructorsRef){handle=requireHandle(handle);returnType=requireRegisteredType(returnType,"emval::as");var destructors=[];var rd=__emval_register(destructors);HEAP32[destructorsRef>>2]=rd;return returnType["toWireType"](destructors,handle)}function __emval_lookupTypes(argCount,argTypes){var a=new Array(argCount);for(var i=0;i>2)+i],"parameter "+i)}return a}function __emval_call(handle,argCount,argTypes,argv){handle=requireHandle(handle);var types=__emval_lookupTypes(argCount,argTypes);var args=new Array(argCount);for(var i=0;i4){emval_handle_array[handle].refcount+=1}}function __emval_new_array(){return __emval_register([])}function __emval_new_cstring(v){return __emval_register(getStringOrSymbol(v))}function __emval_new_object(){return __emval_register({})}function __emval_run_destructors(handle){var destructors=emval_handle_array[handle].value;runDestructors(destructors);__emval_decref(handle)}function __emval_set_property(handle,key,value){handle=requireHandle(handle);key=requireHandle(key);value=requireHandle(value);handle[key]=value}function __emval_take_value(type,argv){type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](argv);return __emval_register(v)}function __emval_typeof(handle){handle=requireHandle(handle);return __emval_register(typeof handle)}function _abort(){abort()}var readAsmConstArgsArray=[];function readAsmConstArgs(sigPtr,buf){readAsmConstArgsArray.length=0;var ch;buf>>=2;while(ch=HEAPU8[sigPtr++]){var double=ch<105;if(double&&buf&1)buf++;readAsmConstArgsArray.push(double?HEAPF64[buf++>>1]:HEAP32[buf]);++buf}return readAsmConstArgsArray}function _emscripten_asm_const_int(code,sigPtr,argbuf){var args=readAsmConstArgs(sigPtr,argbuf);return ASM_CONSTS[code].apply(null,args)}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize+33554432/cutDown;var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var ENV={};function getExecutableName(){return thisProgram||"./this.program"}function getEnvStrings(){if(!getEnvStrings.strings){var lang=(typeof navigator==="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={"USER":"web_user","LOGNAME":"web_user","PATH":"/","PWD":"/","HOME":"/home/web_user","LANG":lang,"_":getExecutableName()};for(var x in ENV){env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(x+"="+env[x])}getEnvStrings.strings=strings}return getEnvStrings.strings}function _environ_get(__environ,environ_buf){try{var bufSize=0;getEnvStrings().forEach(function(string,i){var ptr=environ_buf+bufSize;HEAP32[__environ+i*4>>2]=ptr;writeAsciiToMemory(string,ptr);bufSize+=string.length+1});return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _environ_sizes_get(penviron_count,penviron_buf_size){try{var strings=getEnvStrings();HEAP32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(function(string){bufSize+=string.length+1});HEAP32[penviron_buf_size>>2]=bufSize;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=SYSCALLS.doReadv(stream,iov,iovcnt);HEAP32[pnum>>2]=num;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){try{var stream=SYSCALLS.getStreamFromFD(fd);var HIGH_OFFSET=4294967296;var offset=offset_high*HIGH_OFFSET+(offset_low>>>0);var DOUBLE_LIMIT=9007199254740992;if(offset<=-DOUBLE_LIMIT||offset>=DOUBLE_LIMIT){return-61}FS.llseek(stream,offset,whence);tempI64=[stream.position>>>0,(tempDouble=stream.position,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[newOffset>>2]=tempI64[0],HEAP32[newOffset+4>>2]=tempI64[1];if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=SYSCALLS.doWritev(stream,iov,iovcnt);HEAP32[pnum>>2]=num;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _getTempRet0(){return getTempRet0()}function _llvm_eh_typeid_for(type){return type}function _setTempRet0(val){setTempRet0(val)}function __isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}function __arraySum(array,index){var sum=0;for(var i=0;i<=index;sum+=array[i++]){}return sum}var __MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31];var __MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31];function __addDays(date,days){var newDate=new Date(date.getTime());while(days>0){var leap=__isLeapYear(newDate.getFullYear());var currentMonth=newDate.getMonth();var daysInCurrentMonth=(leap?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR)[currentMonth];if(days>daysInCurrentMonth-newDate.getDate()){days-=daysInCurrentMonth-newDate.getDate()+1;newDate.setDate(1);if(currentMonth<11){newDate.setMonth(currentMonth+1)}else{newDate.setMonth(0);newDate.setFullYear(newDate.getFullYear()+1)}}else{newDate.setDate(newDate.getDate()+days);return newDate}}return newDate}function _strftime(s,maxsize,format,tm){var tm_zone=HEAP32[tm+40>>2];var date={tm_sec:HEAP32[tm>>2],tm_min:HEAP32[tm+4>>2],tm_hour:HEAP32[tm+8>>2],tm_mday:HEAP32[tm+12>>2],tm_mon:HEAP32[tm+16>>2],tm_year:HEAP32[tm+20>>2],tm_wday:HEAP32[tm+24>>2],tm_yday:HEAP32[tm+28>>2],tm_isdst:HEAP32[tm+32>>2],tm_gmtoff:HEAP32[tm+36>>2],tm_zone:tm_zone?UTF8ToString(tm_zone):""};var pattern=UTF8ToString(format);var EXPANSION_RULES_1={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var rule in EXPANSION_RULES_1){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_1[rule])}var WEEKDAYS=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];var MONTHS=["January","February","March","April","May","June","July","August","September","October","November","December"];function leadingSomething(value,digits,character){var str=typeof value==="number"?value.toString():value||"";while(str.length0?1:0}var compare;if((compare=sgn(date1.getFullYear()-date2.getFullYear()))===0){if((compare=sgn(date1.getMonth()-date2.getMonth()))===0){compare=sgn(date1.getDate()-date2.getDate())}}return compare}function getFirstWeekStartDate(janFourth){switch(janFourth.getDay()){case 0:return new Date(janFourth.getFullYear()-1,11,29);case 1:return janFourth;case 2:return new Date(janFourth.getFullYear(),0,3);case 3:return new Date(janFourth.getFullYear(),0,2);case 4:return new Date(janFourth.getFullYear(),0,1);case 5:return new Date(janFourth.getFullYear()-1,11,31);case 6:return new Date(janFourth.getFullYear()-1,11,30)}}function getWeekBasedYear(date){var thisDate=__addDays(new Date(date.tm_year+1900,0,1),date.tm_yday);var janFourthThisYear=new Date(thisDate.getFullYear(),0,4);var janFourthNextYear=new Date(thisDate.getFullYear()+1,0,4);var firstWeekStartThisYear=getFirstWeekStartDate(janFourthThisYear);var firstWeekStartNextYear=getFirstWeekStartDate(janFourthNextYear);if(compareByDay(firstWeekStartThisYear,thisDate)<=0){if(compareByDay(firstWeekStartNextYear,thisDate)<=0){return thisDate.getFullYear()+1}else{return thisDate.getFullYear()}}else{return thisDate.getFullYear()-1}}var EXPANSION_RULES_2={"%a":function(date){return WEEKDAYS[date.tm_wday].substring(0,3)},"%A":function(date){return WEEKDAYS[date.tm_wday]},"%b":function(date){return MONTHS[date.tm_mon].substring(0,3)},"%B":function(date){return MONTHS[date.tm_mon]},"%C":function(date){var year=date.tm_year+1900;return leadingNulls(year/100|0,2)},"%d":function(date){return leadingNulls(date.tm_mday,2)},"%e":function(date){return leadingSomething(date.tm_mday,2," ")},"%g":function(date){return getWeekBasedYear(date).toString().substring(2)},"%G":function(date){return getWeekBasedYear(date)},"%H":function(date){return leadingNulls(date.tm_hour,2)},"%I":function(date){var twelveHour=date.tm_hour;if(twelveHour==0)twelveHour=12;else if(twelveHour>12)twelveHour-=12;return leadingNulls(twelveHour,2)},"%j":function(date){return leadingNulls(date.tm_mday+__arraySum(__isLeapYear(date.tm_year+1900)?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR,date.tm_mon-1),3)},"%m":function(date){return leadingNulls(date.tm_mon+1,2)},"%M":function(date){return leadingNulls(date.tm_min,2)},"%n":function(){return"\n"},"%p":function(date){if(date.tm_hour>=0&&date.tm_hour<12){return"AM"}else{return"PM"}},"%S":function(date){return leadingNulls(date.tm_sec,2)},"%t":function(){return"\t"},"%u":function(date){return date.tm_wday||7},"%U":function(date){var janFirst=new Date(date.tm_year+1900,0,1);var firstSunday=janFirst.getDay()===0?janFirst:__addDays(janFirst,7-janFirst.getDay());var endDate=new Date(date.tm_year+1900,date.tm_mon,date.tm_mday);if(compareByDay(firstSunday,endDate)<0){var februaryFirstUntilEndMonth=__arraySum(__isLeapYear(endDate.getFullYear())?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR,endDate.getMonth()-1)-31;var firstSundayUntilEndJanuary=31-firstSunday.getDate();var days=firstSundayUntilEndJanuary+februaryFirstUntilEndMonth+endDate.getDate();return leadingNulls(Math.ceil(days/7),2)}return compareByDay(firstSunday,janFirst)===0?"01":"00"},"%V":function(date){var janFourthThisYear=new Date(date.tm_year+1900,0,4);var janFourthNextYear=new Date(date.tm_year+1901,0,4);var firstWeekStartThisYear=getFirstWeekStartDate(janFourthThisYear);var firstWeekStartNextYear=getFirstWeekStartDate(janFourthNextYear);var endDate=__addDays(new Date(date.tm_year+1900,0,1),date.tm_yday);if(compareByDay(endDate,firstWeekStartThisYear)<0){return"53"}if(compareByDay(firstWeekStartNextYear,endDate)<=0){return"01"}var daysDifference;if(firstWeekStartThisYear.getFullYear()=0;off=Math.abs(off)/60;off=off/60*100+off%60;return(ahead?"+":"-")+String("0000"+off).slice(-4)},"%Z":function(date){return date.tm_zone},"%%":function(){return"%"}};for(var rule in EXPANSION_RULES_2){if(pattern.includes(rule)){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_2[rule](date))}}var bytes=intArrayFromString(pattern,false);if(bytes.length>maxsize){return 0}writeArrayToMemory(bytes,s);return bytes.length-1}function _strftime_l(s,maxsize,format,tm){return _strftime(s,maxsize,format,tm)}var FSNode=function(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.mounted=null;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.node_ops={};this.stream_ops={};this.rdev=rdev};var readMode=292|73;var writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(val){val?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(val){val?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}});FS.FSNode=FSNode;FS.staticInit();Module["FS_createPath"]=FS.createPath;Module["FS_createDataFile"]=FS.createDataFile;Module["FS_createPreloadedFile"]=FS.createPreloadedFile;Module["FS_createLazyFile"]=FS.createLazyFile;Module["FS_createDevice"]=FS.createDevice;Module["FS_unlink"]=FS.unlink;InternalError=Module["InternalError"]=extendError(Error,"InternalError");embind_init_charCodes();BindingError=Module["BindingError"]=extendError(Error,"BindingError");init_ClassHandle();init_RegisteredPointer();init_embind();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");init_emval();function intArrayFromString(stringy,dontAddNull,length){var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}var asmLibraryArg={"x":___assert_fail,"r":___cxa_allocate_exception,"n":___cxa_begin_catch,"y":___cxa_end_catch,"b":___cxa_find_matching_catch_2,"i":___cxa_find_matching_catch_3,"Fa":___cxa_find_matching_catch_4,"s":___cxa_free_exception,"fa":___cxa_rethrow,"D":___cxa_throw,"qa":___cxa_uncaught_exceptions,"c":___resumeException,"_":___sys_fcntl64,"wa":___sys_ioctl,"xa":___sys_open,"ta":___sys_stat64,"Na":__embind_finalize_value_array,"ha":__embind_register_bigint,"za":__embind_register_bool,"t":__embind_register_class,"z":__embind_register_class_class_function,"o":__embind_register_class_class_property,"w":__embind_register_class_constructor,"h":__embind_register_class_function,"M":__embind_register_class_property,"N":__embind_register_constant,"ya":__embind_register_emval,"Ha":__embind_register_enum,"Ga":__embind_register_enum_value,"ba":__embind_register_float,"C":__embind_register_function,"G":__embind_register_integer,"F":__embind_register_memory_view,"q":__embind_register_smart_ptr,"ca":__embind_register_std_string,"U":__embind_register_std_wstring,"ea":__embind_register_value_array,"S":__embind_register_value_array_element,"Aa":__embind_register_void,"K":__emval_as,"Oa":__emval_call,"R":__emval_call_void_method,"Z":__emval_decref,"Q":__emval_get_method_caller,"Ma":__emval_get_property,"aa":__emval_incref,"Qa":__emval_new_array,"La":__emval_new_cstring,"Ia":__emval_new_object,"Ka":__emval_run_destructors,"Pa":__emval_set_property,"A":__emval_take_value,"Ja":__emval_typeof,"oa":_abort,"W":_emscripten_asm_const_int,"na":_emscripten_memcpy_big,"T":_emscripten_resize_heap,"ra":_environ_get,"sa":_environ_sizes_get,"$":_fd_close,"va":_fd_read,"ga":_fd_seek,"ua":_fd_write,"a":_getTempRet0,"Ba":invoke_di,"V":invoke_fi,"Ea":invoke_fifii,"ka":invoke_fii,"ma":invoke_fiii,"u":invoke_i,"g":invoke_ii,"Ca":invoke_iid,"Da":invoke_iif,"e":invoke_iii,"j":invoke_iiii,"v":invoke_iiiii,"Y":invoke_iiiiid,"I":invoke_iiiiii,"H":invoke_iiiiiii,"X":invoke_iiiiiiii,"P":invoke_iiiiiiiiiiii,"k":invoke_v,"l":invoke_vi,"la":invoke_vid,"da":invoke_vif,"d":invoke_vii,"ja":invoke_viif,"f":invoke_viii,"m":invoke_viiii,"p":invoke_viiiii,"J":invoke_viiiiii,"E":invoke_viiiiiii,"L":invoke_viiiiiiiiii,"O":invoke_viiiiiiiiiiiiiii,"B":_llvm_eh_typeid_for,"ia":_setTempRet0,"pa":_strftime_l};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["Sa"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["Ta"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["Va"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["Wa"]).apply(null,arguments)};var ___getTypeName=Module["___getTypeName"]=function(){return(___getTypeName=Module["___getTypeName"]=Module["asm"]["Xa"]).apply(null,arguments)};var ___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=function(){return(___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=Module["asm"]["Ya"]).apply(null,arguments)};var stackSave=Module["stackSave"]=function(){return(stackSave=Module["stackSave"]=Module["asm"]["Za"]).apply(null,arguments)};var stackRestore=Module["stackRestore"]=function(){return(stackRestore=Module["stackRestore"]=Module["asm"]["_a"]).apply(null,arguments)};var stackAlloc=Module["stackAlloc"]=function(){return(stackAlloc=Module["stackAlloc"]=Module["asm"]["$a"]).apply(null,arguments)};var _setThrew=Module["_setThrew"]=function(){return(_setThrew=Module["_setThrew"]=Module["asm"]["ab"]).apply(null,arguments)};var ___cxa_can_catch=Module["___cxa_can_catch"]=function(){return(___cxa_can_catch=Module["___cxa_can_catch"]=Module["asm"]["bb"]).apply(null,arguments)};var ___cxa_is_pointer_type=Module["___cxa_is_pointer_type"]=function(){return(___cxa_is_pointer_type=Module["___cxa_is_pointer_type"]=Module["asm"]["cb"]).apply(null,arguments)};var dynCall_viijii=Module["dynCall_viijii"]=function(){return(dynCall_viijii=Module["dynCall_viijii"]=Module["asm"]["db"]).apply(null,arguments)};var dynCall_jiji=Module["dynCall_jiji"]=function(){return(dynCall_jiji=Module["dynCall_jiji"]=Module["asm"]["eb"]).apply(null,arguments)};var dynCall_iiiiij=Module["dynCall_iiiiij"]=function(){return(dynCall_iiiiij=Module["dynCall_iiiiij"]=Module["asm"]["fb"]).apply(null,arguments)};var dynCall_iiiiijj=Module["dynCall_iiiiijj"]=function(){return(dynCall_iiiiijj=Module["dynCall_iiiiijj"]=Module["asm"]["gb"]).apply(null,arguments)};var dynCall_iiiiiijj=Module["dynCall_iiiiiijj"]=function(){return(dynCall_iiiiiijj=Module["dynCall_iiiiiijj"]=Module["asm"]["hb"]).apply(null,arguments)};function invoke_ii(index,a1){var sp=stackSave();try{return wasmTable.get(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viii(index,a1,a2,a3){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vii(index,a1,a2){var sp=stackSave();try{wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiii(index,a1,a2,a3,a4){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iii(index,a1,a2){var sp=stackSave();try{return wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiii(index,a1,a2,a3,a4){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiii(index,a1,a2,a3){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vi(index,a1){var sp=stackSave();try{wasmTable.get(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_i(index){var sp=stackSave();try{return wasmTable.get(index)()}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_v(index){var sp=stackSave();try{wasmTable.get(index)()}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vif(index,a1,a2){var sp=stackSave();try{wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fifii(index,a1,a2,a3,a4){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iif(index,a1,a2){var sp=stackSave();try{return wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iid(index,a1,a2){var sp=stackSave();try{return wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fi(index,a1){var sp=stackSave();try{return wasmTable.get(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_di(index,a1){var sp=stackSave();try{return wasmTable.get(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fiii(index,a1,a2,a3){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vid(index,a1,a2){var sp=stackSave();try{wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fii(index,a1,a2){var sp=stackSave();try{return wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiid(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiiii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viif(index,a1,a2,a3){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["FS_createPath"]=FS.createPath;Module["FS_createDataFile"]=FS.createDataFile;Module["FS_createPreloadedFile"]=FS.createPreloadedFile;Module["FS_createLazyFile"]=FS.createLazyFile;Module["FS_createDevice"]=FS.createDevice;Module["FS_unlink"]=FS.unlink;var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();var postRegistrations=[];function onModuleReady(callback){postRegistrations.push(callback)}Module.onRuntimeInitialized=function(){for(var callback of postRegistrations){callback()}};(function(){var nodeFs;var nodePath;var nodeProcess;var pathSep;var wasmPathSep="/";var ENVIRONMENT_IS_WEB;var ENVIRONMENT_IS_NODE;var PATH_LIST_SEPARATOR=";";var callId=0;var MAX_CALL_ID=99999;function removeDuplicates(array){var seen={};return array.filter(function(item){return seen.hasOwnProperty(item)?false:seen[item]=true})}function createFilePath(fileName,filePath,sep=pathSep){var pathSlash=filePath.endsWith(sep);var fileSlash=fileName.startsWith(sep);var path;if(pathSlash||fileSlash){if(pathSlash&&fileSlash){path=filePath.substring(0,filePath.length-1)+fileName}else{path=filePath+fileName}}else{path=filePath+sep+fileName}return path}function fetchXml(fileName,searchPaths){var i=0;function fetchHandler(){var filePath=createFilePath(fileName,searchPaths[i++]);return fetch(filePath).then(function(response){if(response.status===200){return response.text().then(function(data){var url=new URL(response.url);var filePath=url.pathname.substring(1);filePath=filePath.replace(new RegExp(pathSep,"g"),wasmPathSep);return{data:data,filePath:filePath,fullPath:url.origin+url.pathname}})}else if(i/g;var matches=file.matchAll(includeRegex);var includes=[];for(var match of matches){includes.push(match[1])}return includes}function loadFile(fileToLoad,searchPaths){var promise;if(ENVIRONMENT_IS_WEB){promise=fetchXml(fileToLoad,searchPaths)}else if(ENVIRONMENT_IS_NODE){promise=loadXml(fileToLoad,searchPaths)}else{throw new Error("Unknown environment!")}return promise}function trackPath(path,filesUploaded,isFile=false){if(isFile){if(!filesUploaded.files){filesUploaded.files=[]}filesUploaded.files.push(path)}else{if(!filesUploaded.folders){filesUploaded.folders=[]}filesUploaded.folders.splice(0,0,path)}}function createInWasm(file,data,filesUploaded,wasmRootFolder,isFile=true){var folders;if(isFile){folders=file.substring(1,file.lastIndexOf(wasmPathSep)).split(wasmPathSep)}else{folders=file.substring(wasmRootFolder.length).split(wasmPathSep)}var folder=wasmRootFolder;for(var i=1;i-1?pos+1:0);var element=document.createElement("a");element.setAttribute("href","data:text/plain;charset=utf-8,"+encodeURIComponent(content));element.setAttribute("download",fileName);element.style.display="none";document.body.appendChild(element);element.click();document.body.removeChild(element)}}onModuleReady(function(){ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";if(ENVIRONMENT_IS_WEB){pathSep="/"}if(ENVIRONMENT_IS_NODE){nodeFs=require("fs");nodePath=require("path");nodeProcess=require("process");pathSep=nodePath.sep}function _readFromXmlString(doc,str,searchPath,readOptions,filesLoaded=[],initialFilePath=""){var wasmRootFolder="/readFromXml"+callId++%MAX_CALL_ID;var searchPaths=prepareSearchPaths(searchPath);try{FS.mkdir(wasmRootFolder)}catch(e){throw new Error("Failed to create folder in WASM FS.")}var includes=[];if(!readOptions||readOptions.readXIncludes){includes=getIncludes(str)}var filesUploaded={files:[],folders:[]};var wasmCwd=getWasmCwd(wasmRootFolder);var initialFileName=wasmCwd+"/ChosenToHopefullyNotClashWithAnyOtherFile123";if(initialFilePath){var sep=pathSep==="\\"?"\\\\":pathSep;initialFileName=initialFilePath.replace(new RegExp(sep,"g"),wasmPathSep);initialFileName=createFilePath(initialFileName,wasmRootFolder,wasmPathSep);createInWasm(wasmCwd,null,filesUploaded,wasmRootFolder,false)}createInWasm(initialFileName,str,filesUploaded,wasmRootFolder);function loadFiles(filesLoadedList,fileList,pathsList){var promises=[Promise.resolve()];for(var fileToLoad of fileList){var filesLoadedCopy=filesLoadedList.slice();var searchPathsCopy=pathsList.slice();var promise=loadFile(fileToLoad,searchPathsCopy).then(function(result){if(filesLoadedCopy.includes(result.fullPath)){throw new Error("Cycle detected!\n"+filesLoadedCopy.join("\n-> ")+"\n-> "+result.fullPath)}filesLoadedCopy.push(result.fullPath);var pos=result.fullPath.lastIndexOf(pathSep);var path=result.fullPath.substring(0,pos>-1?pos:0);if(!searchPathsCopy.includes(path)){searchPathsCopy.splice(0,0,path)}var includes=getIncludes(result.data);var wasmPath=createFilePath(result.filePath,wasmRootFolder,wasmPathSep);if(!filesUploaded.files.includes(wasmPath)){createInWasm(wasmPath,result.data,filesUploaded,wasmRootFolder)}return loadFiles(filesLoadedCopy,includes,searchPathsCopy)});promises.push(promise)}return Promise.all(promises)}return loadFiles(filesLoaded,includes,searchPaths).then(function(){var wasmSearchPath=getWasmSearchPath(searchPath,wasmRootFolder);FS.chdir(wasmCwd);try{var searchPathEnv=Module.getEnviron(Module.MATERIALX_SEARCH_PATH_ENV_VAR);if(searchPathEnv){var wasmSearchPathEnv=makeWasmAbsolute(searchPathEnv,wasmRootFolder);Module.setEnviron(Module.MATERIALX_SEARCH_PATH_ENV_VAR,wasmSearchPathEnv)}Module._readFromXmlFile(doc,initialFileName,wasmSearchPath,readOptions);if(searchPathEnv){Module.setEnviron(Module.MATERIALX_SEARCH_PATH_ENV_VAR,searchPathEnv)}}catch(errPtr){throw new Error("Failed to read MaterialX files from WASM FS: "+Module.getExceptionMessage(errPtr))}try{for(var file of filesUploaded.files){FS.unlink(file)}FS.chdir("/");for(var folder of filesUploaded.folders){FS.rmdir(folder)}FS.rmdir(wasmRootFolder)}catch(e){throw new Error("Failed to delete temporary files from WASM FS.")}})}Module.readFromXmlString=function(doc,str,searchPath="",readOptions=null){if(arguments.length<2||arguments.length>4){throw new Error("Function readFromXmlString called with an invalid number of arguments ("+arguments.length+") - expects 2 to 4!")}return _readFromXmlString(doc,str,searchPath,readOptions)};Module.readFromXmlFile=function(doc,fileName,searchPath="",readOptions=null){if(arguments.length<2||arguments.length>4){throw new Error("Function readFromXmlFile called with an invalid number of arguments ("+arguments.length+") - expects 2 to 4!")}var searchPaths=prepareSearchPaths(searchPath);return loadFile(fileName,searchPaths).then(function(result){var filesLoaded=[result.fullPath];var pos=result.fullPath.lastIndexOf(pathSep);var path=result.fullPath.substring(0,pos>-1?pos:0);searchPath=searchPath.concat(PATH_LIST_SEPARATOR,path);return _readFromXmlString(doc,result.data,searchPath,readOptions,filesLoaded,result.filePath)})};Module.writeToXmlFile=function(doc,fileName,writeOptions=null){if(arguments.length<2||arguments.length>3){throw new Error("Function writeToXmlFile called with an invalid number of arguments ("+arguments.length+") - expects 2 to 3!")}var file=Module.writeToXmlString(doc,writeOptions);storeFileToDisk(fileName,file)};Module.exportToXmlFile=function(doc,fileName,exportOptions=null){if(arguments.length<2||arguments.length>3){throw new Error("Function exportToXmlFile called with an invalid number of arguments ("+arguments.length+") - expects 2 to 3!")}var file=Module.exportToXmlString(doc,exportOptions);storeFileToDisk(fileName,file)}})})(); + + + return MaterialX.ready +} +); +})(); +if (typeof exports === 'object' && typeof module === 'object') + module.exports = MaterialX; +else if (typeof define === 'function' && define['amd']) + define([], function() { return MaterialX; }); +else if (typeof exports === 'object') + exports["MaterialX"] = MaterialX; diff --git a/JsMaterialXCore.wasm b/JsMaterialXCore.wasm new file mode 100644 index 0000000000..a96355f9ee Binary files /dev/null and b/JsMaterialXCore.wasm differ diff --git a/JsMaterialXGenShader.data b/JsMaterialXGenShader.data new file mode 100644 index 0000000000..073ffadde8 --- /dev/null +++ b/JsMaterialXGenShader.data @@ -0,0 +1,26202 @@ +if (MATERIALX_OSL_LEGACY_CLOSURES) + set(PBRLIB_SUFFIX "legacy") +else() + set(PBRLIB_SUFFIX "mtlx") +endif() + +if(NOT SKBUILD) + install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ + DESTINATION "${MATERIALX_INSTALL_STDLIB_PATH}" + PATTERN "CMakeLists.txt" EXCLUDE + PATTERN "pbrlib_genosl_impl.*" EXCLUDE) + install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/pbrlib/genosl/pbrlib_genosl_impl.${PBRLIB_SUFFIX}" + DESTINATION "${MATERIALX_INSTALL_STDLIB_PATH}/pbrlib/genosl/" RENAME pbrlib_genosl_impl.mtlx) +endif() + +set(MATERIALX_PYTHON_LIBRARIES_PATH "${MATERIALX_PYTHON_FOLDER_NAME}/${MATERIALX_INSTALL_STDLIB_PATH}") +if(SKBUILD) + set(MATERIALX_PYTHON_LIBRARIES_PATH "${SKBUILD_PLATLIB_DIR}/MaterialX/libraries") +endif() + +if(MATERIALX_BUILD_PYTHON) + install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ + DESTINATION "${MATERIALX_PYTHON_LIBRARIES_PATH}" + PATTERN "CMakeLists.txt" EXCLUDE + PATTERN "pbrlib_genosl_impl.*" EXCLUDE) + install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/pbrlib/genosl/pbrlib_genosl_impl.${PBRLIB_SUFFIX}" + DESTINATION "${MATERIALX_PYTHON_LIBRARIES_PATH}/pbrlib/genosl/" RENAME pbrlib_genosl_impl.mtlx) +endif() +# MaterialX Data Libraries + +This folder contains the standard data libraries for MaterialX, providing declarations and graph definitions for the MaterialX nodes, and source code for all supported shader generators. + +## Standard Pattern Library +- [stdlib](stdlib) + - [stdlib_defs.mtlx](stdlib/stdlib_defs.mtlx) : Nodedef declarations. + - [stdlib_ng.mtlx](stdlib/stdlib_ng.mtlx) : Nodegraph definitions. + - [genglsl](stdlib/genglsl): GLSL language support. + - [lib](stdlib/genglsl/lib) : Shader utility files. + - [stdlib_genglsl_impl.mtlx](stdlib/genglsl/stdlib_genglsl_impl.mtlx) : Mapping from declarations to implementations. + - [genosl](stdlib/genosl): OSL language support. + - [lib](stdlib/genosl/lib) : Shader utility files. + - [stdlib_genosl_impl.mtlx](stdlib/genosl/stdlib_genosl_impl.mtlx) : Mapping from declarations to implementations. + - [genmdl](stdlib/genmdl): MDL language support. + - [stdlib_genmdl_impl.mtlx](stdlib/genmdl/stdlib_genmdl_impl.mtlx) : Mapping from declarations to implementations. + - Additional MaterialX support libraries for MDL are located in the [source/MaterialXGenMdl/mdl/materialx](../source/MaterialXGenMdl/mdl/materialx) package folder + - [genmsl](stdlib/genmsl): MSL language support. + - [lib](stdlib/genmsl/lib) : Shader utility files. + - [stdlib_genmsl_impl.mtlx](stdlib/genmsl/stdlib_genmsl_impl.mtlx) : Mapping from declarations to implementations. + +## Physically Based Shading Library +- [pbrlib](pbrlib) + - [pbrlib_defs.mtlx](pbrlib/pbrlib_defs.mtlx) : Nodedef declarations. + - [pbrlib_ng.mtlx](pbrlib/pbrlib_ng.mtlx) : Nodegraph definitions. + - [genglsl](pbrlib/genglsl) : GLSL language support + - [lib](pbrlib/genglsl/lib) : Shader utility files. + - [pbrlib_genglsl_impl.mtlx](pbrlib/genglsl/pbrlib_genglsl_impl.mtlx) : Mapping from declarations to implementations. + - [genosl](pbrlib/genosl) : OSL language support + - [lib](pbrlib/genosl/lib) : Shader utility files. + - [pbrlib_genosl_impl.mtlx](pbrlib/genosl/pbrlib_genosl_impl.mtlx) : Mapping from declarations to implementations. + - [genmdl](pbrlib/genmdl) : MDL language support + - [pbrlib_genmdl_impl.mtlx](pbrlib/genmdl/pbrlib_genmdl_impl.mtlx) : Mapping from declarations to implementations. + - [genmsl](pbrlib/genmsl) : MSL language support + - [pbrlib_genmsl_impl.mtlx](pbrlib/genmsl/pbrlib_genmsl_impl.mtlx) : Mapping from declarations to implementations. + +## BxDF Graph Library +- [bxdf](bxdf) + - [standard_surface.mtlx](bxdf/standard_surface.mtlx) : Graph definition of the [Autodesk Standard Surface](https://autodesk.github.io/standard-surface/) shading model. + - [gltf_pbr.mtlx](bxdf/gltf_pbr.mtlx) : Graph definition of the [glTF PBR](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#appendix-b-brdf-implementation) shading model. + - [usd_preview_surface.mtlx](bxdf/usd_preview_surface.mtlx) : Graph definition of the [UsdPreviewSurface](https://openusd.org/release/spec_usdpreviewsurface.html) shading model. + - [lama](bxdf/lama) : Graph definitions of the [MaterialX Lama](https://rmanwiki.pixar.com/display/REN24/MaterialX+Lama) node set. + +## Color Management Library +- MaterialX shader generation natively supports a small set of common spaces for input colors, with all color transforms implemented as language-independent MaterialX graphs.The canonical definitions of these color transforms may be found in the OpenColorIO configuration for [ACES 1.2](https://github.com/colour-science/OpenColorIO-Configs/tree/feature/aces-1.2-config/aces_1.2). + - lin_rec709 + - g18_rec709 + - g22_rec709 + - rec709_display + - acescg (lin_ap1) + - g22_ap1 + - srgb_texture + - lin_adobergb + - adobergb + - srgb_displayp3 + - lin_displayp3 +- [cmlib](cmlib) + - [cmlib_defs.mtlx](cmlib/cmlib_defs.mtlx) : Nodedef declarations. + - [cmlib_ng.mtlx](cmlib/cmlib_ng.mtlx) : Nodegraph definitions. + +## Target Definitions +- Each target implementation requires a target definition for declaration / implementation correspondence to work. +- The [targets](targets) folder contains definition files for the following core targets: + - GLSL : `genglsl` + - OSL : `genosl` + - MDL : `genmdl` + - MSL : `genmsl` +- Any additional target files should be added under this folder and loaded in as required. + +### Target Support +- GLSL target support is for version 4.0 or higher. +- OSL target support is for version 1.9.10 or higher. +- MDL target support is for version 1.7. +- Basic GLSL and MSL `lightshader` node definitions and implementations are provided for the following light types: + - point, directional, spot +- Shader generation does not currently support: + - `ambientocclusion` node. + - `arrayappend` node. + - `curveadjust` node. + - `displacementshader` and `volumeshader` nodes for hardware shading targets (GLSL, MSL). + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +void mx_spot_light(LightData light, float3 position, thread lightshader& result) +{ + result.direction = light.position - position; + float distance = length(result.direction) + M_FLOAT_EPS; + float attenuation = pow(distance + 1.0, light.decay_rate + M_FLOAT_EPS); + result.intensity = light.color * light.intensity / attenuation; + result.direction /= distance; + float low = min(light.inner_angle, light.outer_angle); + float high = light.inner_angle; + float cosDir = dot(result.direction, -light.direction); + float spotAttenuation = smoothstep(low, high, cosDir); + result.intensity *= spotAttenuation; +} +void mx_point_light(LightData light, float3 position, thread lightshader& result) +{ + result.direction = light.position - position; + float distance = length(result.direction) + M_FLOAT_EPS; + float attenuation = pow(distance + 1.0, light.decay_rate + M_FLOAT_EPS); + result.intensity = light.color * light.intensity / attenuation; + result.direction /= distance; +} + + + + + + + + + + + + + +void mx_directional_light(LightData light, float3 position, thread lightshader& result) +{ + result.direction = -light.direction; + result.intensity = light.color * light.intensity; +} +void mx_point_light(LightData light, vec3 position, out lightshader result) +{ + result.direction = light.position - position; + float distance = length(result.direction) + M_FLOAT_EPS; + float attenuation = pow(distance + 1.0, light.decay_rate + M_FLOAT_EPS); + result.intensity = light.color * light.intensity / attenuation; + result.direction /= distance; +} +void mx_spot_light(LightData light, vec3 position, out lightshader result) +{ + result.direction = light.position - position; + float distance = length(result.direction) + M_FLOAT_EPS; + float attenuation = pow(distance + 1.0, light.decay_rate + M_FLOAT_EPS); + result.intensity = light.color * light.intensity / attenuation; + result.direction /= distance; + float low = min(light.inner_angle, light.outer_angle); + float high = light.inner_angle; + float cosDir = dot(result.direction, -light.direction); + float spotAttenuation = smoothstep(low, high, cosDir); + result.intensity *= spotAttenuation; +} + + + + + + + + + + + + + +void mx_directional_light(LightData light, vec3 position, out lightshader result) +{ + result.direction = -light.direction; + result.intensity = light.color * light.intensity; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +void mx_displacement_vector3(vec3 disp, float scale, out displacementshader result) +{ + result.offset = disp; + result.scale = scale; +} +void mx_anisotropic_vdf(vec3 absorption, vec3 scattering, float anisotropy, inout BSDF bsdf) +{ + // TODO: Add some approximation for volumetric light absorption. +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +void mx_displacement_float(float disp, float scale, out displacementshader result) +{ + result.offset = vec3(disp); + result.scale = scale; +} +void mx_add_edf(vec3 N, vec3 L, EDF in1, EDF in2, out EDF result) +{ + result = in1 + in2; +} +#include "lib/mx_microfacet_specular.glsl" + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} +#include "lib/mx_microfacet_specular.glsl" + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} +void mx_roughness_dual(vec2 roughness, out vec2 result) +{ + if (roughness.y < 0.0) + { + roughness.y = roughness.x; + } + result.x = clamp(roughness.x * roughness.x, M_FLOAT_EPS, 1.0); + result.y = clamp(roughness.y * roughness.y, M_FLOAT_EPS, 1.0); +} +#include "lib/mx_microfacet_diffuse.glsl" + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} +#include "lib/mx_microfacet_sheen.glsl" + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} +#include "lib/mx_microfacet_specular.glsl" + +// https://eugenedeon.com/pdfs/egsrhair.pdf +void mx_deon_hair_absorption_from_melanin( + float melanin_concentration, + float melanin_redness, + // constants converted to color via exp(-c). the defaults are lin_rec709 colors, they may be + // transformed to scene-linear rendering color space. + vec3 eumelanin_color, // default: (0.657704, 0.498077, 0.254106) == exp(-(0.419, 0.697, 1.37)) + vec3 pheomelanin_color, // default: (0.829443, 0.670320, 0.349937) == exp(-(0.187, 0.4, 1.05)) + out vec3 absorption) +{ + float melanin = -log(max(1.0 - melanin_concentration, 0.0001)); + float eumelanin = melanin * (1.0 - melanin_redness); + float pheomelanin = melanin * melanin_redness; + absorption = max( + eumelanin * -log(eumelanin_color) + pheomelanin * -log(pheomelanin_color), + vec3(0.0) + ); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/152/asset/eurographics2016Fur_Smaller.pdf +void mx_chiang_hair_absorption_from_color(vec3 color, float betaN, out vec3 absorption) +{ + float b2 = betaN* betaN; + float b4 = b2 * b2; + float b_fac = + 5.969 - + (0.215 * betaN) + + (2.532 * b2) - + (10.73 * b2 * betaN) + + (5.574 * b4) + + (0.245 * b4 * betaN); + vec3 sigma = log(min(max(color, 0.001), vec3(1.0))) / b_fac; + absorption = sigma * sigma; +} + +void mx_chiang_hair_roughness( + float longitudinal, + float azimuthal, + float scale_TT, // empirical roughenss scale from Marschner et al. (2003). + float scale_TRT, // default: scale_TT = 0.5, scale_TRT = 2.0 + out vec2 roughness_R, + out vec2 roughness_TT, + out vec2 roughness_TRT +) +{ + float lr = clamp(longitudinal, 0.001, 1.0); + float ar = clamp(azimuthal, 0.001, 1.0); + + // longitudinal variance + float v = 0.726 * lr + 0.812 * lr * lr + 3.7 * pow(lr, 20.0); + v = v * v; + + float s = 0.265 * ar + 1.194 * ar * ar + 5.372 * pow(ar, 22.0); + + roughness_R = vec2(v, s); + roughness_TT = vec2(v * scale_TT * scale_TT, s); + roughness_TRT = vec2(v * scale_TRT * scale_TRT, s); +} + +float mx_hair_transform_sin_cos(float x) +{ + return sqrt(max(1.0 - x * x, 0.0)); +} + +float mx_hair_I0(float x) +{ + float v = 1.0; + float n = 1.0; + float d = 1.0; + float f = 1.0; + float x2 = x * x; + for (int i = 0; i < 9 ; ++i) + { + d *= 4.0 * (f * f); + n *= x2; + v += n / d; + f += 1.0; + } + return v; +} + +float mx_hair_log_I0(float x) +{ + if (x > 12.0) + return x + 0.5 * (-log(2.0 * M_PI) + log(1.0 / x) + 1.0 / (8.0 * x)); + else + return log(mx_hair_I0(x)); +} + +float mx_hair_logistic(float x, float s) +{ + if (x > 0.0) + x = -x; + float f = exp(x / s); + return f / (s * (1.0 + f) * (1.0 + f)); +} + +float mx_hair_logistic_cdf(float x, float s) +{ + return 1.0 / (1.0 + exp(-x / s)); +} + +float mx_hair_trimmed_logistic(float x, float s, float a, float b) +{ + // the constant can be found in Chiang et al. (2016) Appendix A, eq. (12) + s *= 0.626657; // sqrt(M_PI/8) + return mx_hair_logistic(x, s) / (mx_hair_logistic_cdf(b, s) - mx_hair_logistic_cdf(a, s)); +} + +float mx_hair_phi(int p, float gammaO, float gammaT) +{ + float fP = float(p); + return 2.0 * fP * gammaT - 2.0 * gammaO + fP * M_PI; +} + +float mx_hair_longitudinal_scattering( // Mp + float sinThetaI, + float cosThetaI, + float sinThetaO, + float cosThetaO, + float v +) +{ + float inv_v = 1.0 / v; + float a = cosThetaO * cosThetaI * inv_v; + float b = sinThetaO * sinThetaI * inv_v; + if (v < 0.1) + return exp(mx_hair_log_I0(a) - b - inv_v + 0.6931 + log(0.5 * inv_v)); + else + return ((exp(-b) * mx_hair_I0(a)) / (2.0 * v * sinh(inv_v))); +} + +float mx_hair_azimuthal_scattering( // Np + float phi, + int p, + float s, + float gammaO, + float gammaT +) +{ + if (p >= 3) + return float(0.5 / M_PI); + + float dphi = phi - mx_hair_phi(p, gammaO, gammaT); + if (isinf(dphi)) + return float(0.5 / M_PI); + + while (dphi > M_PI) dphi -= (2.0 * M_PI); + while (dphi < (-M_PI)) dphi += (2.0 * M_PI); + + return mx_hair_trimmed_logistic(dphi, s, -M_PI, M_PI); +} + +void mx_hair_alpha_angles( + float alpha, + float sinThetaI, + float cosThetaI, + out vec2 angles[4] +) +{ + // 0:R, 1:TT, 2:TRT, 3:TRRT+ + for (int i = 0; i <= 3; ++i) + { + if (alpha == 0.0 || i == 3) + angles[i] = vec2(sinThetaI, cosThetaI); + else + { + float m = 2.0 - float(i) * 3.0; + float sa = sin(m * alpha); + float ca = cos(m * alpha); + angles[i].x = sinThetaI * ca + cosThetaI * sa; + angles[i].y = cosThetaI * ca - sinThetaI * sa; + } + } +} + +void mx_hair_attenuation(float f, vec3 T, out vec3 Ap[4]) // Ap +{ + // 0:R, 1:TT, 2:TRT, 3:TRRT+ + Ap[0] = vec3(f); + Ap[1] = (1.0 - f) * (1.0 - f) * T; + Ap[2] = Ap[1] * T * f; + Ap[3] = Ap[2] * T * f / (vec3(1.0) - T * f); +} + +vec3 mx_chiang_hair_bsdf( + vec3 L, + vec3 V, + vec3 tint_R, + vec3 tint_TT, + vec3 tint_TRT, + float ior, + vec2 roughness_R, + vec2 roughness_TT, + vec2 roughness_TRT, + float cuticle_angle, + vec3 absorption_coefficient, + vec3 N, + vec3 X +) +{ + N = mx_forward_facing_normal(N, V); + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + + float sinThetaO = dot(V, X); + float sinThetaI = dot(L, X); + float cosThetaO = mx_hair_transform_sin_cos(sinThetaO); + float cosThetaI = mx_hair_transform_sin_cos(sinThetaI); + + float y1 = dot(L, N); + float x1 = dot(L, Y); + float y2 = dot(V, N); + float x2 = dot(V, Y); + float phi = mx_atan(y1 * x2 - y2 * x1, x1 * x2 + y1 * y2); + + vec3 k1_p = normalize(V - X * dot(V, X)); + float cosGammaO = dot(N, k1_p); + float sinGammaO = mx_hair_transform_sin_cos(cosGammaO); + if (dot(k1_p, Y) > 0.0) + sinGammaO = -sinGammaO; + float gammaO = asin(sinGammaO); + + float sinThetaT = sinThetaO / ior; + float cosThetaT = mx_hair_transform_sin_cos(sinThetaT); + float etaP = sqrt(max(ior * ior - sinThetaO * sinThetaO, 0.0)) / max(cosThetaO, 1e-8); + float sinGammaT = max(min(sinGammaO / etaP, 1.0), -1.0); + float cosGammaT = sqrt(1.0 - sinGammaT * sinGammaT); + float gammaT = asin(sinGammaT); + + // attenuation + vec3 Ap[4]; + float fresnel = mx_fresnel_dielectric(cosThetaO * cosGammaO, ior); + vec3 T = exp(-absorption_coefficient * (2.0 * cosGammaT / cosThetaT)); + mx_hair_attenuation(fresnel, T, Ap); + + // parameters for each lobe + vec2 angles[4]; + float alpha = cuticle_angle * M_PI - (M_PI / 2.0); // remap [0, 1] to [-PI/2, PI/2] + mx_hair_alpha_angles(alpha, sinThetaI, cosThetaI, angles); + + vec3 tint[4]; + tint[0] = tint_R; + tint[1] = tint_TT; + tint[2] = tint_TRT; + tint[3] = tint_TRT; + + roughness_R = clamp(roughness_R, 0.001, 1.0); + roughness_TT = clamp(roughness_TT, 0.001, 1.0); + roughness_TRT = clamp(roughness_TRT, 0.001, 1.0); + + vec2 vs[4]; + vs[0] = roughness_R; + vs[1] = roughness_TT; + vs[2] = roughness_TRT; + vs[3] = roughness_TRT; + + // R, TT, TRT, TRRT+ + vec3 F = vec3(0.0); + for (int i = 0; i <= 3; ++i) + { + tint[i] = max(tint[i], vec3(0.0)); + float Mp = mx_hair_longitudinal_scattering(angles[i].x, angles[i].y, sinThetaO, cosThetaO, vs[i].x); + float Np = (i == 3) ? (1.0 / 2.0 * M_PI) : mx_hair_azimuthal_scattering(phi, i, vs[i].y, gammaO, gammaT); + F += Mp * Np * tint[i] * Ap[i]; + } + + return F; +} + +void mx_chiang_hair_bsdf_reflection( + vec3 L, + vec3 V, + vec3 P, + float occlusion, + vec3 tint_R, + vec3 tint_TT, + vec3 tint_TRT, + float ior, + vec2 roughness_R, + vec2 roughness_TT, + vec2 roughness_TRT, + float cuticle_angle, + vec3 absorption_coefficient, + vec3 N, + vec3 X, + inout BSDF bsdf +) +{ + vec3 F = mx_chiang_hair_bsdf( + L, + V, + tint_R, + tint_TT, + tint_TRT, + ior, + roughness_R, + roughness_TT, + roughness_TRT, + cuticle_angle, + absorption_coefficient, + N, + X + ); + + bsdf.throughput = vec3(0.0); + bsdf.response = F * occlusion * M_PI_INV; +} + +void mx_chiang_hair_bsdf_indirect( + vec3 V, + vec3 tint_R, + vec3 tint_TT, + vec3 tint_TRT, + float ior, + vec2 roughness_R, + vec2 roughness_TT, + vec2 roughness_TRT, + float cuticle_angle, + vec3 absorption_coefficient, + vec3 N, + vec3 X, + inout BSDF bsdf +) +{ + // this indirect lighing is *very* rough approximation + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_dielectric(ior, 0.0, 1.0); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 roughness = (roughness_R + roughness_TT + roughness_TRT) / vec2(3.0); // ? + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + // use ggx because the environment map for FIS is preintegrated with ggx + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, 0, fd); + vec3 tint = (tint_R + tint_TT + tint_TRT) / vec3(3.0); // ? + + bsdf.throughput = vec3(0.0); + bsdf.response = Li * comp * tint; +} +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} +#include "lib/mx_microfacet_diffuse.glsl" + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} +#include "lib/mx_microfacet.glsl" + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} +/// XYZ to Rec.709 RGB colorspace conversion +const mat3 XYZ_to_RGB = mat3( 3.2406, -0.9689, 0.0557, + -1.5372, 1.8758, -0.2040, + -0.4986, 0.0415, 1.0570); + +void mx_blackbody(float temperatureKelvin, out vec3 colorValue) +{ + float xc, yc; + float t, t2, t3, xc2, xc3; + + // if value outside valid range of approximation clamp to accepted temperature range + temperatureKelvin = clamp(temperatureKelvin, 1667.0, 25000.0); + + t = 1000.0 / temperatureKelvin; + t2 = t * t; + t3 = t * t * t; + + // Cubic spline approximation for Kelvin temperature to sRGB conversion + // (https://en.wikipedia.org/wiki/Planckian_locus#Approximation) + if (temperatureKelvin < 4000.0) { // 1667K <= temperatureKelvin < 4000K + xc = -0.2661239 * t3 - 0.2343580 * t2 + 0.8776956 * t + 0.179910; + } + else { // 4000K <= temperatureKelvin <= 25000K + xc = -3.0258469 * t3 + 2.1070379 * t2 + 0.2226347 * t + 0.240390; + } + xc2 = xc * xc; + xc3 = xc * xc * xc; + + if (temperatureKelvin < 2222.0) { // 1667K <= temperatureKelvin < 2222K + yc = -1.1063814 * xc3 - 1.34811020 * xc2 + 2.18555832 * xc - 0.20219683; + } + else if (temperatureKelvin < 4000.0) { // 2222K <= temperatureKelvin < 4000K + yc = -0.9549476 * xc3 - 1.37418593 * xc2 + 2.09137015 * xc - 0.16748867; + } + else { // 4000K <= temperatureKelvin <= 25000K + yc = 3.0817580 * xc3 - 5.87338670 * xc2 + 3.75112997 * xc - 0.37001483; + } + + if (yc <= 0.0) { // avoid division by zero + colorValue = vec3(1.0); + return; + } + + vec3 XYZ = vec3(xc / yc, 1.0, (1.0 - xc - yc) / yc); + + colorValue = XYZ_to_RGB * XYZ; + colorValue = max(colorValue, vec3(0.0)); +} +#include "lib/mx_microfacet_specular.glsl" + +void mx_generalized_schlick_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color0, vec3 color82, vec3 color90, float exponent, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeColor0 = max(color0, 0.0); + vec3 safeColor82 = max(color82, 0.0); + vec3 safeColor90 = max(color90, 0.0); + FresnelData fd = mx_init_fresnel_schlick(safeColor0, safeColor82, safeColor90, exponent, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, safeColor0, safeColor90) * comp; + float avgDirAlbedo = dot(dirAlbedo, vec3(1.0 / 3.0)); + bsdf.throughput = vec3(1.0 - avgDirAlbedo * weight); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_generalized_schlick_bsdf_transmission(vec3 V, float weight, vec3 color0, vec3 color82, vec3 color90, float exponent, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeColor0 = max(color0, 0.0); + vec3 safeColor82 = max(color82, 0.0); + vec3 safeColor90 = max(color90, 0.0); + FresnelData fd = mx_init_fresnel_schlick(safeColor0, safeColor82, safeColor90, exponent, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, safeColor0, safeColor90) * comp; + float avgDirAlbedo = dot(dirAlbedo, vec3(1.0 / 3.0)); + bsdf.throughput = vec3(1.0 - avgDirAlbedo * weight); + + if (scatter_mode != 0) + { + float avgF0 = dot(safeColor0, vec3(1.0 / 3.0)); + fd.ior = vec3(mx_f0_to_ior(avgF0)); + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, vec3(1.0)) * weight; + } +} + +void mx_generalized_schlick_bsdf_indirect(vec3 V, float weight, vec3 color0, vec3 color82, vec3 color90, float exponent, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeColor0 = max(color0, 0.0); + vec3 safeColor82 = max(color82, 0.0); + vec3 safeColor90 = max(color90, 0.0); + FresnelData fd = mx_init_fresnel_schlick(safeColor0, safeColor82, safeColor90, exponent, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, safeColor0, safeColor90) * comp; + float avgDirAlbedo = dot(dirAlbedo, vec3(1.0 / 3.0)); + bsdf.throughput = vec3(1.0 - avgDirAlbedo * weight); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * comp * weight; +} +#include "lib/mx_microfacet_diffuse.glsl" + +void mx_burley_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotH = clamp(dot(L, normalize(L + V)), M_FLOAT_EPS, 1.0); + + bsdf.response = color * occlusion * weight * NdotL * M_PI_INV; + bsdf.response *= mx_burley_diffuse(NdotV, NdotL, LdotH, roughness); +} + +void mx_burley_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 Li = mx_environment_irradiance(normal) * + mx_burley_diffuse_dir_albedo(NdotV, roughness); + bsdf.response = Li * color * weight; +} +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} +#include "mx_microfacet_specular.glsl" + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = $envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float($envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, $envMatrix, lod, $envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * $envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, $envMatrix, 0.0, $envIrradiance); + return Li * $envLightIntensity; +} +// https://developer.nvidia.com/gpugems/gpugems3/part-ii-light-and-shadows/chapter-8-summed-area-variance-shadow-maps +float mx_variance_shadow_occlusion(vec2 moments, float fragmentDepth) +{ + const float MIN_VARIANCE = 0.00001; + + // One-tailed inequality valid if fragmentDepth > moments.x. + float p = (fragmentDepth <= moments.x) ? 1.0 : 0.0; + + // Compute variance. + float variance = moments.y - mx_square(moments.x); + variance = max(variance, MIN_VARIANCE); + + // Compute probabilistic upper bound. + float d = fragmentDepth - moments.x; + float pMax = variance / (variance + mx_square(d)); + return max(p, pMax); +} + +vec2 mx_compute_depth_moments() +{ + float depth = gl_FragCoord.z; + return vec2(depth, mx_square(depth)); +} +#include "mx_microfacet_specular.glsl" + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + return tint; +} +#include "mx_microfacet.glsl" + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize($albedoTable, 0).x > 1) + { + vec2 AB = texture($albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} +#include "mx_microfacet.glsl" + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize($albedoTable, 0).x > 1) + { + return texture($albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} +#include "mx_microfacet_sheen.glsl" +#include "mx_microfacet_specular.glsl" + +vec3 mx_generate_dir_albedo_table() +{ + vec2 uv = gl_FragCoord.xy / $albedoTableSize; + vec2 ggxDirAlbedo = mx_ggx_dir_albedo(uv.x, uv.y, vec3(1, 0, 0), vec3(0, 1, 0)).xy; + float sheenDirAlbedo = mx_imageworks_sheen_dir_albedo(uv.x, uv.y); + return vec3(ggxDirAlbedo, sheenDirAlbedo); +} +#include "mx_microfacet_specular.glsl" + +// Return the mip level associated with the given alpha in a prefiltered environment. +float mx_latlong_alpha_to_lod(float alpha) +{ + float lodBias = (alpha < 0.25) ? sqrt(alpha) : 0.5 * alpha + 0.375; + return lodBias * float($envRadianceMips - 1); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + N = mx_forward_facing_normal(N, V); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, N, fd.ior.x) : -reflect(V, N); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float avgAlpha = mx_average_alpha(alpha); + vec3 F = mx_compute_fresnel(NdotV, fd); + float G = mx_ggx_smith_G2(NdotV, NdotV, avgAlpha); + vec3 FG = fd.refraction ? vec3(1.0) - (F * G) : F * G; + + vec3 Li = mx_latlong_map_lookup(L, $envMatrix, mx_latlong_alpha_to_lod(avgAlpha), $envRadiance); + return Li * FG * $envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, $envMatrix, 0.0, $envIrradiance); + return Li * $envLightIntensity; +} +#include "mx_microfacet_specular.glsl" + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if ($refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} +#include "mx_microfacet.glsl" + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize($albedoTable, 0).x > 1) + { + return texture($albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} +#include "mx_microfacet_specular.glsl" + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 roughness, int distribution, FresnelData fd) +{ + return vec3(0.0); +} + +vec3 mx_environment_irradiance(vec3 N) +{ + return vec3(0.0); +} +#include "mx_microfacet_specular.glsl" + +// Return the alpha associated with the given mip level in a prefiltered environment. +float mx_latlong_lod_to_alpha(float lod) +{ + float lodBias = lod / float($envRadianceMips - 1); + return (lodBias < 0.5) ? mx_square(lodBias) : 2.0 * (lodBias - 0.375); +} + +// The inverse of mx_latlong_projection. +vec3 mx_latlong_map_projection_inverse(vec2 uv) +{ + float latitude = (uv.y - 0.5) * M_PI; + float longitude = (uv.x - 0.5) * M_PI * 2.0; + + float x = -mx_cos(latitude) * mx_sin(longitude); + float y = -mx_sin(latitude); + float z = mx_cos(latitude) * mx_cos(longitude); + + return vec3(x, y, z); +} + +vec3 mx_generate_prefilter_env() +{ + // The tangent view vector is aligned with the normal. + vec3 V = vec3(0.0, 0.0, 1.0); + float NdotV = 1.0; + + // Compute derived properties. + vec2 uv = gl_FragCoord.xy * pow(2.0, $envPrefilterMip) / vec2(textureSize($envRadiance, 0)); + vec3 worldN = mx_latlong_map_projection_inverse(uv); + mat3 tangentToWorld = mx_orthonormal_basis(worldN); + float alpha = mx_latlong_lod_to_alpha(float($envPrefilterMip)); + float G1V = mx_ggx_smith_G1(NdotV, alpha); + + // Integrate the LD term for the given environment and alpha. + vec3 radiance = vec3(0.0, 0.0, 0.0); + float weight = 0.0; + int envRadianceSamples = 1024; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -V + 2.0 * H.z * H; + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, vec2(alpha)) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float($envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, $envMatrix, lod, $envRadiance); + + // Add the radiance contribution of this sample. + radiance += G * sampleColor; + weight += G; + } + + return radiance / weight; +} +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} +void mx_roughness_dual(vector2 roughness, output vector2 result) +{ + result.x = clamp(roughness.x * roughness.x, M_FLOAT_EPS, 1.0); + if (roughness.y < 0.0) + { + result.y = result.x; + } + else + { + result.y = clamp(roughness.y * roughness.y, M_FLOAT_EPS, 1.0); + } +} +void mx_displacement_float(float displacement, float scale, output displacementshader result) +{ + result = vector(displacement * scale); +} +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} +#include "lib/mx_microfacet.osl" + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +void mx_generalized_schlick_bsdf(float weight, color color0, color color82, color color90, float exponent, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * generalized_schlick_bsdf(N, U, color(1.0), color(0.0), roughness.x, roughness.y, color0, color90, exponent, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * generalized_schlick_bsdf(N, U, color(0.0), color(1.0), roughness.x, roughness.y, color0, color90, exponent, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * generalized_schlick_bsdf(N, U, color(1.0), color(1.0), roughness.x, roughness.y, color0, color90, exponent, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} +void mx_blackbody(float temp, output color color_value) +{ + float xc, yc; + float t, t2, t3, xc2, xc3; + + // if value outside valid range of approximation clamp to accepted temperature range + float temperature = clamp(temp, 1667.0, 25000.0); + + t = 1000.0 / temperature; + t2 = t * t; + t3 = t * t * t; + + // Cubic spline approximation for Kelvin temperature to sRGB conversion + // (https://en.wikipedia.org/wiki/Planckian_locus#Approximation) + if (temperature < 4000.0) { // 1667K <= temperature < 4000K + xc = -0.2661239 * t3 - 0.2343580 * t2 + 0.8776956 * t + 0.179910; + } + else { // 4000K <= temperature <= 25000K + xc = -3.0258469 * t3 + 2.1070379 * t2 + 0.2226347 * t + 0.240390; + } + xc2 = xc * xc; + xc3 = xc * xc * xc; + + if (temperature < 2222.0) { // 1667K <= temperature < 2222K + yc = -1.1063814 * xc3 - 1.34811020 * xc2 + 2.18555832 * xc - 0.20219683; + } + else if (temperature < 4000.0) { // 2222K <= temperature < 4000K + yc = -0.9549476 * xc3 - 1.37418593 * xc2 + 2.09137015 * xc - 0.16748867; + } + else { // 4000K <= temperature <= 25000K + yc = 3.0817580 * xc3 - 5.87338670 * xc2 + 3.75112997 * xc - 0.37001483; + } + + if (yc <= 0.0) { // avoid division by zero + color_value = color(1.0); + return; + } + + vector XYZ = vector(xc / yc, 1.0, (1 - xc - yc) / yc); + + /// XYZ to Rec.709 RGB colorspace conversion + matrix XYZ_to_RGB = matrix( 3.2406, -0.9689, 0.0557, 0.0, + -1.5372, 1.8758, -0.2040, 0.0, + -0.4986, 0.0415, 1.0570, 0.0, + 0.0, 0.0, 0.0, 1.0); + + color_value = transform(XYZ_to_RGB, XYZ); + color_value = max(color_value, vector(0.0)); +} +void mx_displacement_vector3(vector displacement, float scale, output displacementshader result) +{ + result = displacement * scale; +} +void mx_anisotropic_vdf(color absorption, color scattering, float anisotropy, output VDF vdf) +{ + // Convert from absorption and scattering coefficients to + // extinction coefficient and single-scattering albedo. + color extinction = absorption + scattering; + color albedo = scattering / extinction; + vdf = anisotropic_vdf(albedo, extinction, anisotropy); +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} +void mx_burley_diffuse_bsdf(float weight, color reflectance, float roughness, normal N, output BSDF bsdf) +{ + // TODO: Implement properly. + bsdf.response = reflectance * weight * oren_nayar(N, roughness); + bsdf.throughput = color(0.0); +} +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf.response; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf.response = _color * weight * diffuse(N); + bsdf.throughput = color(0.0); +} +#include "../lib/mx_microfacet_specular.osl" + +void mx_conductor_bsdf(float weight, color ior_n, color ior_k, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, output BSDF bsdf) +{ + bsdf.throughput = color(0.0); + + if (weight < M_FLOAT_EPS) + { + bsdf.response = 0; + return; + } + + // Calculate conductor fresnel + // + // Fresnel should be based on microfacet normal + // but we have no access to that from here, so just use + // view direction and surface normal instead + // + float NdotV = fabs(dot(N,-I)); + color F = mx_fresnel_conductor(NdotV, ior_n, ior_k); + + // Calculate compensation for multiple scattering. + // This should normally be done inside the closure + // but since vanilla OSL doesen't support this we + // add it here in shader code instead. + vector2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + color comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Set ior to 0.0 to disable the internal dielectric fresnel + bsdf.response = F * comp * weight * microfacet(distribution, N, U, safeAlpha.x, safeAlpha.y, 0.0, false); +} +#include "../lib/mx_microfacet_specular.osl" + +void mx_generalized_schlick_bsdf(float weight, color color0, color color82, color color90, float exponent, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + float avgF0 = dot(color0, color(1.0 / 3.0)); + float ior = mx_f0_to_ior(avgF0); + + if (scatter_mode == "T") + { + bsdf.response = weight * microfacet(distribution, N, U, roughness.x, roughness.y, ior, 1); + bsdf.throughput = weight; + return; + } + + float NdotV = fabs(dot(N,-I)); + color F = mx_fresnel_schlick(NdotV, color0, color90, exponent); + + // Calculate compensation for multiple scattering. + // This should normally be done inside the closure + // but since vanilla OSL doesen't support this we + // add it here in shader code instead. + vector2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + color comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Calculate throughput from directional albedo. + color dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, color0, color90) * comp; + float avgDirAlbedo = dot(dirAlbedo, color(1.0 / 3.0)); + bsdf.throughput = 1.0 - avgDirAlbedo * weight; + + // Calculate the reflection response, setting IOR to zero to disable internal Fresnel. + bsdf.response = F * comp * weight * microfacet(distribution, N, U, safeAlpha.x, safeAlpha.y, 0.0, 0); + + if (scatter_mode == "RT") + { + bsdf.response += bsdf.throughput * microfacet(distribution, N, U, safeAlpha.x, safeAlpha.y, ior, 1); + } +} +void mx_anisotropic_vdf(vector absorption, vector scattering, float anisotropy, output VDF vdf) +{ + // Not implemented in vanilla OSL + vdf = 0; // volume_henyey_greenstein(color(absorption), color(scattering), color(0.0), anisotropy); +} +#include "../lib/mx_microfacet_sheen.osl" + +// TODO: Vanilla OSL doesn't have a proper sheen closure, +// so use 'diffuse' scaled by sheen directional albedo for now. +void mx_sheen_bsdf(float weight, color Ks, float roughness, vector N, output BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + bsdf.response = 0; + bsdf.throughput = color(1.0); + return; + } + + // TODO: Normalization should not be needed. My suspicion is that + // BSDF sampling of new outgoing direction in 'testrender' needs + // to be fixed. + vector V = normalize(-I); + + float NdotV = fabs(dot(N,V)); + float alpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float albedo = weight * mx_imageworks_sheen_dir_albedo(NdotV, alpha); + bsdf.response = albedo * Ks * diffuse(N); + bsdf.throughput = 1.0 - albedo; +} +#include "../lib/mx_microfacet_specular.osl" + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "T") + { + bsdf.response = tint * weight * microfacet(distribution, N, U, roughness.x, roughness.y, ior, 1); + bsdf.throughput = tint * weight; + return; + } + + float NdotV = clamp(dot(N,-I), M_FLOAT_EPS, 1.0); + float F0 = mx_ior_to_f0(ior); + float F = mx_fresnel_schlick(NdotV, F0); + + // Calculate compensation for multiple scattering. + // This should normally be done inside the closure + // but since vanilla OSL doesen't support this we + // add it here in shader code instead. + vector2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + float comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Calculate throughput from directional albedo. + float dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, ior) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode == "R") + { + bsdf.response = tint * weight * comp * microfacet(distribution, N, U, safeAlpha.x, safeAlpha.y, ior, 0); + } + else + { + bsdf.response = tint * weight * comp * microfacet(distribution, N, U, safeAlpha.x, safeAlpha.y, ior, 2); + } +} +void mx_oren_nayar_diffuse_bsdf(float weight, color _color, float roughness, normal N, int energy_compensation, output BSDF bsdf) +{ + bsdf.response = _color * weight * oren_nayar(N, roughness); + bsdf.throughput = color(0.0); +} +void mx_translucent_bsdf(float weight, color _color, normal N, output BSDF bsdf) +{ + bsdf.response = _color * weight * translucent(N); + bsdf.throughput = color(0.0); +} +#include "mx_microfacet.osl" + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vector2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +color mx_ggx_dir_albedo(float NdotV, float alpha, color F0, color F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vector4 r = vector4(0.1003, 0.9345, 1.0, 1.0) + + vector4(-0.6303, -2.323, -1.765, 0.2281) * x + + vector4(9.748, 2.229, 8.263, 15.94) * y + + vector4(-2.038, -3.748, 11.53, -55.83) * x * y + + vector4(29.34, 1.424, 28.96, 13.08) * x2 + + vector4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vector4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vector4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vector4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vector2 AB = vector2(r.x, r.y) / vector2(r.z, r.w); + AB.x = clamp(AB.x, 0.0, 1.0); + AB.y = clamp(AB.y, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + color result = mx_ggx_dir_albedo(NdotV, alpha, color(F0), color(F90)); + return result[0]; +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float ior) +{ + color result = mx_ggx_dir_albedo(NdotV, alpha, color(mx_ior_to_f0(ior)), color(1.0)); + return result[0]; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +color mx_ggx_energy_compensation(float NdotV, float alpha, color Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + color result = mx_ggx_energy_compensation(NdotV, alpha, color(Fss)); + return result[0]; +} +#include "mx_microfacet.osl" + +// Rational curve fit approximation for the directional albedo of Imageworks sheen. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + float a = 5.25248 - 7.66024 * NdotV + 14.26377 * roughness; + float b = 1.0 + 30.66449 * NdotV + 32.53420 * roughness; + return a / b; +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + return clamp(dirAlbedo, 0.0, 1.0); +} +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +// Restrict to 7x7 kernel size for performance reasons +#define MX_MAX_SAMPLE_COUNT 49 +// Size of all weights for all levels (including level 1) +#define MX_WEIGHT_ARRAY_SIZE 84 + +// +// Function to compute the sample size relative to a texture coordinate +// +vec2 mx_compute_sample_size_uv(vec2 uv, float filterSize, float filterOffset) +{ + vec2 derivUVx = dFdx(uv) * 0.5f; + vec2 derivUVy = dFdy(uv) * 0.5f; + float derivX = abs(derivUVx.x) + abs(derivUVy.x); + float derivY = abs(derivUVx.y) + abs(derivUVy.y); + float sampleSizeU = 2.0f * filterSize * derivX + filterOffset; + if (sampleSizeU < 1.0E-05f) + sampleSizeU = 1.0E-05f; + float sampleSizeV = 2.0f * filterSize * derivY + filterOffset; + if (sampleSizeV < 1.0E-05f) + sampleSizeV = 1.0E-05f; + return vec2(sampleSizeU, sampleSizeV); +} + +// +// Compute a normal mapped to 0..1 space based on a set of input +// samples using a Sobel filter. +// +vec3 mx_normal_from_samples_sobel(constant float S[9], float _scale) +{ + float nx = S[0] - S[2] + (2.0*S[3]) - (2.0*S[5]) + S[6] - S[8]; + float ny = S[0] + (2.0*S[1]) + S[2] - S[6] - (2.0*S[7]) - S[8]; + float nz = max(_scale, M_FLOAT_EPS) * sqrt(max(1.0 - nx * nx - ny * ny, M_FLOAT_EPS)); + vec3 norm = normalize(vec3(nx, ny, nz)); + return (norm + 1.0) * 0.5; +} + +// +// Apply filter for float samples S, using weights W. +// sampleCount should be a square of a odd number in the range { 1, 3, 5, 7 } +// +float mx_convolution_float(float S[MX_MAX_SAMPLE_COUNT], constant float W[MX_WEIGHT_ARRAY_SIZE], int offset, int sampleCount) +{ + float result = 0.0; + for (int i = 0; i < sampleCount; i++) + { + result += S[i]*W[i+offset]; + } + return result; +} + +// +// Apply filter for vec2 samples S, using weights W. +// sampleCount should be a square of a odd number in the range { 1, 3, 5, 7 } +// +vec2 mx_convolution_vec2(vec2 S[MX_MAX_SAMPLE_COUNT], constant float W[MX_WEIGHT_ARRAY_SIZE], int offset, int sampleCount) +{ + vec2 result = vec2(0.0); + for (int i=0; i +T1 mx_mod(T1 x, T2 y) +{ + return x - y * floor(x/y); +} + +float3x3 mx_inverse(float3x3 m) +{ + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; +} + +float4x4 mx_inverse(float4x4 m) +{ + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; +} + +float mx_atan(float y_over_x) +{ + return ::atan(y_over_x); +} + +float mx_atan(float y, float x) +{ + return ::atan2(y, x); +} + +vec2 mx_atan(vec2 y, vec2 x) +{ + return ::atan2(y, x); +} + +vec3 mx_atan(vec3 y, vec3 x) +{ + return ::atan2(y, x); +} + +vec4 mx_atan(vec4 y, vec4 x) +{ + return ::atan2(y, x); +} + +float mx_radians(float degree) +{ + return (degree * M_PI_F / 180.0f); +} +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +void mx_rotate_vector2(vec2 _in, float amount, out vec2 result) +{ + float rotationRadians = mx_radians(amount); + float sa = mx_sin(rotationRadians); + float ca = mx_cos(rotationRadians); + result = vec2(ca*_in.x + sa*_in.y, -sa*_in.x + ca*_in.y); +} +#include "mx_burn_float.glsl" + +void mx_burn_color3(vec3 fg, vec3 bg, float mixval, out vec3 result) +{ + float f; + mx_burn_float(fg.x, bg.x, mixval, f); result.x = f; + mx_burn_float(fg.y, bg.y, mixval, f); result.y = f; + mx_burn_float(fg.z, bg.z, mixval, f); result.z = f; +} +void mx_mix_surfaceshader(surfaceshader fg, surfaceshader bg, float w, out surfaceshader returnshader) +{ + returnshader.color = mix(bg.color, fg.color, w); + returnshader.transparency = mix(bg.transparency, fg.transparency, w); +} +#include "lib/mx_noise.glsl" + +void mx_fractal3d_float(float amplitude, int octaves, float lacunarity, float diminish, vec3 position, out float result) +{ + float value = mx_fractal_noise_float(position, octaves, lacunarity, diminish); + result = value * amplitude; +} +#include "lib/$fileTransformUv" + +void mx_image_color4(sampler2D tex_sampler, int layer, vec4 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec4 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv); +} +#include "lib/mx_noise.glsl" + +void mx_worleynoise3d_float(vec3 position, float jitter, out float result) +{ + result = mx_worley_noise_float(position, jitter, 0); +} +#include "lib/mx_hsv.glsl" + +void mx_hsvtorgb_color3(vec3 _in, out vec3 result) +{ + result = mx_hsvtorgb(_in); +} +#include "mx_aastep.glsl" + +void mx_splitlr_float(float valuel, float valuer, float center, vec2 texcoord, out float result) +{ + result = mix(valuel, valuer, mx_aastep(center, texcoord.x)); +} +void mx_premult_color4(vec4 _in, out vec4 result) +{ + result = vec4(_in.rgb * _in.a, _in.a); +} +void mx_ramptb_vector3(vec3 valuet, vec3 valueb, vec2 texcoord, out vec3 result) +{ + result = mix (valuet, valueb, clamp(texcoord.y, 0.0, 1.0) ); +} +#include "mx_aastep.glsl" + +void mx_splitlr_vector2(vec2 valuel, vec2 valuer, float center, vec2 texcoord, out vec2 result) +{ + result = mix(valuel, valuer, mx_aastep(center, texcoord.x)); +} +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} +#include "lib/$fileTransformUv" + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} +#include "mx_aastep.glsl" + +void mx_splitlr_vector3(vec3 valuel, vec3 valuer, float center, vec2 texcoord, out vec3 result) +{ + result = mix(valuel, valuer, mx_aastep(center, texcoord.x)); +} +void mx_ramptb_float(float valuet, float valueb, vec2 texcoord, out float result) +{ + result = mix (valuet, valueb, clamp(texcoord.y, 0.0, 1.0) ); +} +#include "lib/mx_noise.glsl" + +void mx_noise3d_vector3(vec3 amplitude, float pivot, vec3 position, out vec3 result) +{ + vec3 value = mx_perlin_noise_vec3(position); + result = value * amplitude + pivot; +} +#include "lib/$fileTransformUv" + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} +#include "lib/mx_noise.glsl" + +void mx_noise3d_float(float amplitude, float pivot, vec3 position, out float result) +{ + float value = mx_perlin_noise_float(position); + result = value * amplitude + pivot; +} +#include "lib/mx_noise.glsl" + +void mx_fractal3d_vector3(vec3 amplitude, int octaves, float lacunarity, float diminish, vec3 position, out vec3 result) +{ + vec3 value = mx_fractal_noise_vec3(position, octaves, lacunarity, diminish); + result = value * amplitude; +} +#include "lib/mx_noise.glsl" + +void mx_worleynoise3d_vector3(vec3 position, float jitter, out vec3 result) +{ + result = mx_worley_noise_vec3(position, jitter, 0); +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +float mx_aastep(float threshold, float value) +{ + float afwidth = length(vec2(dFdx(value), dFdy(value))) * 0.70710678118654757; + return smoothstep(threshold-afwidth, threshold+afwidth, value); +} +#include "lib/mx_noise.glsl" + +void mx_worleynoise2d_float(vec2 texcoord, float jitter, out float result) +{ + result = mx_worley_noise_float(texcoord, jitter, 0); +} +void mx_unpremult_color4(vec4 _in, out vec4 result) +{ + result = vec4(_in.rgb / _in.a, _in.a); +} +#include "lib/mx_hsv.glsl" + +void mx_rgbtohsv_color4(vec4 _in, out vec4 result) +{ + result = vec4(mx_rgbtohsv(_in.rgb), 1.0); +} +void mx_transformmatrix_vector3M4(vec3 val, mat4 transform, out vec3 result) +{ + vec4 res = transform * vec4(val, 1.0); + result = res.xyz; +} +void mx_creatematrix_vector3_matrix44(vec3 in1, vec3 in2, vec3 in3, vec3 in4, out mat4 result) +{ + result = mat4(in1.x, in1.y, in1.z, 0.0, + in2.x, in2.y, in2.z, 0.0, + in3.x, in3.y, in3.z, 0.0, + in4.x, in4.y, in4.z, 1.0); +} +#include "lib/mx_noise.glsl" + +void mx_noise2d_vector3(vec3 amplitude, float pivot, vec2 texcoord, out vec3 result) +{ + vec3 value = mx_perlin_noise_vec3(texcoord); + result = value * amplitude + pivot; +} +void mx_ramptb_vector2(vec2 valuet, vec2 valueb, vec2 texcoord, out vec2 result) +{ + result = mix (valuet, valueb, clamp(texcoord.y, 0.0, 1.0) ); +} +#include "mx_aastep.glsl" + +void mx_splittb_vector3(vec3 valuet, vec3 valueb, float center, vec2 texcoord, out vec3 result) +{ + result = mix(valuet, valueb, mx_aastep(center, texcoord.y)); +} +void mx_ramplr_float(float valuel, float valuer, vec2 texcoord, out float result) +{ + result = mix (valuel, valuer, clamp(texcoord.x, 0.0, 1.0) ); +} +#include "mx_dodge_float.glsl" + +void mx_dodge_color4(vec4 fg , vec4 bg , float mixval, out vec4 result) +{ + float f; + mx_dodge_float(fg.x, bg.x, mixval, f); result.x = f; + mx_dodge_float(fg.y, bg.y, mixval, f); result.y = f; + mx_dodge_float(fg.z, bg.z, mixval, f); result.z = f; + mx_dodge_float(fg.w, bg.w, mixval, f); result.w = f; +} +#include "lib/mx_noise.glsl" + +void mx_cellnoise3d_float(vec3 position, out float result) +{ + result = mx_cell_noise_float(position); +} +void mx_ramplr_vector4(vec4 valuel, vec4 valuer, vec2 texcoord, out vec4 result) +{ + result = mix (valuel, valuer, clamp(texcoord.x, 0.0, 1.0) ); +} +#include "lib/mx_hsv.glsl" + +void mx_hsvtorgb_color4(vec4 _in, out vec4 result) +{ + result = vec4(mx_hsvtorgb(_in.rgb), 1.0); +} +void mx_creatematrix_vector4_matrix44(vec4 in1, vec4 in2, vec4 in3, vec4 in4, out mat4 result) +{ + result = mat4(in1.x, in1.y, in1.z, in1.w, + in2.x, in2.y, in2.z, in2.w, + in3.x, in3.y, in3.z, in3.w, + in4.x, in4.y, in4.z, in4.w); +} +void mx_transformmatrix_vector2M3(vec2 val, mat3 transform, out vec2 result) +{ + vec3 res = transform * vec3(val, 1.0); + result = res.xy; +} +void mx_dodge_float(float fg, float bg, float mixval, out float result) +{ + if (abs(1.0 - fg) < M_FLOAT_EPS) + { + result = 0.0; + return; + } + result = mixval*(bg / (1.0 - fg)) + ((1.0-mixval)*bg); +} +#include "lib/mx_noise.glsl" + +void mx_cellnoise2d_float(vec2 texcoord, out float result) +{ + result = mx_cell_noise_float(texcoord); +} +#include "lib/mx_noise.glsl" + +void mx_noise3d_vector4(vec4 amplitude, float pivot, vec3 position, out vec4 result) +{ + vec3 xyz = mx_perlin_noise_vec3(position); + float w = mx_perlin_noise_float(position + vec3(19, 73, 29)); + result = vec4(xyz, w) * amplitude + pivot; +} +#include "lib/$fileTransformUv" + +void mx_image_vector2(sampler2D tex_sampler, int layer, vec2 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec2 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rg; +} +#include "mx_aastep.glsl" + +void mx_splittb_vector2(vec2 valuet, vec2 valueb, float center, vec2 texcoord, out vec2 result) +{ + result = mix(valuet, valueb, mx_aastep(center, texcoord.y)); +} +void mx_disjointover_color4(vec4 fg, vec4 bg, float mixval, out vec4 result) +{ + float summedAlpha = fg.w + bg.w; + + if (summedAlpha <= 1.0) + { + result.xyz = fg.xyz + bg.xyz; + } + else + { + if (abs(bg.w) < M_FLOAT_EPS) + { + result.xyz = vec3(0.0); + } + else + { + float x = (1.0 - fg.w) / bg.w; + result.xyz = fg.xyz + bg.xyz * x; + } + } + result.w = min(summedAlpha, 1.0); + + result.xyz = result.xyz * mixval + (1.0 - mixval) * bg.xyz; + result.w = result.w * mixval + (1.0 - mixval) * bg.w; +} +#include "lib/mx_hsv.glsl" + +void mx_rgbtohsv_color3(vec3 _in, out vec3 result) +{ + result = mx_rgbtohsv(_in); +} +#include "mx_burn_float.glsl" + +void mx_burn_color4(vec4 fg, vec4 bg, float mixval, out vec4 result) +{ + float f; + mx_burn_float(fg.x, bg.x, mixval, f); result.x = f; + mx_burn_float(fg.y, bg.y, mixval, f); result.y = f; + mx_burn_float(fg.z, bg.z, mixval, f); result.z = f; + mx_burn_float(fg.w, bg.w, mixval, f); result.w = f; +} +void mx_luminance_color4(vec4 _in, vec3 lumacoeffs, out vec4 result) +{ + result = vec4(vec3(dot(_in.rgb, lumacoeffs)), _in.a); +} +#include "mx_aastep.glsl" + +void mx_splittb_vector4(vec4 valuet, vec4 valueb, float center, vec2 texcoord, out vec4 result) +{ + result = mix(valuet, valueb, mx_aastep(center, texcoord.y)); +} +#include "lib/mx_noise.glsl" + +void mx_worleynoise2d_vector3(vec2 texcoord, float jitter, out vec3 result) +{ + result = mx_worley_noise_vec3(texcoord, jitter, 0); +} +#include "mx_aastep.glsl" + +void mx_splitlr_vector4(vec4 valuel, vec4 valuer, float center, vec2 texcoord, out vec4 result) +{ + result = mix(valuel, valuer, mx_aastep(center, texcoord.x)); +} +void mx_ramplr_vector2(vec2 valuel, vec2 valuer, vec2 texcoord, out vec2 result) +{ + result = mix (valuel, valuer, clamp(texcoord.x, 0.0, 1.0) ); +} +void mx_burn_float(float fg, float bg, float mixval, out float result) +{ + if (abs(fg) < M_FLOAT_EPS) + { + result = 0.0; + return; + } + result = mixval*(1.0 - ((1.0 - bg) / fg)) + ((1.0-mixval)*bg); +} +void mx_smoothstep_float(float val, float low, float high, out float result) +{ + if (val >= high) + result = 1.0; + else if (val <= low) + result = 0.0; + else + result = smoothstep(low, high, val); +} +#include "lib/mx_noise.glsl" + +void mx_worleynoise3d_vector2(vec3 position, float jitter, out vec2 result) +{ + result = mx_worley_noise_vec2(position, jitter, 0); +} +#include "lib/$fileTransformUv" + +void mx_image_vector4(sampler2D tex_sampler, int layer, vec4 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec4 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv); +} +void mx_creatematrix_vector3_matrix33(vec3 in1, vec3 in2, vec3 in3, out mat3 result) +{ + result = mat3(in1.x, in1.y, in1.z, + in2.x, in2.y, in2.z, + in3.x, in3.y, in3.z); +} +#include "mx_dodge_float.glsl" + +void mx_dodge_color3(vec3 fg, vec3 bg, float mixval, out vec3 result) +{ + float f; + mx_dodge_float(fg.x, bg.x, mixval, f); result.x = f; + mx_dodge_float(fg.y, bg.y, mixval, f); result.y = f; + mx_dodge_float(fg.z, bg.z, mixval, f); result.z = f; +} +#include "lib/mx_noise.glsl" + +void mx_fractal3d_vector2(vec2 amplitude, int octaves, float lacunarity, float diminish, vec3 position, out vec2 result) +{ + vec2 value = mx_fractal_noise_vec2(position, octaves, lacunarity, diminish); + result = value * amplitude; +} +#include "lib/mx_noise.glsl" + +void mx_noise3d_vector2(vec2 amplitude, float pivot, vec3 position, out vec2 result) +{ + vec3 value = mx_perlin_noise_vec3(position); + result = value.xy * amplitude + pivot; +} +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} +#include "lib/mx_noise.glsl" + +void mx_worleynoise2d_vector2(vec2 texcoord, float jitter, out vec2 result) +{ + result = mx_worley_noise_vec2(texcoord, jitter, 0); +} +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} +void mx_ramptb_vector4(vec4 valuet, vec4 valueb, vec2 texcoord, out vec4 result) +{ + result = mix (valuet, valueb, clamp(texcoord.y, 0.0, 1.0) ); +} +#include "lib/mx_noise.glsl" + +void mx_noise2d_float(float amplitude, float pivot, vec2 texcoord, out float result) +{ + float value = mx_perlin_noise_float(texcoord); + result = value * amplitude + pivot; +} +#include "lib/mx_noise.glsl" + +void mx_noise2d_vector4(vec4 amplitude, float pivot, vec2 texcoord, out vec4 result) +{ + vec3 xyz = mx_perlin_noise_vec3(texcoord); + float w = mx_perlin_noise_float(texcoord + vec2(19, 73)); + result = vec4(xyz, w) * amplitude + pivot; +} +#include "lib/mx_noise.glsl" + +void mx_fractal3d_vector4(vec4 amplitude, int octaves, float lacunarity, float diminish, vec3 position, out vec4 result) +{ + vec4 value = mx_fractal_noise_vec4(position, octaves, lacunarity, diminish); + result = value * amplitude; +} +#include "lib/mx_noise.glsl" + +void mx_noise2d_vector2(vec2 amplitude, float pivot, vec2 texcoord, out vec2 result) +{ + vec3 value = mx_perlin_noise_vec3(texcoord); + result = value.xy * amplitude + pivot; +} +#include "lib/$fileTransformUv" + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} +void mx_ramplr_vector3(vec3 valuel, vec3 valuer, vec2 texcoord, out vec3 result) +{ + result = mix (valuel, valuer, clamp(texcoord.x, 0.0, 1.0) ); +} +#include "mx_aastep.glsl" + +void mx_splittb_float(float valuet, float valueb, float center, vec2 texcoord, out float result) +{ + result = mix(valuet, valueb, mx_aastep(center, texcoord.y)); +} +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return vec2(uv.x, 1.0 - uv.y); +} +// Restrict to 7x7 kernel size for performance reasons +#define MX_MAX_SAMPLE_COUNT 49 +// Size of all weights for all levels (including level 1) +#define MX_WEIGHT_ARRAY_SIZE 84 + +// +// Function to compute the sample size relative to a texture coordinate +// +vec2 mx_compute_sample_size_uv(vec2 uv, float filterSize, float filterOffset) +{ + vec2 derivUVx = dFdx(uv) * 0.5f; + vec2 derivUVy = dFdy(uv) * 0.5f; + float derivX = abs(derivUVx.x) + abs(derivUVy.x); + float derivY = abs(derivUVx.y) + abs(derivUVy.y); + float sampleSizeU = 2.0f * filterSize * derivX + filterOffset; + if (sampleSizeU < 1.0E-05f) + sampleSizeU = 1.0E-05f; + float sampleSizeV = 2.0f * filterSize * derivY + filterOffset; + if (sampleSizeV < 1.0E-05f) + sampleSizeV = 1.0E-05f; + return vec2(sampleSizeU, sampleSizeV); +} + +// +// Compute a normal mapped to 0..1 space based on a set of input +// samples using a Sobel filter. +// +vec3 mx_normal_from_samples_sobel(float S[9], float _scale) +{ + float nx = S[0] - S[2] + (2.0*S[3]) - (2.0*S[5]) + S[6] - S[8]; + float ny = S[0] + (2.0*S[1]) + S[2] - S[6] - (2.0*S[7]) - S[8]; + float nz = max(_scale, M_FLOAT_EPS) * sqrt(max(1.0 - nx * nx - ny * ny, M_FLOAT_EPS)); + vec3 norm = normalize(vec3(nx, ny, nz)); + return (norm + 1.0) * 0.5; +} + +// +// Apply filter for float samples S, using weights W. +// sampleCount should be a square of a odd number in the range { 1, 3, 5, 7 } +// +float mx_convolution_float(float S[MX_MAX_SAMPLE_COUNT], float W[MX_WEIGHT_ARRAY_SIZE], int offset, int sampleCount) +{ + float result = 0.0; + for (int i = 0; i < sampleCount; i++) + { + result += S[i]*W[i+offset]; + } + return result; +} + +// +// Apply filter for vec2 samples S, using weights W. +// sampleCount should be a square of a odd number in the range { 1, 3, 5, 7 } +// +vec2 mx_convolution_vec2(vec2 S[MX_MAX_SAMPLE_COUNT], float W[MX_WEIGHT_ARRAY_SIZE], int offset, int sampleCount) +{ + vec2 result = vec2(0.0); + for (int i=0; i>(32-k)); +} + +void mx_bjmix(inout uint a, inout uint b, inout uint c) +{ + a -= c; a ^= mx_rotl32(c, 4); c += b; + b -= a; b ^= mx_rotl32(a, 6); a += c; + c -= b; c ^= mx_rotl32(b, 8); b += a; + a -= c; a ^= mx_rotl32(c,16); c += b; + b -= a; b ^= mx_rotl32(a,19); a += c; + c -= b; c ^= mx_rotl32(b, 4); b += a; +} + +// Mix up and combine the bits of a, b, and c (doesn't change them, but +// returns a hash of those three original values). +uint mx_bjfinal(uint a, uint b, uint c) +{ + c ^= b; c -= mx_rotl32(b,14); + a ^= c; a -= mx_rotl32(c,11); + b ^= a; b -= mx_rotl32(a,25); + c ^= b; c -= mx_rotl32(b,16); + a ^= c; a -= mx_rotl32(c,4); + b ^= a; b -= mx_rotl32(a,14); + c ^= b; c -= mx_rotl32(b,24); + return c; +} + +// Convert a 32 bit integer into a floating point number in [0,1] +float mx_bits_to_01(uint bits) +{ + return float(bits) / float(uint(0xffffffff)); +} + +float mx_fade(float t) +{ + return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); +} + +uint mx_hash_int(int x) +{ + uint len = 1u; + uint seed = uint(0xdeadbeef) + (len << 2u) + 13u; + return mx_bjfinal(seed+uint(x), seed, seed); +} + +uint mx_hash_int(int x, int y) +{ + uint len = 2u; + uint a, b, c; + a = b = c = uint(0xdeadbeef) + (len << 2u) + 13u; + a += uint(x); + b += uint(y); + return mx_bjfinal(a, b, c); +} + +uint mx_hash_int(int x, int y, int z) +{ + uint len = 3u; + uint a, b, c; + a = b = c = uint(0xdeadbeef) + (len << 2u) + 13u; + a += uint(x); + b += uint(y); + c += uint(z); + return mx_bjfinal(a, b, c); +} + +uint mx_hash_int(int x, int y, int z, int xx) +{ + uint len = 4u; + uint a, b, c; + a = b = c = uint(0xdeadbeef) + (len << 2u) + 13u; + a += uint(x); + b += uint(y); + c += uint(z); + mx_bjmix(a, b, c); + a += uint(xx); + return mx_bjfinal(a, b, c); +} + +uint mx_hash_int(int x, int y, int z, int xx, int yy) +{ + uint len = 5u; + uint a, b, c; + a = b = c = uint(0xdeadbeef) + (len << 2u) + 13u; + a += uint(x); + b += uint(y); + c += uint(z); + mx_bjmix(a, b, c); + a += uint(xx); + b += uint(yy); + return mx_bjfinal(a, b, c); +} + +uvec3 mx_hash_vec3(int x, int y) +{ + uint h = mx_hash_int(x, y); + // we only need the low-order bits to be random, so split out + // the 32 bit result into 3 parts for each channel + uvec3 result; + result.x = (h ) & 0xFFu; + result.y = (h >> 8 ) & 0xFFu; + result.z = (h >> 16) & 0xFFu; + return result; +} + +uvec3 mx_hash_vec3(int x, int y, int z) +{ + uint h = mx_hash_int(x, y, z); + // we only need the low-order bits to be random, so split out + // the 32 bit result into 3 parts for each channel + uvec3 result; + result.x = (h ) & 0xFFu; + result.y = (h >> 8 ) & 0xFFu; + result.z = (h >> 16) & 0xFFu; + return result; +} + +float mx_perlin_noise_float(vec2 p) +{ + int X, Y; + float fx = mx_floorfrac(p.x, X); + float fy = mx_floorfrac(p.y, Y); + float u = mx_fade(fx); + float v = mx_fade(fy); + float result = mx_bilerp( + mx_gradient_float(mx_hash_int(X , Y ), fx , fy ), + mx_gradient_float(mx_hash_int(X+1, Y ), fx-1.0, fy ), + mx_gradient_float(mx_hash_int(X , Y+1), fx , fy-1.0), + mx_gradient_float(mx_hash_int(X+1, Y+1), fx-1.0, fy-1.0), + u, v); + return mx_gradient_scale2d(result); +} + +float mx_perlin_noise_float(vec3 p) +{ + int X, Y, Z; + float fx = mx_floorfrac(p.x, X); + float fy = mx_floorfrac(p.y, Y); + float fz = mx_floorfrac(p.z, Z); + float u = mx_fade(fx); + float v = mx_fade(fy); + float w = mx_fade(fz); + float result = mx_trilerp( + mx_gradient_float(mx_hash_int(X , Y , Z ), fx , fy , fz ), + mx_gradient_float(mx_hash_int(X+1, Y , Z ), fx-1.0, fy , fz ), + mx_gradient_float(mx_hash_int(X , Y+1, Z ), fx , fy-1.0, fz ), + mx_gradient_float(mx_hash_int(X+1, Y+1, Z ), fx-1.0, fy-1.0, fz ), + mx_gradient_float(mx_hash_int(X , Y , Z+1), fx , fy , fz-1.0), + mx_gradient_float(mx_hash_int(X+1, Y , Z+1), fx-1.0, fy , fz-1.0), + mx_gradient_float(mx_hash_int(X , Y+1, Z+1), fx , fy-1.0, fz-1.0), + mx_gradient_float(mx_hash_int(X+1, Y+1, Z+1), fx-1.0, fy-1.0, fz-1.0), + u, v, w); + return mx_gradient_scale3d(result); +} + +vec3 mx_perlin_noise_vec3(vec2 p) +{ + int X, Y; + float fx = mx_floorfrac(p.x, X); + float fy = mx_floorfrac(p.y, Y); + float u = mx_fade(fx); + float v = mx_fade(fy); + vec3 result = mx_bilerp( + mx_gradient_vec3(mx_hash_vec3(X , Y ), fx , fy ), + mx_gradient_vec3(mx_hash_vec3(X+1, Y ), fx-1.0, fy ), + mx_gradient_vec3(mx_hash_vec3(X , Y+1), fx , fy-1.0), + mx_gradient_vec3(mx_hash_vec3(X+1, Y+1), fx-1.0, fy-1.0), + u, v); + return mx_gradient_scale2d(result); +} + +vec3 mx_perlin_noise_vec3(vec3 p) +{ + int X, Y, Z; + float fx = mx_floorfrac(p.x, X); + float fy = mx_floorfrac(p.y, Y); + float fz = mx_floorfrac(p.z, Z); + float u = mx_fade(fx); + float v = mx_fade(fy); + float w = mx_fade(fz); + vec3 result = mx_trilerp( + mx_gradient_vec3(mx_hash_vec3(X , Y , Z ), fx , fy , fz ), + mx_gradient_vec3(mx_hash_vec3(X+1, Y , Z ), fx-1.0, fy , fz ), + mx_gradient_vec3(mx_hash_vec3(X , Y+1, Z ), fx , fy-1.0, fz ), + mx_gradient_vec3(mx_hash_vec3(X+1, Y+1, Z ), fx-1.0, fy-1.0, fz ), + mx_gradient_vec3(mx_hash_vec3(X , Y , Z+1), fx , fy , fz-1.0), + mx_gradient_vec3(mx_hash_vec3(X+1, Y , Z+1), fx-1.0, fy , fz-1.0), + mx_gradient_vec3(mx_hash_vec3(X , Y+1, Z+1), fx , fy-1.0, fz-1.0), + mx_gradient_vec3(mx_hash_vec3(X+1, Y+1, Z+1), fx-1.0, fy-1.0, fz-1.0), + u, v, w); + return mx_gradient_scale3d(result); +} + +float mx_cell_noise_float(float p) +{ + int ix = mx_floor(p); + return mx_bits_to_01(mx_hash_int(ix)); +} + +float mx_cell_noise_float(vec2 p) +{ + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + return mx_bits_to_01(mx_hash_int(ix, iy)); +} + +float mx_cell_noise_float(vec3 p) +{ + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + int iz = mx_floor(p.z); + return mx_bits_to_01(mx_hash_int(ix, iy, iz)); +} + +float mx_cell_noise_float(vec4 p) +{ + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + int iz = mx_floor(p.z); + int iw = mx_floor(p.w); + return mx_bits_to_01(mx_hash_int(ix, iy, iz, iw)); +} + +vec3 mx_cell_noise_vec3(float p) +{ + int ix = mx_floor(p); + return vec3( + mx_bits_to_01(mx_hash_int(ix, 0)), + mx_bits_to_01(mx_hash_int(ix, 1)), + mx_bits_to_01(mx_hash_int(ix, 2)) + ); +} + +vec3 mx_cell_noise_vec3(vec2 p) +{ + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + return vec3( + mx_bits_to_01(mx_hash_int(ix, iy, 0)), + mx_bits_to_01(mx_hash_int(ix, iy, 1)), + mx_bits_to_01(mx_hash_int(ix, iy, 2)) + ); +} + +vec3 mx_cell_noise_vec3(vec3 p) +{ + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + int iz = mx_floor(p.z); + return vec3( + mx_bits_to_01(mx_hash_int(ix, iy, iz, 0)), + mx_bits_to_01(mx_hash_int(ix, iy, iz, 1)), + mx_bits_to_01(mx_hash_int(ix, iy, iz, 2)) + ); +} + +vec3 mx_cell_noise_vec3(vec4 p) +{ + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + int iz = mx_floor(p.z); + int iw = mx_floor(p.w); + return vec3( + mx_bits_to_01(mx_hash_int(ix, iy, iz, iw, 0)), + mx_bits_to_01(mx_hash_int(ix, iy, iz, iw, 1)), + mx_bits_to_01(mx_hash_int(ix, iy, iz, iw, 2)) + ); +} + +float mx_fractal_noise_float(vec3 p, int octaves, float lacunarity, float diminish) +{ + float result = 0.0; + float amplitude = 1.0; + for (int i = 0; i < octaves; ++i) + { + result += amplitude * mx_perlin_noise_float(p); + amplitude *= diminish; + p *= lacunarity; + } + return result; +} + +vec3 mx_fractal_noise_vec3(vec3 p, int octaves, float lacunarity, float diminish) +{ + vec3 result = vec3(0.0); + float amplitude = 1.0; + for (int i = 0; i < octaves; ++i) + { + result += amplitude * mx_perlin_noise_vec3(p); + amplitude *= diminish; + p *= lacunarity; + } + return result; +} + +vec2 mx_fractal_noise_vec2(vec3 p, int octaves, float lacunarity, float diminish) +{ + return vec2(mx_fractal_noise_float(p, octaves, lacunarity, diminish), + mx_fractal_noise_float(p+vec3(19, 193, 17), octaves, lacunarity, diminish)); +} + +vec4 mx_fractal_noise_vec4(vec3 p, int octaves, float lacunarity, float diminish) +{ + vec3 c = mx_fractal_noise_vec3(p, octaves, lacunarity, diminish); + float f = mx_fractal_noise_float(p+vec3(19, 193, 17), octaves, lacunarity, diminish); + return vec4(c, f); +} + +float mx_worley_distance(vec2 p, int x, int y, int xoff, int yoff, float jitter, int metric) +{ + vec3 tmp = mx_cell_noise_vec3(vec2(x+xoff, y+yoff)); + vec2 off = vec2(tmp.x, tmp.y); + + off -= 0.5f; + off *= jitter; + off += 0.5f; + + vec2 cellpos = vec2(float(x), float(y)) + off; + vec2 diff = cellpos - p; + if (metric == 2) + return abs(diff.x) + abs(diff.y); // Manhattan distance + if (metric == 3) + return max(abs(diff.x), abs(diff.y)); // Chebyshev distance + // Either Euclidian or Distance^2 + return dot(diff, diff); +} + +float mx_worley_distance(vec3 p, int x, int y, int z, int xoff, int yoff, int zoff, float jitter, int metric) +{ + vec3 off = mx_cell_noise_vec3(vec3(x+xoff, y+yoff, z+zoff)); + + off -= 0.5f; + off *= jitter; + off += 0.5f; + + vec3 cellpos = vec3(float(x), float(y), float(z)) + off; + vec3 diff = cellpos - p; + if (metric == 2) + return abs(diff.x) + abs(diff.y) + abs(diff.z); // Manhattan distance + if (metric == 3) + return max(max(abs(diff.x), abs(diff.y)), abs(diff.z)); // Chebyshev distance + // Either Euclidian or Distance^2 + return dot(diff, diff); +} + +float mx_worley_noise_float(vec2 p, float jitter, int metric) +{ + int X, Y; + vec2 localpos = vec2(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y)); + float sqdist = 1e6f; // Some big number for jitter > 1 (not all GPUs may be IEEE) + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + float dist = mx_worley_distance(localpos, x, y, X, Y, jitter, metric); + sqdist = min(sqdist, dist); + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; +} + +vec2 mx_worley_noise_vec2(vec2 p, float jitter, int metric) +{ + int X, Y; + vec2 localpos = vec2(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y)); + vec2 sqdist = vec2(1e6f, 1e6f); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + float dist = mx_worley_distance(localpos, x, y, X, Y, jitter, metric); + if (dist < sqdist.x) + { + sqdist.y = sqdist.x; + sqdist.x = dist; + } + else if (dist < sqdist.y) + { + sqdist.y = dist; + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; +} + +vec3 mx_worley_noise_vec3(vec2 p, float jitter, int metric) +{ + int X, Y; + vec2 localpos = vec2(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y)); + vec3 sqdist = vec3(1e6f, 1e6f, 1e6f); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + float dist = mx_worley_distance(localpos, x, y, X, Y, jitter, metric); + if (dist < sqdist.x) + { + sqdist.z = sqdist.y; + sqdist.y = sqdist.x; + sqdist.x = dist; + } + else if (dist < sqdist.y) + { + sqdist.z = sqdist.y; + sqdist.y = dist; + } + else if (dist < sqdist.z) + { + sqdist.z = dist; + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; +} + +float mx_worley_noise_float(vec3 p, float jitter, int metric) +{ + int X, Y, Z; + vec3 localpos = vec3(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y), mx_floorfrac(p.z, Z)); + float sqdist = 1e6f; + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + for (int z = -1; z <= 1; ++z) + { + float dist = mx_worley_distance(localpos, x, y, z, X, Y, Z, jitter, metric); + sqdist = min(sqdist, dist); + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; +} + +vec2 mx_worley_noise_vec2(vec3 p, float jitter, int metric) +{ + int X, Y, Z; + vec3 localpos = vec3(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y), mx_floorfrac(p.z, Z)); + vec2 sqdist = vec2(1e6f, 1e6f); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + for (int z = -1; z <= 1; ++z) + { + float dist = mx_worley_distance(localpos, x, y, z, X, Y, Z, jitter, metric); + if (dist < sqdist.x) + { + sqdist.y = sqdist.x; + sqdist.x = dist; + } + else if (dist < sqdist.y) + { + sqdist.y = dist; + } + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; +} + +vec3 mx_worley_noise_vec3(vec3 p, float jitter, int metric) +{ + int X, Y, Z; + vec3 localpos = vec3(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y), mx_floorfrac(p.z, Z)); + vec3 sqdist = vec3(1e6f, 1e6f, 1e6f); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + for (int z = -1; z <= 1; ++z) + { + float dist = mx_worley_distance(localpos, x, y, z, X, Y, Z, jitter, metric); + if (dist < sqdist.x) + { + sqdist.z = sqdist.y; + sqdist.y = sqdist.x; + sqdist.x = dist; + } + else if (dist < sqdist.y) + { + sqdist.z = sqdist.y; + sqdist.y = dist; + } + else if (dist < sqdist.z) + { + sqdist.z = dist; + } + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; +} +/* +Color transform functions. + +These funcions are modified versions of the color operators found in Open Shading Language: +github.com/imageworks/OpenShadingLanguage/blob/master/src/liboslexec/opcolor.cpp + +It contains the subset of color operators needed to implement the MaterialX +standard library. The modifications are for conversions from C++ to GLSL. + +Original copyright notice: +------------------------------------------------------------------------ +Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of Sony Pictures Imageworks nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +------------------------------------------------------------------------ +*/ + +vec3 mx_hsvtorgb(vec3 hsv) +{ + // Reference for this technique: Foley & van Dam + float h = hsv.x; float s = hsv.y; float v = hsv.z; + if (s < 0.0001f) { + return vec3 (v, v, v); + } else { + h = 6.0f * (h - floor(h)); // expand to [0..6) + int hi = int(trunc(h)); + float f = h - float(hi); + float p = v * (1.0f-s); + float q = v * (1.0f-s*f); + float t = v * (1.0f-s*(1.0f-f)); + if (hi == 0) + return vec3 (v, t, p); + else if (hi == 1) + return vec3 (q, v, p); + else if (hi == 2) + return vec3 (p, v, t); + else if (hi == 3) + return vec3 (p, q, v); + else if (hi == 4) + return vec3 (t, p, v); + return vec3 (v, p, q); + } +} + + +vec3 mx_rgbtohsv(vec3 c) +{ + // See Foley & van Dam + float r = c.x; float g = c.y; float b = c.z; + float mincomp = min (r, min(g, b)); + float maxcomp = max (r, max(g, b)); + float delta = maxcomp - mincomp; // chroma + float h, s, v; + v = maxcomp; + if (maxcomp > 0.0f) + s = delta / maxcomp; + else s = 0.0f; + if (s <= 0.0f) + h = 0.0f; + else { + if (r >= maxcomp) h = (g-b) / delta; + else if (g >= maxcomp) h = 2.0f + (b-r) / delta; + else h = 4.0f + (r-g) / delta; + h *= (1.0f/6.0f); + if (h < 0.0f) + h += 1.0f; + } + return vec3(h, s, v); +} +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} +void mx_noise2d_float(float amplitude, float pivot, vector2 texcoord, output float result) +{ + float value = noise("snoise", texcoord.x, texcoord.y); + result = value * amplitude + pivot; +} +void mx_worleynoise2d_float(vector2 texcoord, float jitter, output float result) +{ + result = mx_worley_noise_float(texcoord, jitter, 0); +} +void mx_fractal3d_vector2(vector2 amplitude, int octaves, float lacunarity, float diminish, vector position, output vector2 result) +{ + vector2 f = mx_fbm(position, octaves, lacunarity, diminish, "snoise"); + result = f * amplitude; +} +void mx_surface_unlit(float emission_weight, color emission_color, float transmission_weight, color transmission_color, float opacity, output surfaceshader result) +{ + float trans = clamp(transmission_weight, 0.0, 1.0); + result.bsdf = trans * transmission_color * transparent(); + result.edf = (1.0 - trans) * emission_weight * emission_color * emission(); + result.opacity = clamp(opacity, 0.0, 1.0); +} +#include "lib/$fileTransformUv" + +void mx_image_vector2(textureresource file, string layer, vector2 default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector2 out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value.x, default_value.y, 0.0); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out.x = rgb[0]; + out.y = rgb[1]; +} +void mx_worleynoise3d_float(vector position, float jitter, output float result) +{ + result = mx_worley_noise_float(position, jitter, 0); +} +void mx_noise2d_vector2(vector2 amplitude, float pivot, vector2 texcoord, output vector2 result) +{ + vector2 value = mx_noise("snoise", texcoord.x, texcoord.y); + result = value * amplitude + pivot; +} +void mx_geompropvalue_vector4(string geomprop, vector4 defaultVal, output vector4 out) +{ + float value[4]; + if (getattribute(geomprop, value) == 0) + { + out = defaultVal; + } + else + { + out.x = value[0]; + out.y = value[1]; + out.z = value[2]; + out.w = value[3]; + } +} +#include "mx_burn_float.osl" + +void mx_burn_color3(color fg, color bg, float mix, output color result) +{ + mx_burn_float(fg[0], bg[0], mix, result[0]); + mx_burn_float(fg[1], bg[1], mix, result[1]); + mx_burn_float(fg[2], bg[2], mix, result[2]); +} +void mx_geomcolor_float(int index, output float result) +{ + getattribute("color", result); +} +#include "mx_burn_float.osl" + +void mx_burn_color4(color4 fg, color4 bg, float mix, output color4 result) +{ + mx_burn_float(fg.rgb[0], bg.rgb[0], mix, result.rgb[0]); + mx_burn_float(fg.rgb[1], bg.rgb[1], mix, result.rgb[1]); + mx_burn_float(fg.rgb[2], bg.rgb[2], mix, result.rgb[2]); + mx_burn_float(fg.a, bg.a, mix, result.a); +} +#include "mx_dodge_float.osl" + +void mx_dodge_color3(color fg, color bg, float mix, output color result) +{ + mx_dodge_float(fg[0], bg[0], mix, result[0]); + mx_dodge_float(fg[1], bg[1], mix, result[1]); + mx_dodge_float(fg[2], bg[2], mix, result[2]); +} +void mx_rgbtohsv_color4(color4 _in, output color4 result) +{ + result = color4(transformc("rgb","hsv", _in.rgb), 1.0); +} +void mx_geompropvalue_color(string geomprop, color defaultVal, output color out) +{ + if (getattribute(geomprop, out) == 0) + out = defaultVal; +} +void mx_hsvtorgb_color3(vector _in, output vector result) +{ + result = transformc("hsv","rgb", _in); +} +void mx_geompropvalue_color4(string geomprop, color4 defaultVal, output color4 out) +{ + float value[4]; + if (getattribute(geomprop, value) == 0) + { + out.rgb = defaultVal.rgb; + out.a = defaultVal.a; + } + else + { + out.rgb[0] = value[0]; + out.rgb[1] = value[1]; + out.rgb[2] = value[2]; + out.a = value[3]; + } +} +void mx_ambientocclusion_float(float coneangle, float maxdistance, output float result) +{ + // This node is a stub and does not currently operate to specification + result = 0; +} +void mx_disjointover_color4(color4 fg, color4 bg, float mix, output color4 result) +{ + float summedAlpha = fg.a + bg.a; + + if (summedAlpha <= 1) + { + result.rgb = fg.rgb + bg.rgb; + } + else + { + if (abs(bg.a) < M_FLOAT_EPS) + { + result.rgb = 0.0; + } + else + { + float x = (1 - fg.a) / bg.a; + result.rgb = fg.rgb + bg.rgb * x; + } + } + result.a = min(summedAlpha, 1.0); + + result.rgb = result.rgb * mix + (1.0 - mix) * bg.rgb; + result.a = result.a * mix + (1.0 - mix) * bg.a; +} +void mx_geompropvalue_vector2(string geomprop, vector2 defaultVal, output vector2 out) +{ + float value[2]; + if (getattribute(geomprop, value) == 0) + { + out = defaultVal; + } + else + { + out.x = value[0]; + out.y = value[1]; + } +} +void mx_cellnoise3d_float(vector position, output float result) +{ + result = cellnoise(position); +} +void mx_mix_surfaceshader(surfaceshader fg, surfaceshader bg, float w, output surfaceshader result) +{ + result.bsdf = mix(bg.bsdf, fg.bsdf, w); + result.edf = mix(bg.edf, fg.edf, w); + result.opacity = mix(bg.opacity, fg.opacity, w); +} +void mx_time_float(float fps, output float result) +{ + float frame; + getattribute("frame", frame); + result = frame / fps; +} +void mx_premult_color4(color4 in, output color4 result) +{ + result = color4(in.rgb * in.a, in.a); +} +void mx_geompropvalue_integer(string geomprop, int defaultVal, output int out) +{ + if (getattribute(geomprop, out) == 0) + out = defaultVal; +} +void mx_noise3d_vector2(vector2 amplitude, float pivot, vector position, output vector2 result) +{ + vector2 value = mx_noise("snoise", position); + result = value * amplitude + pivot; +} +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} +void mx_noise3d_vector3(vector amplitude, float pivot, vector position, output vector result) +{ + vector value = noise("snoise", position); + result = value * amplitude + pivot; +} +void mx_geompropvalue_boolean(string geomprop, int defaultVal, output int out) +{ + if (getattribute(geomprop, out) == 0) + out = defaultVal; +} +#include "lib/$fileTransformUv" + +void mx_image_color4(textureresource file, string layer, color4 default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color4 out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value.rgb; + float missingAlpha = default_value.a; + vector2 st = mx_transform_uv(texcoord); + float alpha; + color rgb = texture(file.filename, st.x, st.y, "alpha", alpha, "subimage", layer, + "missingcolor", missingColor, "missingalpha", missingAlpha, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); + + out = color4(rgb, alpha); +} +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} +#include "lib/$fileTransformUv" + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} +#include "lib/$fileTransformUv" + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} +void mx_worleynoise3d_vector3(vector position, float jitter, output vector result) +{ + result = mx_worley_noise_vector3(position, jitter, 0); +} +void mx_rotate_vector2(vector2 _in, float amount, output vector2 result) +{ + float rotationRadians = radians(amount); + float sa = sin(rotationRadians); + float ca = cos(rotationRadians); + result = vector2(ca*_in.x + sa*_in.y, -sa*_in.x + ca*_in.y); +} +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} +void mx_dodge_float(float fg, float bg, float mix, output float out) +{ + if (abs(1.0 - fg) < M_FLOAT_EPS) + { + out = 0.0; + return; + } + out = mix*(bg / (1.0 - fg)) + ((1.0-mix)*bg); +} +void mx_worleynoise2d_vector3(vector2 texcoord, float jitter, output vector result) +{ + result = mx_worley_noise_vector3(texcoord, jitter, 0); +} +void mx_worleynoise2d_vector2(vector2 texcoord, float jitter, output vector2 result) +{ + result = mx_worley_noise_vector2(texcoord, jitter, 0); +} +void mx_noise2d_vector3(vector amplitude, float pivot, vector2 texcoord, output vector result) +{ + vector value = noise("snoise", texcoord.x, texcoord.y); + result = value * amplitude + pivot; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +void mx_fractal3d_vector4(vector4 amplitude, int octaves, float lacunarity, float diminish, vector position, output vector4 result) +{ + vector4 f = mx_fbm(position, octaves, lacunarity, diminish, "snoise"); + result = f * amplitude; +} +#include "lib/$fileTransformUv" + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} +void mx_burn_float(float fg, float bg, float mix, output float result) +{ + if (abs(fg) < M_FLOAT_EPS) + { + result = 0.0; + return; + } + result = mix*(1.0 - ((1.0 - bg) / fg)) + ((1.0-mix)*bg); +} +void mx_heighttonormal_vector3(float in, float scale, output vector result) +{ + point htP = P + normalize(N) * in * scale; + result = normalize(calculatenormal(htP)); +} +void mx_luminance_color4(color4 in, color lumacoeffs, output color4 result) +{ + result = color4(dot(in.rgb, lumacoeffs), in.a); +} +void mx_frame_float(output float result) +{ + getattribute("frame", result); +} +void mx_geomcolor_color4(int index, output color4 result) +{ + float value[4]; + getattribute("color", value); + result.rgb[0] = value[0]; + result.rgb[1] = value[1]; + result.rgb[2] = value[2]; + result.a = value[3]; +} +void mx_unpremult_color4(color4 in, output color4 result) +{ + result = color4(in.rgb / in.a, in.a); +} +void mx_transformmatrix_vector2M3(vector2 val, matrix m, output vector2 result) +{ + point res = transform(m, point(val.x, val.y, 1.0)); + result.x = res[0]; + result.y = res[1]; +} +void mx_geomcolor_color3(int index, output color result) +{ + getattribute("color", result); +} +void mx_noise2d_vector4(vector4 amplitude, float pivot, vector2 texcoord, output vector4 result) +{ + vector4 value = mx_noise("snoise", texcoord.x, texcoord.y); + result = value * amplitude + pivot; +} +void mx_hsvtorgb_color4(color4 _in, output color4 result) +{ + result = color4(transformc("hsv","rgb", _in.rgb), 1.0); +} +void mx_worleynoise3d_vector2(vector position, float jitter, output vector2 result) +{ + result = mx_worley_noise_vector2(position, jitter, 0); +} +void mx_cellnoise2d_float(vector2 texcoord, output float result) +{ + result = cellnoise(texcoord.x, texcoord.y); +} +void mx_fractal3d_vector3(vector amplitude, int octaves, float lacunarity, float diminish, vector position, output vector result) +{ + vector f = mx_fbm(position, octaves, lacunarity, diminish, "snoise"); + result = f * amplitude; +} +#include "mx_dodge_float.osl" + +void mx_dodge_color4(color4 fg , color4 bg , float mix , output color4 result) +{ + mx_dodge_float(fg.rgb[0], bg.rgb[0], mix, result.rgb[0]); + mx_dodge_float(fg.rgb[1], bg.rgb[1], mix, result.rgb[1]); + mx_dodge_float(fg.rgb[2], bg.rgb[2], mix, result.rgb[2]); + mx_dodge_float(fg.a, bg.a, mix, result.a); +} +void mx_geompropvalue_vector(string geomprop, vector defaultVal, output vector out) +{ + if (getattribute(geomprop, out) == 0) + out = defaultVal; +} +void mx_geompropvalue_float(string geomprop, float defaultVal, output float result) +{ + if (getattribute(geomprop, result) == 0) + { + result = defaultVal; + } +} +void mx_noise3d_float(float amplitude, float pivot, vector position, output float result) +{ + float value = noise("snoise", position); + result = value * amplitude + pivot; +} +void mx_creatematrix_vector3_matrix33(vector in1, vector in2, vector in3, output matrix result) +{ + result = matrix(in1.x, in1.y, in1.z, 0.0, + in2.x, in2.y, in2.z, 0.0, + in3.x, in3.y, in3.z, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_creatematrix_vector3_matrix44(vector in1, vector in2, vector in3, vector in4, output matrix result) +{ + result = matrix(in1.x, in1.y, in1.z, 0.0, + in2.x, in2.y, in2.z, 0.0, + in3.x, in3.y, in3.z, 0.0, + in4.x, in4.y, in4.z, 1.0); +} + +void mx_creatematrix_vector4_matrix44(vector4 in1, vector4 in2, vector4 in3, vector4 in4, output matrix result) +{ + result = matrix(in1.x, in1.y, in1.z, in1.w, + in2.x, in2.y, in2.z, in2.w, + in3.x, in3.y, in3.z, in3.w, + in4.x, in4.y, in4.z, in4.w); +} +void mx_noise3d_vector4(vector4 amplitude, float pivot, vector position, output vector4 result) +{ + vector4 value = mx_noise("snoise", position); + result = value * amplitude + pivot; +} +#include "lib/$fileTransformUv" + +void mx_image_vector4(textureresource file, string layer, vector4 default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector4 out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value.x, default_value.y, default_value.z); + float missingAlpha = default_value.w; + vector2 st = mx_transform_uv(texcoord); + float alpha; + color rgb = texture(file.filename, st.x, st.y, "alpha", alpha, "subimage", layer, + "missingcolor", missingColor, "missingalpha", missingAlpha, "swrap", uaddressmode, "twrap", vaddressmode); + + out = vector4(rgb[0], rgb[1], rgb[2], alpha); +} +void mx_fractal3d_float(float amplitude, int octaves, float lacunarity, float diminish, vector position, output float result) +{ + float f = mx_fbm(position, octaves, lacunarity, diminish, "snoise"); + result = f * amplitude; +} +void mx_rgbtohsv_color3(vector _in, output vector result) +{ + result = transformc("rgb","hsv", _in); +} +void mx_geompropvalue_string(string geomprop, string defaultVal, output string out) +{ + if (getattribute(geomprop, out) == 0) + out = defaultVal; +} +// Open Shading Language : Copyright (c) 2009-2017 Sony Pictures Imageworks Inc., et al. +// https://github.com/imageworks/OpenShadingLanguage/blob/master/LICENSE + +#pragma once +#define VECTOR2_H + +// vector2 is a 2D vector +struct vector2 +{ + float x; + float y; +}; + + + +// +// For vector2, define math operators to match vector +// + +vector2 __operator__neg__(vector2 a) +{ + return vector2(-a.x, -a.y); +} + +vector2 __operator__add__(vector2 a, vector2 b) +{ + return vector2(a.x + b.x, a.y + b.y); +} + +vector2 __operator__add__(vector2 a, int b) +{ + return a + vector2(b, b); +} + +vector2 __operator__add__(vector2 a, float b) +{ + return a + vector2(b, b); +} + +vector2 __operator__add__(int a, vector2 b) +{ + return vector2(a, a) + b; +} + +vector2 __operator__add__(float a, vector2 b) +{ + return vector2(a, a) + b; +} + +vector2 __operator__sub__(vector2 a, vector2 b) +{ + return vector2(a.x - b.x, a.y - b.y); +} + +vector2 __operator__sub__(vector2 a, int b) +{ + return a - vector2(b, b); +} + +vector2 __operator__sub__(vector2 a, float b) +{ + return a - vector2(b, b); +} + +vector2 __operator__sub__(int a, vector2 b) +{ + return vector2(a, a) - b; +} + +vector2 __operator__sub__(float a, vector2 b) +{ + return vector2(a, a) - b; +} + +vector2 __operator__mul__(vector2 a, vector2 b) +{ + return vector2(a.x * b.x, a.y * b.y); +} + +vector2 __operator__mul__(vector2 a, int b) +{ + return a * vector2(b, b); +} + +vector2 __operator__mul__(vector2 a, float b) +{ + return a * vector2(b, b); +} + +vector2 __operator__mul__(int a, vector2 b) +{ + return b * vector2(a, a); +} + +vector2 __operator__mul__(float a, vector2 b) +{ + return b * vector2(a, a); +} + +vector2 __operator__div__(vector2 a, vector2 b) +{ + return vector2(a.x / b.x, a.y / b.y); +} + +vector2 __operator__div__(vector2 a, int b) +{ + float b_inv = 1.0/b; + return a * vector2(b_inv, b_inv); +} + +vector2 __operator__div__(vector2 a, float b) +{ + float b_inv = 1.0/b; + return a * vector2(b_inv, b_inv); +} + +vector2 __operator__div__(int a, vector2 b) +{ + return vector2(a, a) / b; +} + +vector2 __operator__div__(float a, vector2 b) +{ + return vector2(a, a) / b; +} + +int __operator__eq__(vector2 a, vector2 b) +{ + return (a.x == b.x) && (a.y == b.y); +} + +int __operator__ne__(vector2 a, vector2 b) +{ + return (a.x != b.x) || (a.y != b.y); +} + + + + +// +// For vector2, define most of the stdosl functions to match vector +// + +vector2 abs(vector2 a) +{ + return vector2 (abs(a.x), abs(a.y)); +} + +vector2 ceil(vector2 a) +{ + return vector2 (ceil(a.x), ceil(a.y)); +} + +vector2 round(vector2 a) +{ + return vector2 (round(a.x), round(a.y)); +} + +vector2 floor(vector2 a) +{ + return vector2 (floor(a.x), floor(a.y)); +} + +vector2 sqrt(vector2 a) +{ + return vector2 (sqrt(a.x), sqrt(a.y)); +} + +vector2 exp(vector2 a) +{ + return vector2 (exp(a.x), exp(a.y)); +} + +vector2 log(vector2 a) +{ + return vector2 (log(a.x), log(a.y)); +} + +vector2 log2(vector2 a) +{ + return vector2 (log2(a.x), log2(a.y)); +} + +vector2 mix(vector2 a, vector2 b, float x ) +{ + return vector2 (mix(a.x, b.x, x), mix(a.y, b.y, x)); +} + +vector2 mix(vector2 a, vector2 b, vector2 x ) +{ + return vector2 (mix(a.x, b.x, x.x), mix(a.y, b.y, x.y)); +} + +float dot(vector2 a, vector2 b) +{ + return (a.x * b.x + a.y * b.y); +} + +float length (vector2 a) +{ + return hypot (a.x, a.y); +} + +vector2 smoothstep(vector2 low, vector2 high, vector2 in) +{ + return vector2 (smoothstep(low.x, high.x, in.x), + smoothstep(low.y, high.y, in.y)); +} + +vector2 smoothstep(float low, float high, vector2 in) +{ + return vector2 (smoothstep(low, high, in.x), + smoothstep(low, high, in.y)); +} + +vector2 clamp(vector2 in, vector2 low, vector2 high) +{ + return vector2 (clamp(in.x, low.x, high.x), + clamp(in.y, low.y, high.y)); +} + +vector2 clamp(vector2 in, float low, float high) +{ + return clamp(in, vector2(low, low), vector2(high, high)); +} + +vector2 max(vector2 a, vector2 b) +{ + return vector2 (max(a.x, b.x), + max(a.y, b.y)); +} + +vector2 max(vector2 a, float b) +{ + return max(a, vector2(b, b)); +} + +vector2 normalize(vector2 a) +{ + return a / length(a); +} + +vector2 min(vector2 a, vector2 b) +{ + return vector2 (min(a.x, a.x), + min(b.y, b.y)); +} + +vector2 min(vector2 a, float b) +{ + return min(a, vector2(b, b)); +} + +vector2 mod(vector2 a, vector2 b) +{ + return vector2(mod(a.x, b.x), + mod(a.y, b.y)); +} + +vector2 mod(vector2 a, float b) +{ + return mod(a, vector2(b, b)); +} + +vector2 fmod(vector2 a, vector2 b) +{ + return vector2 (fmod(a.x, b.x), + fmod(a.y, b.y)); +} + +vector2 fmod(vector2 a, float b) +{ + return fmod(a, vector2(b, b)); +} + +vector2 pow(vector2 in, vector2 amount) +{ + return vector2(pow(in.x, amount.x), + pow(in.y, amount.y)); +} + +vector2 pow(vector2 in, float amount) +{ + return vector2(pow(in.x, amount), + pow(in.y, amount)); +} + +vector2 sign(vector2 a) +{ + return vector2(sign(a.x), + sign(a.y)); +} + +vector2 sin(vector2 a) +{ + return vector2(sin(a.x), + sin(a.y)); +} + +vector2 cos(vector2 a) +{ + return vector2(cos(a.x), + cos(a.y)); +} + +vector2 tan(vector2 a) +{ + return vector2(tan(a.x), + tan(a.y)); +} + +vector2 asin(vector2 a) +{ + return vector2(asin(a.x), + asin(a.y)); +} + +vector2 acos(vector2 a) +{ + return vector2(acos(a.x), + acos(a.y)); +} + +vector2 atan2(vector2 a, float f) +{ + return vector2(atan2(a.x, f), + atan2(a.y, f)); +} + +vector2 atan2(vector2 a, vector2 b) +{ + return vector2(atan2(a.x, b.x), + atan2(a.y, b.y)); +} + + +// Open Shading Language : Copyright (c) 2009-2017 Sony Pictures Imageworks Inc., et al. +// https://github.com/imageworks/OpenShadingLanguage/blob/master/LICENSE + +#pragma once +#define VECTOR4_H + + +// vector4 is a 4D vector +struct vector4 +{ + float x; + float y; + float z; + float w; +}; + + + +// +// For vector4, define math operators to match vector +// + +vector4 __operator__neg__(vector4 a) +{ + return vector4(-a.x, -a.y, -a.z, -a.w); +} + +vector4 __operator__add__(vector4 a, vector4 b) +{ + return vector4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); +} + +vector4 __operator__add__(vector4 a, int b) +{ + return a + vector4(b, b, b, b); +} + +vector4 __operator__add__(vector4 a, float b) +{ + return a + vector4(b, b, b, b); +} + +vector4 __operator__add__(int a, vector4 b) +{ + return vector4(a, a, a, a) + b; +} + +vector4 __operator__add__(float a, vector4 b) +{ + return vector4(a, a, a, a) + b; +} + +vector4 __operator__sub__(vector4 a, vector4 b) +{ + return vector4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); +} + +vector4 __operator__sub__(vector4 a, int b) +{ + return a - vector4(b, b, b, b); +} + +vector4 __operator__sub__(vector4 a, float b) +{ + return a - vector4(b, b, b, b); +} + +vector4 __operator__sub__(int a, vector4 b) +{ + return vector4(a, a, a, a) - b; +} + +vector4 __operator__sub__(float a, vector4 b) +{ + return vector4(a, a, a, a) - b; +} + +vector4 __operator__mul__(vector4 a, vector4 b) +{ + return vector4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); +} + +vector4 __operator__mul__(vector4 a, int b) +{ + return a * vector4(b, b, b, b); +} + +vector4 __operator__mul__(vector4 a, float b) +{ + return a * vector4(b, b, b, b); +} + +vector4 __operator__mul__(int a, vector4 b) +{ + return vector4(a, a, a, a) * b; +} + +vector4 __operator__mul__(float a, vector4 b) +{ + return vector4(a, a, a, a) * b; +} + +vector4 __operator__div__(vector4 a, vector4 b) +{ + return vector4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w); +} + +vector4 __operator__div__(vector4 a, int b) +{ + float b_inv = 1.0/b; + return a * vector4(b_inv, b_inv, b_inv, b_inv); +} + +vector4 __operator__div__(vector4 a, float b) +{ + float b_inv = 1.0/b; + return a * vector4(b_inv, b_inv, b_inv, b_inv); +} + +vector4 __operator__div__(int a, vector4 b) +{ + return vector4(a, a, a, a) / b; +} + +vector4 __operator__div__(float a, vector4 b) +{ + return vector4(a, a, a, a) / b; +} + +int __operator__eq__(vector4 a, vector4 b) +{ + return (a.x == b.x) && (a.y == b.y) && (a.z == b.z) && (a.w == b.w); +} + +int __operator__ne__(vector4 a, vector4 b) +{ + return (a.x != b.x) || (a.y != b.y) || (a.z != b.z) || (a.w != b.w); +} + + + + +// +// For vector4, define most of the stdosl functions to match vector +// + +vector4 abs(vector4 in) +{ + return vector4 (abs(in.x), + abs(in.y), + abs(in.z), + abs(in.w)); +} + +vector4 ceil(vector4 in) +{ + return vector4 (ceil(in.x), + ceil(in.y), + ceil(in.z), + ceil(in.w)); +} + +vector4 round(vector4 in) +{ + return vector4 (round(in.x), + round(in.y), + round(in.z), + round(in.w)); +} + +vector4 floor(vector4 in) +{ + return vector4 (floor(in.x), + floor(in.y), + floor(in.z), + floor(in.w)); +} + +vector4 sqrt(vector4 in) +{ + return vector4 (sqrt(in.x), + sqrt(in.y), + sqrt(in.z), + sqrt(in.w)); +} + +vector4 exp(vector4 in) +{ + return vector4 (exp(in.x), + exp(in.y), + exp(in.z), + exp(in.w)); +} + +vector4 log(vector4 in) +{ + return vector4 (log(in.x), + log(in.y), + log(in.z), + log(in.w)); +} + +vector4 log2(vector4 in) +{ + return vector4 (log2(in.x), + log2(in.y), + log2(in.z), + log2(in.w)); +} + +vector4 mix(vector4 value1, vector4 value2, float x ) +{ + return vector4 (mix( value1.x, value2.x, x), + mix( value1.y, value2.y, x), + mix( value1.z, value2.z, x), + mix( value1.w, value2.w, x)); +} + +vector4 mix(vector4 value1, vector4 value2, vector4 x ) +{ + return vector4 (mix( value1.x, value2.x, x.x), + mix( value1.y, value2.y, x.y), + mix( value1.z, value2.z, x.z), + mix( value1.w, value2.w, x.w)); +} + +vector vec4ToVec3(vector4 v) +{ + return vector(v.x, v.y, v.z) / v.w; +} + +float dot(vector4 a, vector4 b) +{ + return ((a.x * b.x) + (a.y * b.y) + (a.z * b.z) + (a.w * b.w)); +} + +float length (vector4 a) +{ + return sqrt (a.x*a.x + a.y*a.y + a.z*a.z + a.w*a.w); +} + +vector4 smoothstep(vector4 low, vector4 high, vector4 in) +{ + return vector4 (smoothstep(low.x, high.x, in.x), + smoothstep(low.y, high.y, in.y), + smoothstep(low.z, high.z, in.z), + smoothstep(low.w, high.w, in.w)); +} + +vector4 smoothstep(float low, float high, vector4 in) +{ + return vector4 (smoothstep(low, high, in.x), + smoothstep(low, high, in.y), + smoothstep(low, high, in.z), + smoothstep(low, high, in.w)); +} + +vector4 clamp(vector4 in, vector4 low, vector4 high) +{ + return vector4 (clamp(in.x, low.x, high.x), + clamp(in.y, low.y, high.y), + clamp(in.z, low.z, high.z), + clamp(in.w, low.w, high.w)); +} + +vector4 clamp(vector4 in, float low, float high) +{ + return vector4 (clamp(in.x, low, high), + clamp(in.y, low, high), + clamp(in.z, low, high), + clamp(in.w, low, high)); +} + +vector4 max(vector4 a, vector4 b) +{ + return vector4 (max(a.x, b.x), + max(a.y, b.y), + max(a.z, b.z), + max(a.w, b.w)); +} + +vector4 max(vector4 a, float b) +{ + return max(a, vector4(b, b, b, b)); +} + +vector4 normalize(vector4 a) +{ + return a / length(a); +} + +vector4 min(vector4 a, vector4 b) +{ + return vector4 (min(a.x, b.x), + min(a.y, b.y), + min(a.z, b.z), + min(a.w, b.w)); +} + +vector4 min(vector4 a, float b) +{ + return min(a, vector4(b, b, b, b)); +} + +vector4 mod(vector4 a, vector4 b) +{ + return vector4(mod(a.x, b.x), + mod(a.y, b.y), + mod(a.z, b.z), + mod(a.w, b.w)); +} + +vector4 mod(vector4 a, float b) +{ + return mod(a, vector4(b, b, b, b)); +} + +vector4 fmod(vector4 a, vector4 b) +{ + return vector4 (fmod(a.x, b.x), + fmod(a.y, b.y), + fmod(a.z, b.z), + fmod(a.w, b.w)); +} + +vector4 fmod(vector4 a, float b) +{ + return fmod(a, vector4(b, b, b, b)); +} + +vector4 pow(vector4 in, vector4 amount) +{ + return vector4 (pow(in.x, amount.x), + pow(in.y, amount.y), + pow(in.z, amount.z), + pow(in.w, amount.w)); +} + +vector4 pow(vector4 in, float amount) +{ + return vector4 (pow(in.x, amount), + pow(in.y, amount), + pow(in.z, amount), + pow(in.w, amount)); +} + +vector4 sign(vector4 a) +{ + return vector4(sign(a.x), + sign(a.y), + sign(a.z), + sign(a.w)); +} + +vector4 sin(vector4 a) +{ + return vector4(sin(a.x), + sin(a.y), + sin(a.z), + sin(a.w)); +} + +vector4 cos(vector4 a) +{ + return vector4(cos(a.x), + cos(a.y), + cos(a.z), + cos(a.w)); +} + +vector4 tan(vector4 a) +{ + return vector4(tan(a.x), + tan(a.y), + tan(a.z), + tan(a.w)); +} + +vector4 asin(vector4 a) +{ + return vector4(asin(a.x), + asin(a.y), + asin(a.z), + asin(a.w)); +} + +vector4 acos(vector4 a) +{ + return vector4(acos(a.x), + acos(a.y), + acos(a.z), + acos(a.w)); +} + +vector4 atan2(vector4 a, float f) +{ + return vector4(atan2(a.x, f), + atan2(a.y, f), + atan2(a.z, f), + atan2(a.w, f)); +} + +vector4 atan2(vector4 a, vector4 b) +{ + return vector4(atan2(a.x, b.x), + atan2(a.y, b.y), + atan2(a.z, b.z), + atan2(a.w, b.w)); +} + + +vector4 transform (matrix M, vector4 p) +{ + return vector4 (M[0][0]*p.x + M[1][0]*p.y + M[2][0]*p.z + M[3][0]*p.w, + M[0][1]*p.x + M[1][1]*p.y + M[2][1]*p.z + M[3][1]*p.w, + M[0][2]*p.x + M[1][2]*p.y + M[2][2]*p.z + M[3][2]*p.w, + M[0][3]*p.x + M[1][3]*p.y + M[2][3]*p.z + M[3][3]*p.w); +} + +vector4 transform (string fromspace, string tospace, vector4 p) +{ + return transform (matrix(fromspace,tospace), p); +} +// Open Shading Language : Copyright (c) 2009-2017 Sony Pictures Imageworks Inc., et al. +// https://github.com/imageworks/OpenShadingLanguage/blob/master/LICENSE +// +// MaterialX specification (c) 2017 Lucasfilm Ltd. +// http://www.materialx.org/ + +#pragma once + +#include "color4.h" +#include "vector2.h" +#include "vector4.h" +#include "matrix33.h" + +// +// Support functions for OSL implementations of the MaterialX nodes. +// + +float mx_ternary(int expr, float v1, float v2) { if (expr) return v1; else return v2; } +int mx_ternary(int expr, int v1, int v2) { if (expr) return v1; else return v2; } +color mx_ternary(int expr, color v1, color v2) { if (expr) return v1; else return v2; } +color4 mx_ternary(int expr, color4 v1, color4 v2) { if (expr) return v1; else return v2; } +vector mx_ternary(int expr, vector v1, vector v2) { if (expr) return v1; else return v2; } +vector2 mx_ternary(int expr, vector2 v1, vector2 v2) { if (expr) return v1; else return v2; } +vector4 mx_ternary(int expr, vector4 v1, vector4 v2) { if (expr) return v1; else return v2; } +matrix mx_ternary(int expr, matrix v1, matrix v2) { if (expr) return v1; else return v2; } +matrix33 mx_ternary(int expr, matrix33 v1, matrix33 v2) { if (expr) return v1; else return v2; } + + +matrix33 mx_add(matrix33 a, matrix33 b) +{ + return matrix33(matrix( + a.m[0][0]+b.m[0][0], a.m[0][1]+b.m[0][1], a.m[0][2]+b.m[0][2], 0.0, + a.m[1][0]+b.m[1][0], a.m[1][1]+b.m[1][1], a.m[1][2]+b.m[1][2], 0.0, + a.m[2][0]+b.m[2][0], a.m[2][1]+b.m[2][1], a.m[2][2]+b.m[2][2], 0.0, + 0.0, 0.0, 0.0, 1.0)); +} + +matrix33 mx_add(matrix33 a, float b) +{ + return matrix33(matrix( + a.m[0][0]+b, a.m[0][1]+b, a.m[0][2]+b, 0.0, + a.m[1][0]+b, a.m[1][1]+b, a.m[1][2]+b, 0.0, + a.m[2][0]+b, a.m[2][1]+b, a.m[2][2]+b, 0.0, + 0.0, 0.0, 0.0, 1.0)); +} + +matrix mx_add(matrix a, matrix b) +{ + return matrix( + a[0][0]+b[0][0], a[0][1]+b[0][1], a[0][2]+b[0][2], a[0][3]+b[0][3], + a[1][0]+b[1][0], a[1][1]+b[1][1], a[1][2]+b[1][2], a[1][3]+b[1][3], + a[2][0]+b[2][0], a[2][1]+b[2][1], a[2][2]+b[2][2], a[2][3]+b[2][3], + a[3][0]+b[3][0], a[3][1]+b[3][1], a[3][2]+b[3][2], a[3][3]+b[3][3]); +} + +matrix mx_add(matrix a, float b) +{ + return matrix( + a[0][0]+b, a[0][1]+b, a[0][2]+b, a[0][3]+b, + a[1][0]+b, a[1][1]+b, a[1][2]+b, a[1][3]+b, + a[2][0]+b, a[2][1]+b, a[2][2]+b, a[2][3]+b, + a[3][0]+b, a[3][1]+b, a[3][2]+b, a[3][3]+b); +} + + +matrix33 mx_subtract(matrix33 a, matrix33 b) +{ + return matrix33(matrix( + a.m[0][0]-b.m[0][0], a.m[0][1]-b.m[0][1], a.m[0][2]-b.m[0][2], 0.0, + a.m[1][0]-b.m[1][0], a.m[1][1]-b.m[1][1], a.m[1][2]-b.m[1][2], 0.0, + a.m[2][0]-b.m[2][0], a.m[2][1]-b.m[2][1], a.m[2][2]-b.m[2][2], 0.0, + 0.0, 0.0, 0.0, 1.0)); +} + +matrix33 mx_subtract(matrix33 a, float b) +{ + return matrix33(matrix( + a.m[0][0]-b, a.m[0][1]-b, a.m[0][2]-b, 0.0, + a.m[1][0]-b, a.m[1][1]-b, a.m[1][2]-b, 0.0, + a.m[2][0]-b, a.m[2][1]-b, a.m[2][2]-b, 0.0, + 0.0, 0.0, 0.0, 1.0)); +} + +matrix mx_subtract(matrix a, matrix b) +{ + return matrix( + a[0][0]-b[0][0], a[0][1]-b[0][1], a[0][2]-b[0][2], a[0][3]-b[0][3], + a[1][0]-b[1][0], a[1][1]-b[1][1], a[1][2]-b[1][2], a[1][3]-b[1][3], + a[2][0]-b[2][0], a[2][1]-b[2][1], a[2][2]-b[2][2], a[2][3]-b[2][3], + a[3][0]-b[3][0], a[3][1]-b[3][1], a[3][2]-b[3][2], a[3][3]-b[3][3]); +} + +matrix mx_subtract(matrix a, float b) +{ + return matrix( + a[0][0]-b, a[0][1]-b, a[0][2]-b, a[0][3]-b, + a[1][0]-b, a[1][1]-b, a[1][2]-b, a[1][3]-b, + a[2][0]-b, a[2][1]-b, a[2][2]-b, a[2][3]-b, + a[3][0]-b, a[3][1]-b, a[3][2]-b, a[3][3]-b); +} + + +float mx_extract(color in, int index) +{ + return in[index]; +} + +float mx_extract(color4 in, int index) +{ + if (index == 0) return in.rgb.r; + else if (index == 1) return in.rgb.g; + else if (index == 2) return in.rgb.b; + else return in.a; +} + +float mx_extract(vector2 in, int index) +{ + if (index == 0) return in.x; + else return in.y; +} + +float mx_extract(vector in, int index) +{ + return in[index]; +} + +float mx_extract(vector4 in, int index) +{ + if (index == 0) return in.x; + else if (index == 1) return in.y; + else if (index == 2) return in.z; + else return in.w; +} + + +float mx_remap(float in, float inLow, float inHigh, float outLow, float outHigh, int doClamp) +{ + float x = (in - inLow)/(inHigh-inLow); + if (doClamp == 1) { + x = clamp(x, 0, 1); + } + return outLow + (outHigh - outLow) * x; +} + +color mx_remap(color in, color inLow, color inHigh, color outLow, color outHigh, int doClamp) +{ + color x = (in - inLow) / (inHigh - inLow); + if (doClamp == 1) { + x = clamp(x, 0, 1); + } + return outLow + (outHigh - outLow) * x; +} + +color mx_remap(color in, float inLow, float inHigh, float outLow, float outHigh, int doClamp) +{ + color x = (in - inLow) / (inHigh - inLow); + if (doClamp == 1) { + x = clamp(x, 0, 1); + } + return outLow + (outHigh - outLow) * x; +} + +color4 mx_remap(color4 c, color4 inLow, color4 inHigh, color4 outLow, color4 outHigh, int doClamp) +{ + return color4(mx_remap(c.rgb, inLow.rgb, inHigh.rgb, outLow.rgb, outHigh.rgb, doClamp), + mx_remap(c.a, inLow.a, inHigh.a, outLow.a, outHigh.a, doClamp)); +} + +color4 mx_remap(color4 c, float inLow, float inHigh, float outLow, float outHigh, int doClamp) +{ + color4 c4_inLow = color4(color(inLow), inLow); + color4 c4_inHigh = color4(color(inHigh), inHigh); + color4 c4_outLow = color4(color(outLow), outLow); + color4 c4_outHigh = color4(color(outHigh), outHigh); + return mx_remap(c, c4_inLow, c4_inHigh, c4_outLow, c4_outHigh, doClamp); +} + +vector2 mx_remap(vector2 in, vector2 inLow, vector2 inHigh, vector2 outLow, vector2 outHigh, int doClamp) +{ + return vector2(mx_remap(in.x, inLow.x, inHigh.x, outLow.x, outHigh.x, doClamp), + mx_remap(in.y, inLow.y, inHigh.y, outLow.y, outHigh.y, doClamp)); +} + +vector2 mx_remap(vector2 in, float inLow, float inHigh, float outLow, float outHigh, int doClamp) +{ + return vector2(mx_remap(in.x, inLow, inHigh, outLow, outHigh, doClamp), + mx_remap(in.y, inLow, inHigh, outLow, outHigh, doClamp)); +} + +vector4 mx_remap(vector4 in, vector4 inLow, vector4 inHigh, vector4 outLow, vector4 outHigh, int doClamp) +{ + return vector4(mx_remap(in.x, inLow.x, inHigh.x, outLow.x, outHigh.x, doClamp), + mx_remap(in.y, inLow.y, inHigh.y, outLow.y, outHigh.y, doClamp), + mx_remap(in.z, inLow.z, inHigh.z, outLow.z, outHigh.z, doClamp), + mx_remap(in.w, inLow.w, inHigh.w, outLow.w, outHigh.w, doClamp)); +} + +vector4 mx_remap(vector4 in, float inLow, float inHigh, float outLow, float outHigh, int doClamp) +{ + return vector4(mx_remap(in.x, inLow, inHigh, outLow, outHigh, doClamp), + mx_remap(in.y, inLow, inHigh, outLow, outHigh, doClamp), + mx_remap(in.z, inLow, inHigh, outLow, outHigh, doClamp), + mx_remap(in.w, inLow, inHigh, outLow, outHigh, doClamp)); +} + + +float mx_contrast(float in, float amount, float pivot) +{ + float out = in - pivot; + out *= amount; + out += pivot; + return out; +} + +color mx_contrast(color in, color amount, color pivot) +{ + color out = in - pivot; + out *= amount; + out += pivot; + return out; +} + +color mx_contrast(color in, float amount, float pivot) +{ + color out = in - pivot; + out *= amount; + out += pivot; + return out; +} + +color4 mx_contrast(color4 c, color4 amount, color4 pivot) +{ + return color4(mx_contrast(c.rgb, amount.rgb, pivot.rgb), + mx_contrast(c.a, amount.a, pivot.a)); +} + +color4 mx_contrast(color4 c, float amount, float pivot) +{ + return mx_contrast(c, color4(color(amount), amount), color4(color(pivot), pivot)); +} + +vector2 mx_contrast(vector2 in, vector2 amount, vector2 pivot) +{ + return vector2 (mx_contrast(in.x, amount.x, pivot.x), + mx_contrast(in.y, amount.y, pivot.y)); +} + +vector2 mx_contrast(vector2 in, float amount, float pivot) +{ + return mx_contrast(in, vector2(amount, amount), vector2(pivot, pivot)); +} + +vector4 mx_contrast(vector4 in, vector4 amount, vector4 pivot) +{ + return vector4(mx_contrast(in.x, amount.x, pivot.x), + mx_contrast(in.y, amount.y, pivot.y), + mx_contrast(in.z, amount.z, pivot.z), + mx_contrast(in.w, amount.w, pivot.w)); +} + +vector4 mx_contrast(vector4 in, float amount, float pivot) +{ + return vector4(mx_contrast(in.x, amount, pivot), + mx_contrast(in.y, amount, pivot), + mx_contrast(in.z, amount, pivot), + mx_contrast(in.w, amount, pivot)); +} + + +vector2 mx_noise(string noisetype, float x, float y) +{ + color cnoise = (color) noise(noisetype, x, y); + return vector2 (cnoise[0], cnoise[1]); +} + +color4 mx_noise(string noisetype, float x, float y) +{ + color cnoise = (color) noise(noisetype, x, y); + float fnoise = (float) noise(noisetype, x + 19, y + 73); + return color4 (cnoise, fnoise); +} + +vector4 mx_noise(string noisetype, float x, float y) +{ + color cnoise = (color) noise(noisetype, x, y); + float fnoise = (float) noise(noisetype, x + 19, y + 73); + return vector4 (cnoise[0], cnoise[1], cnoise[2], fnoise); +} + +vector2 mx_noise(string noisetype, point position) +{ + color cnoise = (color) noise(noisetype, position); + return vector2 (cnoise[0], cnoise[1]); +} + +color4 mx_noise(string noisetype, point position) +{ + color cnoise = (color) noise(noisetype, position); + float fnoise = (float) noise(noisetype, position+vector(19,73,29)); + return color4 (cnoise, fnoise); +} + +vector4 mx_noise(string noisetype, point position) +{ + color cnoise = (color) noise(noisetype, position); + float fnoise = (float) noise(noisetype, position+vector(19,73,29)); + return vector4 (cnoise[0], cnoise[1], cnoise[2], fnoise); +} + + +float mx_fbm(point position, int octaves, float lacunarity, float diminish, string noisetype) +{ + float out = 0; + float amp = 1.0; + point p = position; + + for (int i = 0; i < octaves; i += 1) { + out += amp * noise(noisetype, p); + amp *= diminish; + p *= lacunarity; + } + return out; +} + +color mx_fbm(point position, int octaves, float lacunarity, float diminish, string noisetype) +{ + color out = 0; + float amp = 1.0; + point p = position; + + for (int i = 0; i < octaves; i += 1) { + out += amp * (color)noise(noisetype, p); + amp *= diminish; + p *= lacunarity; + } + return out; +} + +vector2 mx_fbm(point position, int octaves, float lacunarity, float diminish, string noisetype) +{ + return vector2((float) mx_fbm(position, octaves, lacunarity, diminish, noisetype), + (float) mx_fbm(position+point(19, 193, 17), octaves, lacunarity, diminish, noisetype)); +} + +color4 mx_fbm(point position, int octaves, float lacunarity, float diminish, string noisetype) +{ + color c = (color) mx_fbm(position, octaves, lacunarity, diminish, noisetype); + float f = (float) mx_fbm(position+point(19, 193, 17), octaves, lacunarity, diminish, noisetype); + return color4 (c, f); +} + +vector4 mx_fbm(point position, int octaves, float lacunarity, float diminish, string noisetype) +{ + color c = (color) mx_fbm(position, octaves, lacunarity, diminish, noisetype); + float f = (float) mx_fbm(position+point(19, 193, 17), octaves, lacunarity, diminish, noisetype); + return vector4 (c[0], c[1], c[2], f); +} + + +void mx_split_float(output float x, output int ix) +{ + ix = int(floor(x)); + x -= ix; +} + +float mx_worley_distance(vector2 p, int x, int y, int X, int Y, float jitter, int metric) +{ + vector o = cellnoise(x+X, y+Y); + o = (o - .5)*jitter + .5; + float cposx = x + o[0]; + float cposy = y + o[1]; + float diffx = cposx - p.x; + float diffy = cposy - p.y; + + if (metric == 2) + return abs(diffx) + abs(diffy); // Manhattan distance + if (metric == 3) + return max(abs(diffx), abs(diffy)); // Chebyshev distance + return diffx*diffx + diffy*diffy; // Euclidean or distance^2 +} + +float mx_worley_distance(vector p, int x, int y, int z, int X, int Y, int Z, float jitter, int metric) +{ + vector o = cellnoise(vector(x+X, y+Y, z+Z)); + o = (o - .5)*jitter + .5; + vector cpos = vector(x, y, z) + o; + vector diff = cpos - p; + + if (metric == 2) + return abs(diff[0]) + abs(diff[1]); // Manhattan distance + if (metric == 3) + return max(abs(diff[0]), abs(diff[1])); // Chebyshev distance + return dot(diff, diff); // Eucldean or distance^2 +} + +void mx_sort_distance(float dist, output vector2 result) +{ + if (dist < result.x) + { + result.y = result.x; + result.x = dist; + } + else if (dist < result.y) + { + result.y = dist; + } +} + +void mx_sort_distance(float dist, output vector result) +{ + if (dist < result[0]) + { + result[2] = result[1]; + result[1] = result[0]; + result[0] = dist; + } + else if (dist < result[1]) + { + result[2] = result[1]; + result[1] = dist; + } + else if (dist < result[2]) + { + result[2] = dist; + } +} + +float mx_worley_noise_float(vector2 p, float jitter, int metric) +{ + int X, Y; + vector2 seed = p; + float result = 1e6; + + mx_split_float(seed.x, X); + mx_split_float(seed.y, Y); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + float d = mx_worley_distance(seed, x, y, X, Y, jitter, metric); + result = min(result, d); + } + } + if (metric == 0) + result = sqrt(result); + return result; +} + +vector2 mx_worley_noise_vector2(vector2 p, float jitter, int metric) +{ + int X, Y; + vector2 seed = p; + vector2 result = vector2(1e6, 1e6); + + mx_split_float(seed.x, X); + mx_split_float(seed.y, Y); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + float d = mx_worley_distance(seed, x, y, X, Y, jitter, metric); + mx_sort_distance(d, result); + } + } + if (metric == 0) + result = sqrt(result); + return result; +} + +vector mx_worley_noise_vector3(vector2 p, float jitter, int metric) +{ + int X, Y; + vector2 seed = p; + vector result = vector(1e6, 1e6, 1e6); + + mx_split_float(seed.x, X); + mx_split_float(seed.y, Y); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + float d = mx_worley_distance(seed, x, y, X, Y, jitter, metric); + mx_sort_distance(d, result); + } + } + if (metric == 0) + result = sqrt(result); + return result; +} + +float mx_worley_noise_float(vector p, float jitter, int metric) +{ + int X, Y, Z; + vector seed = p; + float result = 1e6; + + mx_split_float(seed[0], X); + mx_split_float(seed[1], Y); + mx_split_float(seed[2], Z); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + for (int z = -1; z <= 1; ++z) + { + float d = mx_worley_distance(seed, x, y, z, X, Y, Z, jitter, metric); + result = min(result, d); + } + } + } + if (metric == 0) + result = sqrt(result); + return result; +} + +vector2 mx_worley_noise_vector2(vector p, float jitter, int metric) +{ + int X, Y, Z; + vector seed = p; + vector2 result = vector2(1e6, 1e6); + + mx_split_float(seed[0], X); + mx_split_float(seed[1], Y); + mx_split_float(seed[2], Z); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + for (int z = -1; z <= 1; ++z) + { + float d = mx_worley_distance(seed, x, y, z, X, Y, Z, jitter, metric); + mx_sort_distance(d, result); + } + } + } + if (metric == 0) + result = sqrt(result); + return result; +} + +vector mx_worley_noise_vector3(vector p, float jitter, int metric) +{ + int X, Y, Z; + vector result = 1e6; + vector seed = p; + + mx_split_float(seed[0], X); + mx_split_float(seed[1], Y); + mx_split_float(seed[2], Z); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + for (int z = -1; z <= 1; ++z) + { + float d = mx_worley_distance(seed, x, y, z, X, Y, Z, jitter, metric); + mx_sort_distance(d, result); + } + } + } + if (metric == 0) + result = sqrt(result); + return result; +} +// Open Shading Language : Copyright (c) 2009-2017 Sony Pictures Imageworks Inc., et al. +// https://github.com/imageworks/OpenShadingLanguage/blob/master/LICENSE +// +// MaterialX specification (c) 2017 Lucasfilm Ltd. +// http://www.materialx.org/ + +#pragma once +#define MATRIX33_H + + +struct matrix33 +{ + matrix m; +}; + +int isValidAs33(matrix m44) +{ + return m44[0][3] == 0 && + m44[1][3] == 0 && + m44[2][3] == 0 && + m44[3][0] == 0 && + m44[3][1] == 0 && + m44[3][2] == 0 && + m44[3][3] == 1; +} + +matrix matrix33To44 (matrix33 m33) +{ + return m33.m; +} + +// Convert an arbitrary m44 to m33 by removing the translation +//QUESTION: should we check if it's valid to represent the 4x4 as a 3x3? +matrix33 matrix44To33 (matrix m44) +{ + matrix33 m33; + m33.m = m44; + m33.m[0][3] = 0; + m33.m[1][3] = 0; + m33.m[2][3] = 0; + m33.m[3][0] = 0; + m33.m[3][1] = 0; + m33.m[3][2] = 0; + m33.m[3][3] = 1; + + return m33; +} + +matrix33 __operator__neg__(matrix33 a) +{ + matrix33 m33; + m33.m = -a.m; + return m33; +} + + +matrix33 __operator__mul__(int a, matrix33 b) +{ + matrix33 m33; + m33.m = a * b.m; + return m33; +} + +matrix33 __operator__mul__(float a, matrix33 b) +{ + matrix33 m33; + m33.m = a * b.m; + return m33; +} + +matrix33 __operator__mul__(matrix33 a, int b) +{ + matrix33 m33; + m33.m = a.m * b; + return m33; +} + +matrix33 __operator__mul__(matrix33 a, float b) +{ + matrix33 m33; + m33.m = a.m * b; + return m33; +} + +matrix33 __operator__mul__(matrix33 a, matrix33 b) +{ + matrix33 m33; + m33.m = a.m * b.m; + return m33; +} + +matrix33 __operator__div__(int a, matrix33 b) +{ + matrix33 m33; + m33.m = a / b.m; + return m33; +} + +matrix33 __operator__div__(float a, matrix33 b) +{ + matrix33 m33; + m33.m = a / b.m; + return m33; +} + +matrix33 __operator__div__(matrix33 a, int b) +{ + matrix33 m33; + m33.m = a.m / b; + return m33; +} + +matrix33 __operator__div__(matrix33 a, float b) +{ + matrix33 m33; + m33.m = a.m / b; + return m33; +} + +matrix33 __operator__div__(matrix33 a, matrix33 b) +{ + matrix33 m33; + m33.m = a.m / b.m; + return m33; +} + +int __operator__eq__(matrix33 a, matrix33 b) +{ + return a.m == b.m; +} + +int __operator__ne__(matrix33 a, matrix33 b) +{ + return a.m != b.m; +} + +float determinant (matrix33 a) +{ + return determinant(a.m); +} + +matrix33 transpose(matrix33 a) +{ + matrix33 m33; + m33.m = transpose(a.m); + return m33; +} + +point transform(matrix33 a, point b) +{ + return transform(a.m, b); +} + +vector transform(matrix33 a, vector b) +{ + return transform(a.m, b); +} + +normal transform(matrix33 a, normal b) +{ + return transform(a.m, b); +} + + + +// Open Shading Language : Copyright (c) 2009-2017 Sony Pictures Imageworks Inc., et al. +// https://github.com/imageworks/OpenShadingLanguage/blob/master/LICENSE + +#pragma once +#define COLOR4_H + + +// color4 is a color + alpha +struct color4 +{ + color rgb; + float a; +}; + + + +// +// For color4, define math operators to match color +// + +color4 __operator__neg__(color4 a) +{ + return color4(-a.rgb, -a.a); +} + +color4 __operator__add__(color4 a, color4 b) +{ + return color4(a.rgb + b.rgb, a.a + b.a); +} + +color4 __operator__add__(color4 a, int b) +{ + return a + color4(color(b), b); +} + +color4 __operator__add__(color4 a, float b) +{ + return a + color4(color(b), b); +} + +color4 __operator__add__(int a, color4 b) +{ + return color4(color(a), a) + b; +} + +color4 __operator__add__(float a, color4 b) +{ + return color4(color(a), a) + b; +} + +color4 __operator__sub__(color4 a, color4 b) +{ + return color4(a.rgb - b.rgb, a.a - b.a); +} + +color4 __operator__sub__(color4 a, int b) +{ + return a - color4(color(b), b); +} + +color4 __operator__sub__(color4 a, float b) +{ + return a - color4(color(b), b); +} + +color4 __operator__sub__(int a, color4 b) +{ + return color4(color(a), a) - b; +} + +color4 __operator__sub__(float a, color4 b) +{ + return color4(color(a), a) - b; +} + +color4 __operator__mul__(color4 a, color4 b) +{ + return color4(a.rgb * b.rgb, a.a * b.a); +} + +color4 __operator__mul__(color4 a, int b) +{ + return a * color4(color(b), b); +} + +color4 __operator__mul__(color4 a, float b) +{ + return a * color4(color(b), b); +} + +color4 __operator__mul__(int a, color4 b) +{ + return color4(color(a), a) * b; +} + +color4 __operator__mul__(float a, color4 b) +{ + return color4(color(a), a) * b; +} + +color4 __operator__div__(color4 a, color4 b) +{ + return color4(a.rgb / b.rgb, a.a / b.a); +} + +color4 __operator__div__(color4 a, int b) +{ + float b_inv = 1.0/b; + return a * color4(color(b_inv), b_inv); +} + +color4 __operator__div__(color4 a, float b) +{ + float b_inv = 1.0/b; + return a * color4(color(b_inv), b_inv); +} + +color4 __operator_div__(int a, color4 b) +{ + return color4(color(a), a) / b; +} + +color4 __operator__div__(float a, color4 b) +{ + return color4(color(a), a) / b; +} + +int __operator__eq__(color4 a, color4 b) +{ + return (a.rgb == b.rgb) && (a.a == b.a); +} + +int __operator__ne__(color4 a, color4 b) +{ + return (a.rgb != b.rgb) || (a.a != b.a); +} + + + +// +// For color4, define most of the stdosl functions to match color +// + +color4 abs(color4 a) +{ + return color4(abs(a.rgb), abs(a.a)); +} + +color4 ceil(color4 a) +{ + return color4(ceil(a.rgb), ceil(a.a)); +} + +color4 round(color4 a) +{ + return color4(round(a.rgb), round(a.a)); +} + +color4 floor(color4 a) +{ + return color4(floor(a.rgb), floor(a.a)); +} + +color4 sqrt(color4 a) +{ + return color4(sqrt(a.rgb), sqrt(a.a)); +} + +color4 exp(color4 a) +{ + return color4(exp(a.rgb), exp(a.a)); +} + +color4 log(color4 a) +{ + return color4(log(a.rgb), log(a.a)); +} + +color4 log2(color4 a) +{ + return color4(log2(a.rgb), log2(a.a)); +} + +color4 mix(color4 a, color4 b, float x ) +{ + return color4(mix(a.rgb, b.rgb, x), + mix(a.a, b.a, x)); +} + +color4 mix(color4 a, color4 b, color4 x ) +{ + return color4(mix(a.rgb, b.rgb, x.rgb), + mix(a.a, b.a, x.a)); +} + +float dot(color4 a, color b) +{ + return dot(a.rgb, b); +} + +color4 smoothstep(color4 edge0, color4 edge1, color4 c) +{ + return color4(smoothstep(edge0.rgb, edge1.rgb, c.rgb), + smoothstep(edge0.a, edge1.a, c.a)); +} + +color4 smoothstep(float edge0, float edge1, color4 c) +{ + return smoothstep(color4(color(edge0), edge0), color4(color(edge1), edge1), c); +} + +color4 clamp(color4 c, color4 minval, color4 maxval) +{ + return color4(clamp(c.rgb, minval.rgb, maxval.rgb), + clamp(c.a, minval.a, maxval.a)); +} + +color4 clamp(color4 c, float minval, float maxval) +{ + return clamp(c, color4(color(minval), minval), color4(color(maxval), maxval)); +} + +color4 max(color4 a, color4 b) +{ + return color4(max(a.rgb, b.rgb), + max(a.a, b.a)); +} + +color4 max(color4 a, float b) +{ + return color4(max(a.rgb, b), + max(a.a, b)); +} + +color4 min(color4 a, color4 b) +{ + return color4(min(a.rgb, b.rgb), + min(a.a, b.a)); +} + +color4 min(color4 a, float b) +{ + return color4(min(a.rgb, b), + min(a.a, b)); +} + +color4 mod(color4 a, color4 b) +{ + return color4(mod(a.rgb, b.rgb), + mod(a.a, b.a)); +} + +color4 mod(color4 a, int b) +{ + return mod(a, color4(color(b), b)); +} + +color4 mod(color4 a, float b) +{ + return mod(a, color4(color(b), b)); +} + +color4 fmod(color4 a, color4 b) +{ + return color4(fmod(a.rgb, b.rgb), + fmod(a.a, b.a)); +} + +color4 fmod(color4 a, int b) +{ + return fmod(a, color4(color(b), b)); +} + +color4 fmod(color4 a, float b) +{ + return fmod(a, color4(color(b), b)); +} + +color4 pow(color4 base, color4 power) +{ + return color4(pow(base.rgb, power.rgb), + pow(base.a, power.a)); +} + +color4 pow(color4 base, float power) +{ + return color4(pow(base.rgb, power), + pow(base.a, power)); +} + +color4 sign(color4 a) +{ + return color4(sign(a.rgb), + sign(a.a)); +} + +color4 sin(color4 a) +{ + return color4(sin(a.rgb), + sin(a.a)); +} + +color4 cos(color4 a) +{ + return color4(cos(a.rgb), + cos(a.a)); +} + +color4 tan(color4 a) +{ + return color4(tan(a.rgb), + tan(a.a)); +} + +color4 asin(color4 a) +{ + return color4(asin(a.rgb), + asin(a.a)); +} + +color4 acos(color4 a) +{ + return color4(acos(a.rgb), + acos(a.a)); +} + +color4 atan2(color4 a, float f) +{ + return color4(atan2(a.rgb, f), + atan2(a.a, f)); +} + +color4 atan2(color4 a, color4 b) +{ + return color4(atan2(a.rgb, b.rgb), + atan2(a.a, b.a)); +} + + +color4 transformc (string fromspace, string tospace, color4 C) +{ + return color4 (transformc (fromspace, tospace, C.rgb), C.a); +} +vector2 mx_transform_uv(vector2 texcoord) +{ + return vector2(texcoord.x, 1.0 - texcoord.y); +} +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} +// Restrict to 7x7 kernel size for performance reasons +#define MX_MAX_SAMPLE_COUNT 49 +// Size of all weights for all levels (including level 1) +#define MX_WEIGHT_ARRAY_SIZE 84 + +// +// Function to compute the sample size relative to a texture coordinate +// +vector2 mx_compute_sample_size_uv(vector2 uv, float filterSize, float filterOffset) +{ + vector derivUVx = Dx(vector(uv.x, uv.y, 0.0)) * 0.5; + vector derivUVy = Dy(vector(uv.x, uv.y, 0.0)) * 0.5; + float derivX = abs(derivUVx[0]) + abs(derivUVy[0]); + float derivY = abs(derivUVx[1]) + abs(derivUVy[1]); + float sampleSizeU = filterSize * derivX + filterOffset; + if (sampleSizeU < 1.0E-05) + sampleSizeU = 1.0E-05; + float sampleSizeV = filterSize * derivY + filterOffset; + if (sampleSizeV < 1.0E-05) + sampleSizeV = 1.0E-05; + return vector2(sampleSizeU, sampleSizeV); +} + +// Kernel weights for box filter +void mx_get_box_weights(output float W[MX_MAX_SAMPLE_COUNT], int filterSize) +{ + int sampleCount = filterSize*filterSize; + float value = 1.0 / float(sampleCount); + for (int i=0; i= 7) + { + W[0] = 0.000036; W[1] = 0.000363; W[2] = 0.001446; W[3] = 0.002291; W[4] = 0.001446; W[5] = 0.000363; W[6] = 0.000036; + W[7] = 0.000363; W[8] = 0.003676; W[9] = 0.014662; W[10] = 0.023226; W[11] = 0.014662; W[12] = 0.003676; W[13] = 0.000363; + W[14] = 0.001446; W[15] = 0.014662; W[16] = 0.058488; W[17] = 0.092651; W[18] = 0.058488; W[19] = 0.014662; W[20] = 0.001446; + W[21] = 0.002291; W[22] = 0.023226; W[23] = 0.092651; W[24] = 0.146768; W[25] = 0.092651; W[26] = 0.023226; W[27] = 0.002291; + W[28] = 0.001446; W[29] = 0.014662; W[30] = 0.058488; W[31] = 0.092651; W[32] = 0.058488; W[33] = 0.014662; W[34] = 0.001446; + W[35] = 0.000363; W[36] = 0.003676; W[37] = 0.014662; W[38] = 0.023226; W[39] = 0.014662; W[40] = 0.003676; W[41] = 0.000363; + W[42] = 0.000036; W[43] = 0.000363; W[44] = 0.001446; W[45] = 0.002291; W[46] = 0.001446; W[47] = 0.000363; W[48] = 0.000036; + } + else if (filterSize >= 5) + { + W[0] = 0.003765; W[1] = 0.015019; W[2] = 0.023792; W[3] = 0.015019; W[4] = 0.003765; + W[5] = 0.015019; W[6] = 0.059912; W[7] = 0.094907; W[8] = 0.059912; W[9] = 0.015019; + W[10] = 0.023792; W[11] = 0.094907; W[12] = 0.150342; W[13] = 0.094907; W[14] = 0.023792; + W[15] = 0.015019; W[16] = 0.059912; W[17] = 0.094907; W[18] = 0.059912; W[19] = 0.015019; + W[20] = 0.003765; W[21] = 0.015019; W[22] = 0.023792; W[23] = 0.015019; W[24] = 0.003765; + } + else if (filterSize >= 3) + { + W[0] = 0.0625; W[1] = 0.125; W[2] = 0.0625; + W[3] = 0.125; W[4] = 0.25; W[5] = 0.125; + W[6] = 0.0625; W[7] = 0.125; W[8] = 0.0625; + } + else + { + W[0] = 1.0; + } +} + +// +// Apply filter for float samples S, using weights W. +// sampleCount should be a square of a odd number in the range { 1, 3, 5, 7 } +// +float mx_convolution_float(float S[MX_MAX_SAMPLE_COUNT], float W[MX_WEIGHT_ARRAY_SIZE], int offset, int sampleCount) +{ + float result = 0.0; + for (int i = 0; i < sampleCount; i++) + { + result += S[i]*W[i+offset]; + } + return result; +} + +// +// Apply filter for vector2 samples S, using weights W. +// sampleCount should be a square of a odd number in the range { 1, 3, 5, 7 } +// +vector2 mx_convolution_vector2(vector2 S[MX_MAX_SAMPLE_COUNT], float W[MX_WEIGHT_ARRAY_SIZE], int offset, int sampleCount) +{ + vector2 result = vector2(0.0, 0.0); + for (int i=0; i + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/JsMaterialXGenShader.js b/JsMaterialXGenShader.js new file mode 100644 index 0000000000..241efacaa8 --- /dev/null +++ b/JsMaterialXGenShader.js @@ -0,0 +1,21 @@ + +var MaterialX = (function() { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; + return ( +function(MaterialX) { + MaterialX = MaterialX || {}; + +var Module=typeof MaterialX!=="undefined"?MaterialX:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});if(!Module.expectedDataFileDownloads){Module.expectedDataFileDownloads=0}Module.expectedDataFileDownloads++;(function(){var loadPackage=function(metadata){var PACKAGE_PATH;if(typeof window==="object"){PACKAGE_PATH=window["encodeURIComponent"](window.location.pathname.toString().substring(0,window.location.pathname.toString().lastIndexOf("/"))+"/")}else if(typeof location!=="undefined"){PACKAGE_PATH=encodeURIComponent(location.pathname.toString().substring(0,location.pathname.toString().lastIndexOf("/"))+"/")}else{throw"using preloaded data can only be done on a web page or in a web worker"}var PACKAGE_NAME="../../bin/JsMaterialXGenShader.data";var REMOTE_PACKAGE_BASE="JsMaterialXGenShader.data";if(typeof Module["locateFilePackage"]==="function"&&!Module["locateFile"]){Module["locateFile"]=Module["locateFilePackage"];err("warning: you defined Module.locateFilePackage, that has been renamed to Module.locateFile (using your locateFilePackage for now)")}var REMOTE_PACKAGE_NAME=Module["locateFile"]?Module["locateFile"](REMOTE_PACKAGE_BASE,""):REMOTE_PACKAGE_BASE;var REMOTE_PACKAGE_SIZE=metadata["remote_package_size"];var PACKAGE_UUID=metadata["package_uuid"];function fetchRemotePackage(packageName,packageSize,callback,errback){var xhr=new XMLHttpRequest;xhr.open("GET",packageName,true);xhr.responseType="arraybuffer";xhr.onprogress=function(event){var url=packageName;var size=packageSize;if(event.total)size=event.total;if(event.loaded){if(!xhr.addedTotal){xhr.addedTotal=true;if(!Module.dataFileDownloads)Module.dataFileDownloads={};Module.dataFileDownloads[url]={loaded:event.loaded,total:size}}else{Module.dataFileDownloads[url].loaded=event.loaded}var total=0;var loaded=0;var num=0;for(var download in Module.dataFileDownloads){var data=Module.dataFileDownloads[download];total+=data.total;loaded+=data.loaded;num++}total=Math.ceil(total*Module.expectedDataFileDownloads/num);if(Module["setStatus"])Module["setStatus"]("Downloading data... ("+loaded+"/"+total+")")}else if(!Module.dataFileDownloads){if(Module["setStatus"])Module["setStatus"]("Downloading data...")}};xhr.onerror=function(event){throw new Error("NetworkError for: "+packageName)};xhr.onload=function(event){if(xhr.status==200||xhr.status==304||xhr.status==206||xhr.status==0&&xhr.response){var packageData=xhr.response;callback(packageData)}else{throw new Error(xhr.statusText+" : "+xhr.responseURL)}};xhr.send(null)}function handleError(error){console.error("package error:",error)}var fetchedCallback=null;var fetched=Module["getPreloadedPackage"]?Module["getPreloadedPackage"](REMOTE_PACKAGE_NAME,REMOTE_PACKAGE_SIZE):null;if(!fetched)fetchRemotePackage(REMOTE_PACKAGE_NAME,REMOTE_PACKAGE_SIZE,function(data){if(fetchedCallback){fetchedCallback(data);fetchedCallback=null}else{fetched=data}},handleError);function runWithFS(){function assert(check,msg){if(!check)throw msg+(new Error).stack}Module["FS_createPath"]("/","libraries",true,true);Module["FS_createPath"]("/libraries","lights",true,true);Module["FS_createPath"]("/libraries/lights","genmsl",true,true);Module["FS_createPath"]("/libraries/lights","genglsl",true,true);Module["FS_createPath"]("/libraries","targets",true,true);Module["FS_createPath"]("/libraries","pbrlib",true,true);Module["FS_createPath"]("/libraries/pbrlib","genmsl",true,true);Module["FS_createPath"]("/libraries/pbrlib","genmdl",true,true);Module["FS_createPath"]("/libraries/pbrlib","genglsl",true,true);Module["FS_createPath"]("/libraries/pbrlib/genglsl","lib",true,true);Module["FS_createPath"]("/libraries/pbrlib","genosl",true,true);Module["FS_createPath"]("/libraries/pbrlib/genosl","legacy",true,true);Module["FS_createPath"]("/libraries/pbrlib/genosl","lib",true,true);Module["FS_createPath"]("/libraries","cmlib",true,true);Module["FS_createPath"]("/libraries","nprlib",true,true);Module["FS_createPath"]("/libraries/nprlib","genmsl",true,true);Module["FS_createPath"]("/libraries/nprlib","genmdl",true,true);Module["FS_createPath"]("/libraries/nprlib","genglsl",true,true);Module["FS_createPath"]("/libraries/nprlib","genosl",true,true);Module["FS_createPath"]("/libraries","stdlib",true,true);Module["FS_createPath"]("/libraries/stdlib","genmsl",true,true);Module["FS_createPath"]("/libraries/stdlib/genmsl","lib",true,true);Module["FS_createPath"]("/libraries/stdlib","genmdl",true,true);Module["FS_createPath"]("/libraries/stdlib","genglsl",true,true);Module["FS_createPath"]("/libraries/stdlib/genglsl","lib",true,true);Module["FS_createPath"]("/libraries/stdlib","genosl",true,true);Module["FS_createPath"]("/libraries/stdlib/genosl","include",true,true);Module["FS_createPath"]("/libraries/stdlib/genosl","lib",true,true);Module["FS_createPath"]("/libraries","bxdf",true,true);Module["FS_createPath"]("/libraries/bxdf","lama",true,true);Module["FS_createPath"]("/libraries/bxdf","translation",true,true);function DataRequest(start,end,audio){this.start=start;this.end=end;this.audio=audio}DataRequest.prototype={requests:{},open:function(mode,name){this.name=name;this.requests[name]=this;Module["addRunDependency"]("fp "+this.name)},send:function(){},onload:function(){var byteArray=this.byteArray.subarray(this.start,this.end);this.finish(byteArray)},finish:function(byteArray){var that=this;Module["FS_createDataFile"](this.name,null,byteArray,true,true,true);Module["removeRunDependency"]("fp "+that.name);this.requests[this.name]=null}};var files=metadata["files"];for(var i=0;i1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!=="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var STACK_ALIGN=16;function alignMemory(size,factor){if(!factor)factor=STACK_ALIGN;return Math.ceil(size/factor)*factor}var tempRet0=0;var setTempRet0=function(value){tempRet0=value};var getTempRet0=function(){return tempRet0};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!=="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}var UTF8Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}var UTF16Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf-16le"):undefined;function UTF16ToString(ptr,maxBytesToRead){var endPtr=ptr;var idx=endPtr>>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder){return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr))}else{var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str}}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i=55296&&codeUnit<=57343)++i;len+=4}return len}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.init.initialized)FS.init();TTY.init();callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}function isFileURI(filename){return filename.startsWith("file://")}var wasmBinaryFile="JsMaterialXGenShader.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["Va"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["Ya"];addOnInit(Module["asm"]["Wa"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){var result=WebAssembly.instantiate(binary,info);return result}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiationResult,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiationResult)})})}else{return instantiateArrayBuffer(receiveInstantiationResult)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}var tempDouble;var tempI64;var ASM_CONSTS={210012:function(){Module["TreeIterator"]["prototype"][Symbol.iterator]=function(){return this}},210096:function(){Module["GraphIterator"]["prototype"][Symbol.iterator]=function(){return this}},210181:function(){Module["InheritanceIterator"]["prototype"][Symbol.iterator]=function(){return this}}};function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){wasmTable.get(func)()}else{wasmTable.get(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}function ___assert_fail(condition,filename,line,func){abort("Assertion failed: "+UTF8ToString(condition)+", at: "+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"])}var ExceptionInfoAttrs={DESTRUCTOR_OFFSET:0,REFCOUNT_OFFSET:4,TYPE_OFFSET:8,CAUGHT_OFFSET:12,RETHROWN_OFFSET:13,SIZE:16};function ___cxa_allocate_exception(size){return _malloc(size+ExceptionInfoAttrs.SIZE)+ExceptionInfoAttrs.SIZE}function ExceptionInfo(excPtr){this.excPtr=excPtr;this.ptr=excPtr-ExceptionInfoAttrs.SIZE;this.set_type=function(type){HEAP32[this.ptr+ExceptionInfoAttrs.TYPE_OFFSET>>2]=type};this.get_type=function(){return HEAP32[this.ptr+ExceptionInfoAttrs.TYPE_OFFSET>>2]};this.set_destructor=function(destructor){HEAP32[this.ptr+ExceptionInfoAttrs.DESTRUCTOR_OFFSET>>2]=destructor};this.get_destructor=function(){return HEAP32[this.ptr+ExceptionInfoAttrs.DESTRUCTOR_OFFSET>>2]};this.set_refcount=function(refcount){HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=refcount};this.set_caught=function(caught){caught=caught?1:0;HEAP8[this.ptr+ExceptionInfoAttrs.CAUGHT_OFFSET>>0]=caught};this.get_caught=function(){return HEAP8[this.ptr+ExceptionInfoAttrs.CAUGHT_OFFSET>>0]!=0};this.set_rethrown=function(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+ExceptionInfoAttrs.RETHROWN_OFFSET>>0]=rethrown};this.get_rethrown=function(){return HEAP8[this.ptr+ExceptionInfoAttrs.RETHROWN_OFFSET>>0]!=0};this.init=function(type,destructor){this.set_type(type);this.set_destructor(destructor);this.set_refcount(0);this.set_caught(false);this.set_rethrown(false)};this.add_ref=function(){var value=HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2];HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=value+1};this.release_ref=function(){var prev=HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2];HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=prev-1;return prev===1}}function CatchInfo(ptr){this.free=function(){_free(this.ptr);this.ptr=0};this.set_base_ptr=function(basePtr){HEAP32[this.ptr>>2]=basePtr};this.get_base_ptr=function(){return HEAP32[this.ptr>>2]};this.set_adjusted_ptr=function(adjustedPtr){var ptrSize=4;HEAP32[this.ptr+ptrSize>>2]=adjustedPtr};this.get_adjusted_ptr=function(){var ptrSize=4;return HEAP32[this.ptr+ptrSize>>2]};this.get_exception_ptr=function(){var isPointer=___cxa_is_pointer_type(this.get_exception_info().get_type());if(isPointer){return HEAP32[this.get_base_ptr()>>2]}var adjusted=this.get_adjusted_ptr();if(adjusted!==0)return adjusted;return this.get_base_ptr()};this.get_exception_info=function(){return new ExceptionInfo(this.get_base_ptr())};if(ptr===undefined){this.ptr=_malloc(8);this.set_adjusted_ptr(0)}else{this.ptr=ptr}}var exceptionCaught=[];function exception_addRef(info){info.add_ref()}var uncaughtExceptionCount=0;function ___cxa_begin_catch(ptr){var catchInfo=new CatchInfo(ptr);var info=catchInfo.get_exception_info();if(!info.get_caught()){info.set_caught(true);uncaughtExceptionCount--}info.set_rethrown(false);exceptionCaught.push(catchInfo);exception_addRef(info);return catchInfo.get_exception_ptr()}var exceptionLast=0;function ___cxa_free_exception(ptr){return _free(new ExceptionInfo(ptr).ptr)}function exception_decRef(info){if(info.release_ref()&&!info.get_rethrown()){var destructor=info.get_destructor();if(destructor){wasmTable.get(destructor)(info.excPtr)}___cxa_free_exception(info.excPtr)}}function ___cxa_end_catch(){_setThrew(0);var catchInfo=exceptionCaught.pop();exception_decRef(catchInfo.get_exception_info());catchInfo.free();exceptionLast=0}function ___resumeException(catchInfoPtr){var catchInfo=new CatchInfo(catchInfoPtr);var ptr=catchInfo.get_base_ptr();if(!exceptionLast){exceptionLast=ptr}catchInfo.free();throw ptr}function ___cxa_find_matching_catch_2(){var thrown=exceptionLast;if(!thrown){setTempRet0(0);return 0|0}var info=new ExceptionInfo(thrown);var thrownType=info.get_type();var catchInfo=new CatchInfo;catchInfo.set_base_ptr(thrown);if(!thrownType){setTempRet0(0);return catchInfo.ptr|0}var typeArray=Array.prototype.slice.call(arguments);var stackTop=stackSave();var exceptionThrowBuf=stackAlloc(4);HEAP32[exceptionThrowBuf>>2]=thrown;for(var i=0;i>2];if(thrown!==adjusted){catchInfo.set_adjusted_ptr(adjusted)}setTempRet0(caughtType);return catchInfo.ptr|0}}stackRestore(stackTop);setTempRet0(thrownType);return catchInfo.ptr|0}function ___cxa_find_matching_catch_3(){var thrown=exceptionLast;if(!thrown){setTempRet0(0);return 0|0}var info=new ExceptionInfo(thrown);var thrownType=info.get_type();var catchInfo=new CatchInfo;catchInfo.set_base_ptr(thrown);if(!thrownType){setTempRet0(0);return catchInfo.ptr|0}var typeArray=Array.prototype.slice.call(arguments);var stackTop=stackSave();var exceptionThrowBuf=stackAlloc(4);HEAP32[exceptionThrowBuf>>2]=thrown;for(var i=0;i>2];if(thrown!==adjusted){catchInfo.set_adjusted_ptr(adjusted)}setTempRet0(caughtType);return catchInfo.ptr|0}}stackRestore(stackTop);setTempRet0(thrownType);return catchInfo.ptr|0}function ___cxa_find_matching_catch_4(){var thrown=exceptionLast;if(!thrown){setTempRet0(0);return 0|0}var info=new ExceptionInfo(thrown);var thrownType=info.get_type();var catchInfo=new CatchInfo;catchInfo.set_base_ptr(thrown);if(!thrownType){setTempRet0(0);return catchInfo.ptr|0}var typeArray=Array.prototype.slice.call(arguments);var stackTop=stackSave();var exceptionThrowBuf=stackAlloc(4);HEAP32[exceptionThrowBuf>>2]=thrown;for(var i=0;i>2];if(thrown!==adjusted){catchInfo.set_adjusted_ptr(adjusted)}setTempRet0(caughtType);return catchInfo.ptr|0}}stackRestore(stackTop);setTempRet0(thrownType);return catchInfo.ptr|0}function ___cxa_rethrow(){var catchInfo=exceptionCaught.pop();if(!catchInfo){abort("no exception to throw")}var info=catchInfo.get_exception_info();var ptr=catchInfo.get_base_ptr();if(!info.get_rethrown()){exceptionCaught.push(catchInfo);info.set_rethrown(true);info.set_caught(false);uncaughtExceptionCount++}else{catchInfo.free()}exceptionLast=ptr;throw ptr}function ___cxa_throw(ptr,type,destructor){var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw ptr}function ___cxa_uncaught_exceptions(){return uncaughtExceptionCount}function setErrNo(value){HEAP32[___errno_location()>>2]=value;return value}var PATH={splitPath:function(filename){var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:function(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:function(path){var isAbsolute=path.charAt(0)==="/",trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:function(path){var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:function(path){if(path==="/")return"/";path=PATH.normalize(path);path=path.replace(/\/$/,"");var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},extname:function(path){return PATH.splitPath(path)[3]},join:function(){var paths=Array.prototype.slice.call(arguments,0);return PATH.normalize(paths.join("/"))},join2:function(l,r){return PATH.normalize(l+"/"+r)}};function getRandomDevice(){if(typeof crypto==="object"&&typeof crypto["getRandomValues"]==="function"){var randomBuffer=new Uint8Array(1);return function(){crypto.getRandomValues(randomBuffer);return randomBuffer[0]}}else if(ENVIRONMENT_IS_NODE){try{var crypto_module=require("crypto");return function(){return crypto_module["randomBytes"](1)[0]}}catch(e){}}return function(){abort("randomDevice")}}var PATH_FS={resolve:function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:FS.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:function(from,to){from=PATH_FS.resolve(from).substr(1);to=PATH_FS.resolve(to).substr(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i0){result=buf.slice(0,bytesRead).toString("utf-8")}else{result=null}}else if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else if(typeof readline=="function"){result=readline();if(result!==null){result+="\n"}}if(!result){return null}tty.input=intArrayFromString(result,true)}return tty.input.shift()},put_char:function(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){out(UTF8ArrayToString(tty.output,0));tty.output=[]}}},default_tty1_ops:{put_char:function(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output,0));tty.output=[]}}}};function mmapAlloc(size){var alignedSize=alignMemory(size,65536);var ptr=_malloc(alignedSize);while(size=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage:function(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr:function(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.timestamp);attr.mtime=new Date(node.timestamp);attr.ctime=new Date(node.timestamp);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr:function(node,attr){if(attr.mode!==undefined){node.mode=attr.mode}if(attr.timestamp!==undefined){node.timestamp=attr.timestamp}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup:function(parent,name){throw FS.genericErrors[44]},mknod:function(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename:function(old_node,new_dir,new_name){if(FS.isDir(old_node.mode)){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}}delete old_node.parent.contents[old_node.name];old_node.parent.timestamp=Date.now();old_node.name=new_name;new_dir.contents[new_name]=old_node;new_dir.timestamp=old_node.parent.timestamp;old_node.parent=new_dir},unlink:function(parent,name){delete parent.contents[name];parent.timestamp=Date.now()},rmdir:function(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.timestamp=Date.now()},readdir:function(node){var entries=[".",".."];for(var key in node.contents){if(!node.contents.hasOwnProperty(key)){continue}entries.push(key)}return entries},symlink:function(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink:function(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read:function(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i0||position+length8){throw new FS.ErrnoError(32)}var parts=PATH.normalizeArray(path.split("/").filter(function(p){return!!p}),false);var current=FS.root;var current_path="/";for(var i=0;i40){throw new FS.ErrnoError(32)}}}}return{path:current_path,node:current}},getPath:function(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?mount+"/"+path:mount+path}path=path?node.name+"/"+path:node.name;node=node.parent}},hashName:function(parentid,name){var hash=0;for(var i=0;i>>0)%FS.nameTable.length},hashAddNode:function(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode:function(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode:function(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode,parent)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode:function(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode:function(node){FS.hashRemoveNode(node)},isRoot:function(node){return node===node.parent},isMountpoint:function(node){return!!node.mounted},isFile:function(mode){return(mode&61440)===32768},isDir:function(mode){return(mode&61440)===16384},isLink:function(mode){return(mode&61440)===40960},isChrdev:function(mode){return(mode&61440)===8192},isBlkdev:function(mode){return(mode&61440)===24576},isFIFO:function(mode){return(mode&61440)===4096},isSocket:function(mode){return(mode&49152)===49152},flagModes:{"r":0,"r+":2,"w":577,"w+":578,"a":1089,"a+":1090},modeStringToFlags:function(str){var flags=FS.flagModes[str];if(typeof flags==="undefined"){throw new Error("Unknown file open mode: "+str)}return flags},flagsToPermissionString:function(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions:function(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup:function(dir){var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate:function(dir,name){try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete:function(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen:function(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&512){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},MAX_OPEN_FDS:4096,nextfd:function(fd_start,fd_end){fd_start=fd_start||0;fd_end=fd_end||FS.MAX_OPEN_FDS;for(var fd=fd_start;fd<=fd_end;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStream:function(fd){return FS.streams[fd]},createStream:function(stream,fd_start,fd_end){if(!FS.FSStream){FS.FSStream=function(){};FS.FSStream.prototype={object:{get:function(){return this.node},set:function(val){this.node=val}},isRead:{get:function(){return(this.flags&2097155)!==1}},isWrite:{get:function(){return(this.flags&2097155)!==0}},isAppend:{get:function(){return this.flags&1024}}}}var newStream=new FS.FSStream;for(var p in stream){newStream[p]=stream[p]}stream=newStream;var fd=FS.nextfd(fd_start,fd_end);stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream:function(fd){FS.streams[fd]=null},chrdev_stream_ops:{open:function(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;if(stream.stream_ops.open){stream.stream_ops.open(stream)}},llseek:function(){throw new FS.ErrnoError(70)}},major:function(dev){return dev>>8},minor:function(dev){return dev&255},makedev:function(ma,mi){return ma<<8|mi},registerDevice:function(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:function(dev){return FS.devices[dev]},getMounts:function(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push.apply(check,m.mounts)}return mounts},syncfs:function(populate,callback){if(typeof populate==="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err("warning: "+FS.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work")}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}mounts.forEach(function(mount){if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},mount:function(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type:type,opts:opts,mountpoint:mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount:function(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);Object.keys(FS.nameTable).forEach(function(hash){var current=FS.nameTable[hash];while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}});node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup:function(parent,name){return parent.node_ops.lookup(parent,name)},mknod:function(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name||name==="."||name===".."){throw new FS.ErrnoError(28)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},create:function(path,mode){mode=mode!==undefined?mode:438;mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir:function(path,mode){mode=mode!==undefined?mode:511;mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree:function(path,mode){var dirs=path.split("/");var d="";for(var i=0;ithis.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]};LazyUint8Array.prototype.setDataGetter=function LazyUint8Array_setDataGetter(getter){this.getter=getter};LazyUint8Array.prototype.cacheLength=function LazyUint8Array_cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=function(from,to){if(from>to)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);if(typeof Uint8Array!="undefined")xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}else{return intArrayFromString(xhr.responseText||"",true)}};var lazyArray=this;lazyArray.setDataGetter(function(chunkNum){var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]==="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]==="undefined")throw new Error("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true};if(typeof XMLHttpRequest!=="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;Object.defineProperties(lazyArray,{length:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._length}},chunkSize:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}});var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url:url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};var keys=Object.keys(node.stream_ops);keys.forEach(function(key){var fn=node.stream_ops[key];stream_ops[key]=function forceLoadLazyFile(){FS.forceLoadFile(node);return fn.apply(null,arguments)}});stream_ops.read=function stream_ops_read(stream,buffer,offset,length,position){FS.forceLoadFile(node);var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i>2]=stat.dev;HEAP32[buf+4>>2]=0;HEAP32[buf+8>>2]=stat.ino;HEAP32[buf+12>>2]=stat.mode;HEAP32[buf+16>>2]=stat.nlink;HEAP32[buf+20>>2]=stat.uid;HEAP32[buf+24>>2]=stat.gid;HEAP32[buf+28>>2]=stat.rdev;HEAP32[buf+32>>2]=0;tempI64=[stat.size>>>0,(tempDouble=stat.size,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>2]=tempI64[0],HEAP32[buf+44>>2]=tempI64[1];HEAP32[buf+48>>2]=4096;HEAP32[buf+52>>2]=stat.blocks;HEAP32[buf+56>>2]=stat.atime.getTime()/1e3|0;HEAP32[buf+60>>2]=0;HEAP32[buf+64>>2]=stat.mtime.getTime()/1e3|0;HEAP32[buf+68>>2]=0;HEAP32[buf+72>>2]=stat.ctime.getTime()/1e3|0;HEAP32[buf+76>>2]=0;tempI64=[stat.ino>>>0,(tempDouble=stat.ino,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+80>>2]=tempI64[0],HEAP32[buf+84>>2]=tempI64[1];return 0},doMsync:function(addr,stream,len,flags,offset){var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},doMkdir:function(path,mode){path=PATH.normalize(path);if(path[path.length-1]==="/")path=path.substr(0,path.length-1);FS.mkdir(path,mode,0);return 0},doMknod:function(path,mode,dev){switch(mode&61440){case 32768:case 8192:case 24576:case 4096:case 49152:break;default:return-28}FS.mknod(path,mode,dev);return 0},doReadlink:function(path,buf,bufsize){if(bufsize<=0)return-28;var ret=FS.readlink(path);var len=Math.min(bufsize,lengthBytesUTF8(ret));var endChar=HEAP8[buf+len];stringToUTF8(ret,buf,bufsize+1);HEAP8[buf+len]=endChar;return len},doAccess:function(path,amode){if(amode&~7){return-28}var node;var lookup=FS.lookupPath(path,{follow:true});node=lookup.node;if(!node){return-44}var perms="";if(amode&4)perms+="r";if(amode&2)perms+="w";if(amode&1)perms+="x";if(perms&&FS.nodePermissions(node,perms)){return-2}return 0},doDup:function(path,flags,suggestFD){var suggest=FS.getStream(suggestFD);if(suggest)FS.close(suggest);return FS.open(path,flags,0,suggestFD,suggestFD).fd},doReadv:function(stream,iov,iovcnt,offset){var ret=0;for(var i=0;i>2];var len=HEAP32[iov+(i*8+4)>>2];var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2];var len=HEAP32[iov+(i*8+4)>>2];var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr}return ret},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},getStreamFromFD:function(fd){var stream=FS.getStream(fd);if(!stream)throw new FS.ErrnoError(8);return stream},get64:function(low,high){return low}};function ___sys_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=SYSCALLS.get();if(arg<0){return-28}var newStream;newStream=FS.open(stream.path,stream.flags,0,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=SYSCALLS.get();stream.flags|=arg;return 0}case 12:{var arg=SYSCALLS.get();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0;case 16:case 8:return-28;case 9:setErrNo(28);return-1;default:{return-28}}}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_getdents64(fd,dirp,count){try{var stream=SYSCALLS.getStreamFromFD(fd);if(!stream.getdents){stream.getdents=FS.readdir(stream.path)}var struct_size=280;var pos=0;var off=FS.llseek(stream,0,1);var idx=Math.floor(off/struct_size);while(idx>>0,(tempDouble=id,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[dirp+pos>>2]=tempI64[0],HEAP32[dirp+pos+4>>2]=tempI64[1];tempI64=[(idx+1)*struct_size>>>0,(tempDouble=(idx+1)*struct_size,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[dirp+pos+8>>2]=tempI64[0],HEAP32[dirp+pos+12>>2]=tempI64[1];HEAP16[dirp+pos+16>>1]=280;HEAP8[dirp+pos+18>>0]=type;stringToUTF8(name,dirp+pos+19,256);pos+=struct_size;idx+=1}FS.llseek(stream,idx*struct_size,0);return pos}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:case 21505:{if(!stream.tty)return-59;return 0}case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:{if(!stream.tty)return-59;return 0}case 21519:{if(!stream.tty)return-59;var argp=SYSCALLS.get();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21531:{var argp=SYSCALLS.get();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;return 0}case 21524:{if(!stream.tty)return-59;return 0}default:abort("bad ioctl syscall "+op)}}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_open(path,flags,varargs){SYSCALLS.varargs=varargs;try{var pathname=SYSCALLS.getStr(path);var mode=varargs?SYSCALLS.get():0;var stream=FS.open(pathname,flags,mode);return stream.fd}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_stat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.stat,path,buf)}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}var tupleRegistrations={};function runDestructors(destructors){while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}}function simpleReadValueFromPointer(pointer){return this["fromWireType"](HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var char_0=48;var char_9=57;function makeLegalFunctionName(name){if(undefined===name){return"_unknown"}name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return"_"+name}else{return name}}function createNamedFunction(name,body){name=makeLegalFunctionName(name);return new Function("body","return function "+name+"() {\n"+' "use strict";'+" return body.apply(this, arguments);\n"+"};\n")(body)}function extendError(baseErrorType,errorName){var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return this.name+": "+this.message}};return errorClass}var InternalError=undefined;function throwInternalError(message){throw new InternalError(message)}function whenDependentTypesAreResolved(myTypes,dependentTypes,getTypeConverters){myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i>shift])},destructorFunction:null})}function ClassHandle_isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right}function shallowCopyInternalPointer(o){return{count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType}}function throwInstanceAlreadyDeleted(obj){function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")}var finalizationGroup=false;function detachFinalizer(handle){}function runDestructor($$){if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}}function releaseClassHandle($$){$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}}function attachFinalizer(handle){if("undefined"===typeof FinalizationGroup){attachFinalizer=function(handle){return handle};return handle}finalizationGroup=new FinalizationGroup(function(iter){for(var result=iter.next();!result.done;result=iter.next()){var $$=result.value;if(!$$.ptr){console.warn("object already deleted: "+$$.ptr)}else{releaseClassHandle($$)}}});attachFinalizer=function(handle){finalizationGroup.register(handle,handle.$$,handle.$$);return handle};detachFinalizer=function(handle){finalizationGroup.unregister(handle.$$)};return attachFinalizer(handle)}function ClassHandle_clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}}function ClassHandle_delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}}function ClassHandle_isDeleted(){return!this.$$.ptr}var delayFunction=undefined;var deletionQueue=[];function flushPendingDeletes(){while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}}function ClassHandle_deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}function init_ClassHandle(){ClassHandle.prototype["isAliasOf"]=ClassHandle_isAliasOf;ClassHandle.prototype["clone"]=ClassHandle_clone;ClassHandle.prototype["delete"]=ClassHandle_delete;ClassHandle.prototype["isDeleted"]=ClassHandle_isDeleted;ClassHandle.prototype["deleteLater"]=ClassHandle_deleteLater}function ClassHandle(){}var registeredPointers={};function ensureOverloadTable(proto,methodName,humanName){if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(){if(!proto[methodName].overloadTable.hasOwnProperty(arguments.length)){throwBindingError("Function '"+humanName+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+proto[methodName].overloadTable+")!")}return proto[methodName].overloadTable[arguments.length].apply(this,arguments)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}}function exposePublicSymbol(name,value,numArguments){if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError("Cannot register public name '"+name+"' twice")}ensureOverloadTable(Module,name,name);if(Module.hasOwnProperty(numArguments)){throwBindingError("Cannot register multiple overloads of a function with the same number of arguments ("+numArguments+")!")}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;if(undefined!==numArguments){Module[name].numArguments=numArguments}}}function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}function upcastPointer(ptr,ptrClass,desiredClass){while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError("Expected null or instance of "+desiredClass.name+", got an instance of "+ptrClass.name)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr}function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,__emval_register(function(){clonedHandle["delete"]()}));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupporting sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+handle.$$.ptrType.name+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function RegisteredPointer_getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr}function RegisteredPointer_destructor(ptr){if(this.rawDestructor){this.rawDestructor(ptr)}}function RegisteredPointer_deleteObject(handle){if(handle!==null){handle["delete"]()}}function downcastPointer(ptr,ptrClass,desiredClass){if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)}function getInheritedInstanceCount(){return Object.keys(registeredInstances).length}function getLiveInheritedInstances(){var rv=[];for(var k in registeredInstances){if(registeredInstances.hasOwnProperty(k)){rv.push(registeredInstances[k])}}return rv}function setDelayFunction(fn){delayFunction=fn;if(deletionQueue.length&&delayFunction){delayFunction(flushPendingDeletes)}}function init_embind(){Module["getInheritedInstanceCount"]=getInheritedInstanceCount;Module["getLiveInheritedInstances"]=getLiveInheritedInstances;Module["flushPendingDeletes"]=flushPendingDeletes;Module["setDelayFunction"]=setDelayFunction}var registeredInstances={};function getBasestPointer(class_,ptr){if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr}function getInheritedInstance(class_,ptr){ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]}function makeClassHandle(prototype,record){if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record}}))}function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr:ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}function init_RegisteredPointer(){RegisteredPointer.prototype.getPointee=RegisteredPointer_getPointee;RegisteredPointer.prototype.destructor=RegisteredPointer_destructor;RegisteredPointer.prototype["argPackAdvance"]=8;RegisteredPointer.prototype["readValueFromPointer"]=simpleReadValueFromPointer;RegisteredPointer.prototype["deleteObject"]=RegisteredPointer_deleteObject;RegisteredPointer.prototype["fromWireType"]=RegisteredPointer_fromWireType}function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this["toWireType"]=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this["toWireType"]=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this["toWireType"]=genericPointerToWireType}}function replacePublicSymbol(name,value,numArguments){if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistant public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}}function dynCallLegacy(sig,ptr,args){var f=Module["dynCall_"+sig];return args&&args.length?f.apply(null,[ptr].concat(args)):f.call(null,ptr)}function dynCall(sig,ptr,args){if(sig.includes("j")){return dynCallLegacy(sig,ptr,args)}return wasmTable.get(ptr).apply(null,args)}function getDynCaller(sig,ptr){var argCache=[];return function(){argCache.length=arguments.length;for(var i=0;i0?", ":"")+argsListWired}invokerFnBody+=(returns?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i>2)+i])}return array}function __embind_register_class_class_function(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,fn){var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName=classType.name+"."+methodName;function unboundTypesHandler(){throwUnboundTypeError("Cannot call "+humanName+" due to unbound types",rawArgTypes)}var proto=classType.registeredClass.constructor;if(undefined===proto[methodName]){unboundTypesHandler.argCount=argCount-1;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-1]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));var func=craftInvokerFunction(humanName,invokerArgsArray,null,rawInvoker,fn);if(undefined===proto[methodName].overloadTable){func.argCount=argCount-1;proto[methodName]=func}else{proto[methodName].overloadTable[argCount-1]=func}return[]});return[]})}function validateThis(this_,classType,humanName){if(!(this_ instanceof Object)){throwBindingError(humanName+' with invalid "this": '+this_)}if(!(this_ instanceof classType.registeredClass.constructor)){throwBindingError(humanName+' incompatible with "this" of type '+this_.constructor.name)}if(!this_.$$.ptr){throwBindingError("cannot call emscripten binding method "+humanName+" on deleted object")}return upcastPointer(this_.$$.ptr,this_.$$.ptrType.registeredClass,classType.registeredClass)}function __embind_register_class_class_property(rawClassType,fieldName,rawFieldType,rawFieldPtr,getterSignature,getter,setterSignature,setter){fieldName=readLatin1String(fieldName);getter=embind__requireFunction(getterSignature,getter);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName=classType.name+"."+fieldName;var desc={get:function(){throwUnboundTypeError("Cannot access "+humanName+" due to unbound types",[rawFieldType])},enumerable:true,configurable:true};if(setter){desc.set=function(){throwUnboundTypeError("Cannot access "+humanName+" due to unbound types",[rawFieldType])}}else{desc.set=function(v){throwBindingError(humanName+" is a read-only property")}}Object.defineProperty(classType.registeredClass.constructor,fieldName,desc);whenDependentTypesAreResolved([],[rawFieldType],function(fieldType){fieldType=fieldType[0];var desc={get:function(){return fieldType["fromWireType"](getter(rawFieldPtr))},enumerable:true};if(setter){setter=embind__requireFunction(setterSignature,setter);desc.set=function(v){var destructors=[];setter(rawFieldPtr,fieldType["toWireType"](destructors,v));runDestructors(destructors)}}Object.defineProperty(classType.registeredClass.constructor,fieldName,desc);return[]});return[]})}function __embind_register_class_constructor(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor){assert(argCount>0);var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);var args=[rawConstructor];var destructors=[];whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName="constructor "+classType.name;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError("Cannot register multiple constructors with identical number of parameters ("+(argCount-1)+") for class '"+classType.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!")}classType.registeredClass.constructor_body[argCount-1]=function unboundTypeHandler(){throwUnboundTypeError("Cannot construct "+classType.name+" due to unbound types",rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){classType.registeredClass.constructor_body[argCount-1]=function constructor_body(){if(arguments.length!==argCount-1){throwBindingError(humanName+" called with "+arguments.length+" arguments, expected "+(argCount-1))}destructors.length=0;args.length=argCount;for(var i=1;i4&&0===--emval_handle_array[handle].refcount){emval_handle_array[handle]=undefined;emval_free_list.push(handle)}}function count_emval_handles(){var count=0;for(var i=5;i>1])};case 2:return function(pointer){var heap=signed?HEAP32:HEAPU32;return this["fromWireType"](heap[pointer>>2])};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_enum(rawType,name,size,isSigned){var shift=getShiftFromSize(size);name=readLatin1String(name);function ctor(){}ctor.values={};registerType(rawType,{name:name,constructor:ctor,"fromWireType":function(c){return this.constructor.values[c]},"toWireType":function(destructors,c){return c.value},"argPackAdvance":8,"readValueFromPointer":enumReadValueFromPointer(name,shift,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor)}function requireRegisteredType(rawType,humanName){var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(humanName+" has unknown type "+getTypeName(rawType))}return impl}function __embind_register_enum_value(rawEnumType,name,enumValue){var enumType=requireRegisteredType(rawEnumType,"enum");name=readLatin1String(name);var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(enumType.name+"_"+name,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value}function _embind_repr(v){if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}}function floatReadValueFromPointer(name,shift){switch(shift){case 2:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 3:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError("Unknown float type: "+name)}}function __embind_register_float(rawType,name,size){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(value){return value},"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}return value},"argPackAdvance":8,"readValueFromPointer":floatReadValueFromPointer(name,shift),destructorFunction:null})}function __embind_register_function(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn){var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=readLatin1String(name);rawInvoker=embind__requireFunction(signature,rawInvoker);exposePublicSymbol(name,function(){throwUnboundTypeError("Cannot call "+name+" due to unbound types",argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,function(argTypes){var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn),argCount-1);return[]})}function integerReadValueFromPointer(name,shift,signed){switch(shift){case 0:return signed?function readS8FromPointer(pointer){return HEAP8[pointer]}:function readU8FromPointer(pointer){return HEAPU8[pointer]};case 1:return signed?function readS16FromPointer(pointer){return HEAP16[pointer>>1]}:function readU16FromPointer(pointer){return HEAPU16[pointer>>1]};case 2:return signed?function readS32FromPointer(pointer){return HEAP32[pointer>>2]}:function readU32FromPointer(pointer){return HEAPU32[pointer>>2]};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_integer(primitiveType,name,size,minRange,maxRange){name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var shift=getShiftFromSize(size);var fromWireType=function(value){return value};if(minRange===0){var bitshift=32-8*size;fromWireType=function(value){return value<>>bitshift}}var isUnsignedType=name.includes("unsigned");registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}if(valuemaxRange){throw new TypeError('Passing a number "'+_embind_repr(value)+'" from JS side to C/C++ side to an argument of type "'+name+'", which is outside the valid range ['+minRange+", "+maxRange+"]!")}return isUnsignedType?value>>>0:value|0},"argPackAdvance":8,"readValueFromPointer":integerReadValueFromPointer(name,shift,minRange!==0),destructorFunction:null})}function __embind_register_memory_view(rawType,dataTypeIndex,name){var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){handle=handle>>2;var heap=HEAPU32;var size=heap[handle];var data=heap[handle+1];return new TA(buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":8,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})}function __embind_register_smart_ptr(rawType,rawPointeeType,name,sharingPolicy,getPointeeSignature,rawGetPointee,constructorSignature,rawConstructor,shareSignature,rawShare,destructorSignature,rawDestructor){name=readLatin1String(name);rawGetPointee=embind__requireFunction(getPointeeSignature,rawGetPointee);rawConstructor=embind__requireFunction(constructorSignature,rawConstructor);rawShare=embind__requireFunction(shareSignature,rawShare);rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);whenDependentTypesAreResolved([rawType],[rawPointeeType],function(pointeeType){pointeeType=pointeeType[0];var registeredPointer=new RegisteredPointer(name,pointeeType.registeredClass,false,false,true,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor);return[registeredPointer]})}function __embind_register_std_string(rawType,name){name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var str;if(stdStringIsUTF8){var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr+4,length+1)}else{if(valueIsOfTypeString){for(var i=0;i255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+4+i]=charCode}}else{for(var i=0;i>2];var HEAP=getHeap();var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||HEAP[currentBytePtr>>shift]==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":function(destructors,value){if(!(typeof value==="string")){throwBindingError("Cannot pass non-string to C++ string type "+name)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length>>shift;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:function(ptr){_free(ptr)}})}function __embind_register_value_array(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor){tupleRegistrations[rawType]={name:readLatin1String(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),elements:[]}}function __embind_register_value_array_element(rawTupleType,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){tupleRegistrations[rawTupleType].elements.push({getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})}function __embind_register_void(rawType,name){name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":function(){return undefined},"toWireType":function(destructors,o){return undefined}})}function requireHandle(handle){if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handle_array[handle].value}function __emval_as(handle,returnType,destructorsRef){handle=requireHandle(handle);returnType=requireRegisteredType(returnType,"emval::as");var destructors=[];var rd=__emval_register(destructors);HEAP32[destructorsRef>>2]=rd;return returnType["toWireType"](destructors,handle)}function __emval_lookupTypes(argCount,argTypes){var a=new Array(argCount);for(var i=0;i>2)+i],"parameter "+i)}return a}function __emval_call(handle,argCount,argTypes,argv){handle=requireHandle(handle);var types=__emval_lookupTypes(argCount,argTypes);var args=new Array(argCount);for(var i=0;i4){emval_handle_array[handle].refcount+=1}}function __emval_new_array(){return __emval_register([])}function __emval_new_cstring(v){return __emval_register(getStringOrSymbol(v))}function __emval_new_object(){return __emval_register({})}function __emval_run_destructors(handle){var destructors=emval_handle_array[handle].value;runDestructors(destructors);__emval_decref(handle)}function __emval_set_property(handle,key,value){handle=requireHandle(handle);key=requireHandle(key);value=requireHandle(value);handle[key]=value}function __emval_take_value(type,argv){type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](argv);return __emval_register(v)}function __emval_typeof(handle){handle=requireHandle(handle);return __emval_register(typeof handle)}function _abort(){abort()}var readAsmConstArgsArray=[];function readAsmConstArgs(sigPtr,buf){readAsmConstArgsArray.length=0;var ch;buf>>=2;while(ch=HEAPU8[sigPtr++]){var double=ch<105;if(double&&buf&1)buf++;readAsmConstArgsArray.push(double?HEAPF64[buf++>>1]:HEAP32[buf]);++buf}return readAsmConstArgsArray}function _emscripten_asm_const_int(code,sigPtr,argbuf){var args=readAsmConstArgs(sigPtr,argbuf);return ASM_CONSTS[code].apply(null,args)}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize+33554432/cutDown;var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var ENV={};function getExecutableName(){return thisProgram||"./this.program"}function getEnvStrings(){if(!getEnvStrings.strings){var lang=(typeof navigator==="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={"USER":"web_user","LOGNAME":"web_user","PATH":"/","PWD":"/","HOME":"/home/web_user","LANG":lang,"_":getExecutableName()};for(var x in ENV){env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(x+"="+env[x])}getEnvStrings.strings=strings}return getEnvStrings.strings}function _environ_get(__environ,environ_buf){try{var bufSize=0;getEnvStrings().forEach(function(string,i){var ptr=environ_buf+bufSize;HEAP32[__environ+i*4>>2]=ptr;writeAsciiToMemory(string,ptr);bufSize+=string.length+1});return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _environ_sizes_get(penviron_count,penviron_buf_size){try{var strings=getEnvStrings();HEAP32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(function(string){bufSize+=string.length+1});HEAP32[penviron_buf_size>>2]=bufSize;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=SYSCALLS.doReadv(stream,iov,iovcnt);HEAP32[pnum>>2]=num;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){try{var stream=SYSCALLS.getStreamFromFD(fd);var HIGH_OFFSET=4294967296;var offset=offset_high*HIGH_OFFSET+(offset_low>>>0);var DOUBLE_LIMIT=9007199254740992;if(offset<=-DOUBLE_LIMIT||offset>=DOUBLE_LIMIT){return-61}FS.llseek(stream,offset,whence);tempI64=[stream.position>>>0,(tempDouble=stream.position,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[newOffset>>2]=tempI64[0],HEAP32[newOffset+4>>2]=tempI64[1];if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=SYSCALLS.doWritev(stream,iov,iovcnt);HEAP32[pnum>>2]=num;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _getTempRet0(){return getTempRet0()}function _llvm_eh_typeid_for(type){return type}function _setTempRet0(val){setTempRet0(val)}function __isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}function __arraySum(array,index){var sum=0;for(var i=0;i<=index;sum+=array[i++]){}return sum}var __MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31];var __MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31];function __addDays(date,days){var newDate=new Date(date.getTime());while(days>0){var leap=__isLeapYear(newDate.getFullYear());var currentMonth=newDate.getMonth();var daysInCurrentMonth=(leap?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR)[currentMonth];if(days>daysInCurrentMonth-newDate.getDate()){days-=daysInCurrentMonth-newDate.getDate()+1;newDate.setDate(1);if(currentMonth<11){newDate.setMonth(currentMonth+1)}else{newDate.setMonth(0);newDate.setFullYear(newDate.getFullYear()+1)}}else{newDate.setDate(newDate.getDate()+days);return newDate}}return newDate}function _strftime(s,maxsize,format,tm){var tm_zone=HEAP32[tm+40>>2];var date={tm_sec:HEAP32[tm>>2],tm_min:HEAP32[tm+4>>2],tm_hour:HEAP32[tm+8>>2],tm_mday:HEAP32[tm+12>>2],tm_mon:HEAP32[tm+16>>2],tm_year:HEAP32[tm+20>>2],tm_wday:HEAP32[tm+24>>2],tm_yday:HEAP32[tm+28>>2],tm_isdst:HEAP32[tm+32>>2],tm_gmtoff:HEAP32[tm+36>>2],tm_zone:tm_zone?UTF8ToString(tm_zone):""};var pattern=UTF8ToString(format);var EXPANSION_RULES_1={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var rule in EXPANSION_RULES_1){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_1[rule])}var WEEKDAYS=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];var MONTHS=["January","February","March","April","May","June","July","August","September","October","November","December"];function leadingSomething(value,digits,character){var str=typeof value==="number"?value.toString():value||"";while(str.length0?1:0}var compare;if((compare=sgn(date1.getFullYear()-date2.getFullYear()))===0){if((compare=sgn(date1.getMonth()-date2.getMonth()))===0){compare=sgn(date1.getDate()-date2.getDate())}}return compare}function getFirstWeekStartDate(janFourth){switch(janFourth.getDay()){case 0:return new Date(janFourth.getFullYear()-1,11,29);case 1:return janFourth;case 2:return new Date(janFourth.getFullYear(),0,3);case 3:return new Date(janFourth.getFullYear(),0,2);case 4:return new Date(janFourth.getFullYear(),0,1);case 5:return new Date(janFourth.getFullYear()-1,11,31);case 6:return new Date(janFourth.getFullYear()-1,11,30)}}function getWeekBasedYear(date){var thisDate=__addDays(new Date(date.tm_year+1900,0,1),date.tm_yday);var janFourthThisYear=new Date(thisDate.getFullYear(),0,4);var janFourthNextYear=new Date(thisDate.getFullYear()+1,0,4);var firstWeekStartThisYear=getFirstWeekStartDate(janFourthThisYear);var firstWeekStartNextYear=getFirstWeekStartDate(janFourthNextYear);if(compareByDay(firstWeekStartThisYear,thisDate)<=0){if(compareByDay(firstWeekStartNextYear,thisDate)<=0){return thisDate.getFullYear()+1}else{return thisDate.getFullYear()}}else{return thisDate.getFullYear()-1}}var EXPANSION_RULES_2={"%a":function(date){return WEEKDAYS[date.tm_wday].substring(0,3)},"%A":function(date){return WEEKDAYS[date.tm_wday]},"%b":function(date){return MONTHS[date.tm_mon].substring(0,3)},"%B":function(date){return MONTHS[date.tm_mon]},"%C":function(date){var year=date.tm_year+1900;return leadingNulls(year/100|0,2)},"%d":function(date){return leadingNulls(date.tm_mday,2)},"%e":function(date){return leadingSomething(date.tm_mday,2," ")},"%g":function(date){return getWeekBasedYear(date).toString().substring(2)},"%G":function(date){return getWeekBasedYear(date)},"%H":function(date){return leadingNulls(date.tm_hour,2)},"%I":function(date){var twelveHour=date.tm_hour;if(twelveHour==0)twelveHour=12;else if(twelveHour>12)twelveHour-=12;return leadingNulls(twelveHour,2)},"%j":function(date){return leadingNulls(date.tm_mday+__arraySum(__isLeapYear(date.tm_year+1900)?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR,date.tm_mon-1),3)},"%m":function(date){return leadingNulls(date.tm_mon+1,2)},"%M":function(date){return leadingNulls(date.tm_min,2)},"%n":function(){return"\n"},"%p":function(date){if(date.tm_hour>=0&&date.tm_hour<12){return"AM"}else{return"PM"}},"%S":function(date){return leadingNulls(date.tm_sec,2)},"%t":function(){return"\t"},"%u":function(date){return date.tm_wday||7},"%U":function(date){var janFirst=new Date(date.tm_year+1900,0,1);var firstSunday=janFirst.getDay()===0?janFirst:__addDays(janFirst,7-janFirst.getDay());var endDate=new Date(date.tm_year+1900,date.tm_mon,date.tm_mday);if(compareByDay(firstSunday,endDate)<0){var februaryFirstUntilEndMonth=__arraySum(__isLeapYear(endDate.getFullYear())?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR,endDate.getMonth()-1)-31;var firstSundayUntilEndJanuary=31-firstSunday.getDate();var days=firstSundayUntilEndJanuary+februaryFirstUntilEndMonth+endDate.getDate();return leadingNulls(Math.ceil(days/7),2)}return compareByDay(firstSunday,janFirst)===0?"01":"00"},"%V":function(date){var janFourthThisYear=new Date(date.tm_year+1900,0,4);var janFourthNextYear=new Date(date.tm_year+1901,0,4);var firstWeekStartThisYear=getFirstWeekStartDate(janFourthThisYear);var firstWeekStartNextYear=getFirstWeekStartDate(janFourthNextYear);var endDate=__addDays(new Date(date.tm_year+1900,0,1),date.tm_yday);if(compareByDay(endDate,firstWeekStartThisYear)<0){return"53"}if(compareByDay(firstWeekStartNextYear,endDate)<=0){return"01"}var daysDifference;if(firstWeekStartThisYear.getFullYear()=0;off=Math.abs(off)/60;off=off/60*100+off%60;return(ahead?"+":"-")+String("0000"+off).slice(-4)},"%Z":function(date){return date.tm_zone},"%%":function(){return"%"}};for(var rule in EXPANSION_RULES_2){if(pattern.includes(rule)){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_2[rule](date))}}var bytes=intArrayFromString(pattern,false);if(bytes.length>maxsize){return 0}writeArrayToMemory(bytes,s);return bytes.length-1}function _strftime_l(s,maxsize,format,tm){return _strftime(s,maxsize,format,tm)}var FSNode=function(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.mounted=null;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.node_ops={};this.stream_ops={};this.rdev=rdev};var readMode=292|73;var writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(val){val?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(val){val?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}});FS.FSNode=FSNode;FS.staticInit();Module["FS_createPath"]=FS.createPath;Module["FS_createDataFile"]=FS.createDataFile;Module["FS_createPreloadedFile"]=FS.createPreloadedFile;Module["FS_createLazyFile"]=FS.createLazyFile;Module["FS_createDevice"]=FS.createDevice;Module["FS_unlink"]=FS.unlink;InternalError=Module["InternalError"]=extendError(Error,"InternalError");embind_init_charCodes();BindingError=Module["BindingError"]=extendError(Error,"BindingError");init_ClassHandle();init_RegisteredPointer();init_embind();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");init_emval();function intArrayFromString(stringy,dontAddNull,length){var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}var asmLibraryArg={"B":___assert_fail,"o":___cxa_allocate_exception,"p":___cxa_begin_catch,"z":___cxa_end_catch,"b":___cxa_find_matching_catch_2,"h":___cxa_find_matching_catch_3,"Ka":___cxa_find_matching_catch_4,"q":___cxa_free_exception,"da":___cxa_rethrow,"K":___cxa_throw,"wa":___cxa_uncaught_exceptions,"e":___resumeException,"fa":___sys_fcntl64,"Da":___sys_getdents64,"Ca":___sys_ioctl,"ha":___sys_open,"za":___sys_stat64,"Qa":__embind_finalize_value_array,"oa":__embind_register_bigint,"Fa":__embind_register_bool,"v":__embind_register_class,"A":__embind_register_class_class_function,"s":__embind_register_class_class_property,"y":__embind_register_class_constructor,"j":__embind_register_class_function,"H":__embind_register_class_property,"T":__embind_register_constant,"Ea":__embind_register_emval,"S":__embind_register_enum,"R":__embind_register_enum_value,"ia":__embind_register_float,"G":__embind_register_function,"N":__embind_register_integer,"M":__embind_register_memory_view,"r":__embind_register_smart_ptr,"ja":__embind_register_std_string,"aa":__embind_register_std_wstring,"na":__embind_register_value_array,"_":__embind_register_value_array_element,"Ga":__embind_register_void,"O":__emval_as,"Ra":__emval_call,"Z":__emval_call_void_method,"ga":__emval_decref,"Y":__emval_get_method_caller,"Pa":__emval_get_property,"ka":__emval_incref,"Ta":__emval_new_array,"Oa":__emval_new_cstring,"La":__emval_new_object,"Na":__emval_run_destructors,"Sa":__emval_set_property,"C":__emval_take_value,"Ma":__emval_typeof,"ua":_abort,"ca":_emscripten_asm_const_int,"ta":_emscripten_memcpy_big,"$":_emscripten_resize_heap,"xa":_environ_get,"ya":_environ_sizes_get,"W":_fd_close,"Ba":_fd_read,"Ua":_fd_seek,"Aa":_fd_write,"a":_getTempRet0,"Ha":invoke_di,"ba":invoke_fi,"Ja":invoke_fifii,"ra":invoke_fii,"ma":invoke_fiii,"x":invoke_i,"g":invoke_ii,"Ia":invoke_iid,"J":invoke_iif,"la":invoke_iiff,"X":invoke_iifff,"d":invoke_iii,"i":invoke_iiii,"t":invoke_iiiii,"ea":invoke_iiiiid,"w":invoke_iiiiii,"D":invoke_iiiiiii,"I":invoke_iiiiiiii,"V":invoke_iiiiiiiiiiii,"m":invoke_v,"l":invoke_vi,"sa":invoke_vid,"L":invoke_vif,"f":invoke_vii,"qa":invoke_viif,"c":invoke_viii,"k":invoke_viiii,"Q":invoke_viiiiffiiii,"n":invoke_viiiii,"u":invoke_viiiiii,"F":invoke_viiiiiii,"P":invoke_viiiiiiiiii,"U":invoke_viiiiiiiiiiiiiii,"E":_llvm_eh_typeid_for,"pa":_setTempRet0,"va":_strftime_l};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["Wa"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["Xa"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["Za"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["_a"]).apply(null,arguments)};var ___getTypeName=Module["___getTypeName"]=function(){return(___getTypeName=Module["___getTypeName"]=Module["asm"]["$a"]).apply(null,arguments)};var ___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=function(){return(___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=Module["asm"]["ab"]).apply(null,arguments)};var stackSave=Module["stackSave"]=function(){return(stackSave=Module["stackSave"]=Module["asm"]["bb"]).apply(null,arguments)};var stackRestore=Module["stackRestore"]=function(){return(stackRestore=Module["stackRestore"]=Module["asm"]["cb"]).apply(null,arguments)};var stackAlloc=Module["stackAlloc"]=function(){return(stackAlloc=Module["stackAlloc"]=Module["asm"]["db"]).apply(null,arguments)};var _setThrew=Module["_setThrew"]=function(){return(_setThrew=Module["_setThrew"]=Module["asm"]["eb"]).apply(null,arguments)};var ___cxa_can_catch=Module["___cxa_can_catch"]=function(){return(___cxa_can_catch=Module["___cxa_can_catch"]=Module["asm"]["fb"]).apply(null,arguments)};var ___cxa_is_pointer_type=Module["___cxa_is_pointer_type"]=function(){return(___cxa_is_pointer_type=Module["___cxa_is_pointer_type"]=Module["asm"]["gb"]).apply(null,arguments)};var dynCall_viijii=Module["dynCall_viijii"]=function(){return(dynCall_viijii=Module["dynCall_viijii"]=Module["asm"]["hb"]).apply(null,arguments)};var dynCall_jiji=Module["dynCall_jiji"]=function(){return(dynCall_jiji=Module["dynCall_jiji"]=Module["asm"]["ib"]).apply(null,arguments)};var dynCall_iiiiij=Module["dynCall_iiiiij"]=function(){return(dynCall_iiiiij=Module["dynCall_iiiiij"]=Module["asm"]["jb"]).apply(null,arguments)};var dynCall_iiiiijj=Module["dynCall_iiiiijj"]=function(){return(dynCall_iiiiijj=Module["dynCall_iiiiijj"]=Module["asm"]["kb"]).apply(null,arguments)};var dynCall_iiiiiijj=Module["dynCall_iiiiiijj"]=function(){return(dynCall_iiiiiijj=Module["dynCall_iiiiiijj"]=Module["asm"]["lb"]).apply(null,arguments)};function invoke_ii(index,a1){var sp=stackSave();try{return wasmTable.get(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viii(index,a1,a2,a3){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vii(index,a1,a2){var sp=stackSave();try{wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiii(index,a1,a2,a3,a4){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iii(index,a1,a2){var sp=stackSave();try{return wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiii(index,a1,a2,a3,a4){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiii(index,a1,a2,a3){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vi(index,a1){var sp=stackSave();try{wasmTable.get(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_i(index){var sp=stackSave();try{return wasmTable.get(index)()}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_v(index){var sp=stackSave();try{wasmTable.get(index)()}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vif(index,a1,a2){var sp=stackSave();try{wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fifii(index,a1,a2,a3,a4){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iif(index,a1,a2){var sp=stackSave();try{return wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iid(index,a1,a2){var sp=stackSave();try{return wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fi(index,a1){var sp=stackSave();try{return wasmTable.get(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_di(index,a1){var sp=stackSave();try{return wasmTable.get(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iifff(index,a1,a2,a3,a4){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiiii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fiii(index,a1,a2,a3){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiff(index,a1,a2,a3){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiffiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vid(index,a1,a2){var sp=stackSave();try{wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fii(index,a1,a2){var sp=stackSave();try{return wasmTable.get(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiid(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11){var sp=stackSave();try{return wasmTable.get(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viif(index,a1,a2,a3){var sp=stackSave();try{wasmTable.get(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["FS_createPath"]=FS.createPath;Module["FS_createDataFile"]=FS.createDataFile;Module["FS_createPreloadedFile"]=FS.createPreloadedFile;Module["FS_createLazyFile"]=FS.createLazyFile;Module["FS_createDevice"]=FS.createDevice;Module["FS_unlink"]=FS.unlink;var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();var postRegistrations=[];function onModuleReady(callback){postRegistrations.push(callback)}Module.onRuntimeInitialized=function(){for(var callback of postRegistrations){callback()}};(function(){var nodeFs;var nodePath;var nodeProcess;var pathSep;var wasmPathSep="/";var ENVIRONMENT_IS_WEB;var ENVIRONMENT_IS_NODE;var PATH_LIST_SEPARATOR=";";var callId=0;var MAX_CALL_ID=99999;function removeDuplicates(array){var seen={};return array.filter(function(item){return seen.hasOwnProperty(item)?false:seen[item]=true})}function createFilePath(fileName,filePath,sep=pathSep){var pathSlash=filePath.endsWith(sep);var fileSlash=fileName.startsWith(sep);var path;if(pathSlash||fileSlash){if(pathSlash&&fileSlash){path=filePath.substring(0,filePath.length-1)+fileName}else{path=filePath+fileName}}else{path=filePath+sep+fileName}return path}function fetchXml(fileName,searchPaths){var i=0;function fetchHandler(){var filePath=createFilePath(fileName,searchPaths[i++]);return fetch(filePath).then(function(response){if(response.status===200){return response.text().then(function(data){var url=new URL(response.url);var filePath=url.pathname.substring(1);filePath=filePath.replace(new RegExp(pathSep,"g"),wasmPathSep);return{data:data,filePath:filePath,fullPath:url.origin+url.pathname}})}else if(i/g;var matches=file.matchAll(includeRegex);var includes=[];for(var match of matches){includes.push(match[1])}return includes}function loadFile(fileToLoad,searchPaths){var promise;if(ENVIRONMENT_IS_WEB){promise=fetchXml(fileToLoad,searchPaths)}else if(ENVIRONMENT_IS_NODE){promise=loadXml(fileToLoad,searchPaths)}else{throw new Error("Unknown environment!")}return promise}function trackPath(path,filesUploaded,isFile=false){if(isFile){if(!filesUploaded.files){filesUploaded.files=[]}filesUploaded.files.push(path)}else{if(!filesUploaded.folders){filesUploaded.folders=[]}filesUploaded.folders.splice(0,0,path)}}function createInWasm(file,data,filesUploaded,wasmRootFolder,isFile=true){var folders;if(isFile){folders=file.substring(1,file.lastIndexOf(wasmPathSep)).split(wasmPathSep)}else{folders=file.substring(wasmRootFolder.length).split(wasmPathSep)}var folder=wasmRootFolder;for(var i=1;i-1?pos+1:0);var element=document.createElement("a");element.setAttribute("href","data:text/plain;charset=utf-8,"+encodeURIComponent(content));element.setAttribute("download",fileName);element.style.display="none";document.body.appendChild(element);element.click();document.body.removeChild(element)}}onModuleReady(function(){ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";if(ENVIRONMENT_IS_WEB){pathSep="/"}if(ENVIRONMENT_IS_NODE){nodeFs=require("fs");nodePath=require("path");nodeProcess=require("process");pathSep=nodePath.sep}function _readFromXmlString(doc,str,searchPath,readOptions,filesLoaded=[],initialFilePath=""){var wasmRootFolder="/readFromXml"+callId++%MAX_CALL_ID;var searchPaths=prepareSearchPaths(searchPath);try{FS.mkdir(wasmRootFolder)}catch(e){throw new Error("Failed to create folder in WASM FS.")}var includes=[];if(!readOptions||readOptions.readXIncludes){includes=getIncludes(str)}var filesUploaded={files:[],folders:[]};var wasmCwd=getWasmCwd(wasmRootFolder);var initialFileName=wasmCwd+"/ChosenToHopefullyNotClashWithAnyOtherFile123";if(initialFilePath){var sep=pathSep==="\\"?"\\\\":pathSep;initialFileName=initialFilePath.replace(new RegExp(sep,"g"),wasmPathSep);initialFileName=createFilePath(initialFileName,wasmRootFolder,wasmPathSep);createInWasm(wasmCwd,null,filesUploaded,wasmRootFolder,false)}createInWasm(initialFileName,str,filesUploaded,wasmRootFolder);function loadFiles(filesLoadedList,fileList,pathsList){var promises=[Promise.resolve()];for(var fileToLoad of fileList){var filesLoadedCopy=filesLoadedList.slice();var searchPathsCopy=pathsList.slice();var promise=loadFile(fileToLoad,searchPathsCopy).then(function(result){if(filesLoadedCopy.includes(result.fullPath)){throw new Error("Cycle detected!\n"+filesLoadedCopy.join("\n-> ")+"\n-> "+result.fullPath)}filesLoadedCopy.push(result.fullPath);var pos=result.fullPath.lastIndexOf(pathSep);var path=result.fullPath.substring(0,pos>-1?pos:0);if(!searchPathsCopy.includes(path)){searchPathsCopy.splice(0,0,path)}var includes=getIncludes(result.data);var wasmPath=createFilePath(result.filePath,wasmRootFolder,wasmPathSep);if(!filesUploaded.files.includes(wasmPath)){createInWasm(wasmPath,result.data,filesUploaded,wasmRootFolder)}return loadFiles(filesLoadedCopy,includes,searchPathsCopy)});promises.push(promise)}return Promise.all(promises)}return loadFiles(filesLoaded,includes,searchPaths).then(function(){var wasmSearchPath=getWasmSearchPath(searchPath,wasmRootFolder);FS.chdir(wasmCwd);try{var searchPathEnv=Module.getEnviron(Module.MATERIALX_SEARCH_PATH_ENV_VAR);if(searchPathEnv){var wasmSearchPathEnv=makeWasmAbsolute(searchPathEnv,wasmRootFolder);Module.setEnviron(Module.MATERIALX_SEARCH_PATH_ENV_VAR,wasmSearchPathEnv)}Module._readFromXmlFile(doc,initialFileName,wasmSearchPath,readOptions);if(searchPathEnv){Module.setEnviron(Module.MATERIALX_SEARCH_PATH_ENV_VAR,searchPathEnv)}}catch(errPtr){throw new Error("Failed to read MaterialX files from WASM FS: "+Module.getExceptionMessage(errPtr))}try{for(var file of filesUploaded.files){FS.unlink(file)}FS.chdir("/");for(var folder of filesUploaded.folders){FS.rmdir(folder)}FS.rmdir(wasmRootFolder)}catch(e){throw new Error("Failed to delete temporary files from WASM FS.")}})}Module.readFromXmlString=function(doc,str,searchPath="",readOptions=null){if(arguments.length<2||arguments.length>4){throw new Error("Function readFromXmlString called with an invalid number of arguments ("+arguments.length+") - expects 2 to 4!")}return _readFromXmlString(doc,str,searchPath,readOptions)};Module.readFromXmlFile=function(doc,fileName,searchPath="",readOptions=null){if(arguments.length<2||arguments.length>4){throw new Error("Function readFromXmlFile called with an invalid number of arguments ("+arguments.length+") - expects 2 to 4!")}var searchPaths=prepareSearchPaths(searchPath);return loadFile(fileName,searchPaths).then(function(result){var filesLoaded=[result.fullPath];var pos=result.fullPath.lastIndexOf(pathSep);var path=result.fullPath.substring(0,pos>-1?pos:0);searchPath=searchPath.concat(PATH_LIST_SEPARATOR,path);return _readFromXmlString(doc,result.data,searchPath,readOptions,filesLoaded,result.filePath)})};Module.writeToXmlFile=function(doc,fileName,writeOptions=null){if(arguments.length<2||arguments.length>3){throw new Error("Function writeToXmlFile called with an invalid number of arguments ("+arguments.length+") - expects 2 to 3!")}var file=Module.writeToXmlString(doc,writeOptions);storeFileToDisk(fileName,file)};Module.exportToXmlFile=function(doc,fileName,exportOptions=null){if(arguments.length<2||arguments.length>3){throw new Error("Function exportToXmlFile called with an invalid number of arguments ("+arguments.length+") - expects 2 to 3!")}var file=Module.exportToXmlString(doc,exportOptions);storeFileToDisk(fileName,file)}})})(); + + + return MaterialX.ready +} +); +})(); +if (typeof exports === 'object' && typeof module === 'object') + module.exports = MaterialX; +else if (typeof define === 'function' && define['amd']) + define([], function() { return MaterialX; }); +else if (typeof exports === 'object') + exports["MaterialX"] = MaterialX; diff --git a/JsMaterialXGenShader.wasm b/JsMaterialXGenShader.wasm new file mode 100644 index 0000000000..73844ee5fe Binary files /dev/null and b/JsMaterialXGenShader.wasm differ diff --git a/Lights/environment_map.mtlx b/Lights/environment_map.mtlx new file mode 100644 index 0000000000..1e294539d6 --- /dev/null +++ b/Lights/environment_map.mtlx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Lights/goegap.hdr b/Lights/goegap.hdr new file mode 100644 index 0000000000..9708bd5583 Binary files /dev/null and b/Lights/goegap.hdr differ diff --git a/Lights/goegap_split.hdr b/Lights/goegap_split.hdr new file mode 100644 index 0000000000..6560d218ef Binary files /dev/null and b/Lights/goegap_split.hdr differ diff --git a/Lights/goegap_split.mtlx b/Lights/goegap_split.mtlx new file mode 100644 index 0000000000..f987f99cc9 --- /dev/null +++ b/Lights/goegap_split.mtlx @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/Lights/irradiance/goegap.hdr b/Lights/irradiance/goegap.hdr new file mode 100644 index 0000000000..6423883051 Binary files /dev/null and b/Lights/irradiance/goegap.hdr differ diff --git a/Lights/irradiance/goegap_split.hdr b/Lights/irradiance/goegap_split.hdr new file mode 100644 index 0000000000..86b785b085 Binary files /dev/null and b/Lights/irradiance/goegap_split.hdr differ diff --git a/Lights/irradiance/san_giuseppe_bridge.hdr b/Lights/irradiance/san_giuseppe_bridge.hdr new file mode 100644 index 0000000000..614813690f Binary files /dev/null and b/Lights/irradiance/san_giuseppe_bridge.hdr differ diff --git a/Lights/irradiance/san_giuseppe_bridge_split.hdr b/Lights/irradiance/san_giuseppe_bridge_split.hdr new file mode 100644 index 0000000000..c5ddbd509e Binary files /dev/null and b/Lights/irradiance/san_giuseppe_bridge_split.hdr differ diff --git a/Lights/irradiance/table_mountain.hdr b/Lights/irradiance/table_mountain.hdr new file mode 100644 index 0000000000..11ec06cdb1 Binary files /dev/null and b/Lights/irradiance/table_mountain.hdr differ diff --git a/Lights/irradiance/table_mountain_split.hdr b/Lights/irradiance/table_mountain_split.hdr new file mode 100644 index 0000000000..fa7d7d3a91 Binary files /dev/null and b/Lights/irradiance/table_mountain_split.hdr differ diff --git a/Lights/san_giuseppe_bridge.hdr b/Lights/san_giuseppe_bridge.hdr new file mode 100644 index 0000000000..b8ab76731b Binary files /dev/null and b/Lights/san_giuseppe_bridge.hdr differ diff --git a/Lights/san_giuseppe_bridge_split.hdr b/Lights/san_giuseppe_bridge_split.hdr new file mode 100644 index 0000000000..2f1b71dced Binary files /dev/null and b/Lights/san_giuseppe_bridge_split.hdr differ diff --git a/Lights/san_giuseppe_bridge_split.mtlx b/Lights/san_giuseppe_bridge_split.mtlx new file mode 100644 index 0000000000..31938e9484 --- /dev/null +++ b/Lights/san_giuseppe_bridge_split.mtlx @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/Lights/table_mountain.hdr b/Lights/table_mountain.hdr new file mode 100644 index 0000000000..9e34e9aa4a Binary files /dev/null and b/Lights/table_mountain.hdr differ diff --git a/Lights/table_mountain_split.hdr b/Lights/table_mountain_split.hdr new file mode 100644 index 0000000000..5230ecfafc Binary files /dev/null and b/Lights/table_mountain_split.hdr differ diff --git a/Lights/table_mountain_split.mtlx b/Lights/table_mountain_split.mtlx new file mode 100644 index 0000000000..658b60b290 --- /dev/null +++ b/Lights/table_mountain_split.mtlx @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/Materials/Examples/GltfPbr/boombox/BoomBox_baseColor.png b/Materials/Examples/GltfPbr/boombox/BoomBox_baseColor.png new file mode 100644 index 0000000000..d361e39b59 Binary files /dev/null and b/Materials/Examples/GltfPbr/boombox/BoomBox_baseColor.png differ diff --git a/Materials/Examples/GltfPbr/boombox/BoomBox_emissive.png b/Materials/Examples/GltfPbr/boombox/BoomBox_emissive.png new file mode 100644 index 0000000000..c9e48ff03a Binary files /dev/null and b/Materials/Examples/GltfPbr/boombox/BoomBox_emissive.png differ diff --git a/Materials/Examples/GltfPbr/boombox/BoomBox_normal.png b/Materials/Examples/GltfPbr/boombox/BoomBox_normal.png new file mode 100644 index 0000000000..ca53dc9d72 Binary files /dev/null and b/Materials/Examples/GltfPbr/boombox/BoomBox_normal.png differ diff --git a/Materials/Examples/GltfPbr/boombox/BoomBox_occlusionRoughnessMetallic.png b/Materials/Examples/GltfPbr/boombox/BoomBox_occlusionRoughnessMetallic.png new file mode 100644 index 0000000000..0bd0d5af59 Binary files /dev/null and b/Materials/Examples/GltfPbr/boombox/BoomBox_occlusionRoughnessMetallic.png differ diff --git a/Materials/Examples/GltfPbr/gltf_pbr_boombox.mtlx b/Materials/Examples/GltfPbr/gltf_pbr_boombox.mtlx new file mode 100644 index 0000000000..411f316672 --- /dev/null +++ b/Materials/Examples/GltfPbr/gltf_pbr_boombox.mtlx @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/GltfPbr/gltf_pbr_carpaint.mtlx b/Materials/Examples/GltfPbr/gltf_pbr_carpaint.mtlx new file mode 100644 index 0000000000..c6ec4bba41 --- /dev/null +++ b/Materials/Examples/GltfPbr/gltf_pbr_carpaint.mtlx @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/Materials/Examples/GltfPbr/gltf_pbr_default.mtlx b/Materials/Examples/GltfPbr/gltf_pbr_default.mtlx new file mode 100644 index 0000000000..88d7031663 --- /dev/null +++ b/Materials/Examples/GltfPbr/gltf_pbr_default.mtlx @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/GltfPbr/gltf_pbr_glass.mtlx b/Materials/Examples/GltfPbr/gltf_pbr_glass.mtlx new file mode 100644 index 0000000000..3eb394c000 --- /dev/null +++ b/Materials/Examples/GltfPbr/gltf_pbr_glass.mtlx @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/Materials/Examples/GltfPbr/gltf_pbr_gold.mtlx b/Materials/Examples/GltfPbr/gltf_pbr_gold.mtlx new file mode 100644 index 0000000000..6d93c5d99e --- /dev/null +++ b/Materials/Examples/GltfPbr/gltf_pbr_gold.mtlx @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/Materials/Examples/GltfPbr/gltf_pbr_plastic.mtlx b/Materials/Examples/GltfPbr/gltf_pbr_plastic.mtlx new file mode 100644 index 0000000000..0a4c99cf83 --- /dev/null +++ b/Materials/Examples/GltfPbr/gltf_pbr_plastic.mtlx @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/Materials/Examples/OpenPbr/open_pbr_aluminum_brushed.mtlx b/Materials/Examples/OpenPbr/open_pbr_aluminum_brushed.mtlx new file mode 100644 index 0000000000..daac59d65c --- /dev/null +++ b/Materials/Examples/OpenPbr/open_pbr_aluminum_brushed.mtlx @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/Materials/Examples/OpenPbr/open_pbr_carpaint.mtlx b/Materials/Examples/OpenPbr/open_pbr_carpaint.mtlx new file mode 100644 index 0000000000..0d98dc2fee --- /dev/null +++ b/Materials/Examples/OpenPbr/open_pbr_carpaint.mtlx @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/Materials/Examples/OpenPbr/open_pbr_default.mtlx b/Materials/Examples/OpenPbr/open_pbr_default.mtlx new file mode 100644 index 0000000000..2f541d82ba --- /dev/null +++ b/Materials/Examples/OpenPbr/open_pbr_default.mtlx @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/OpenPbr/open_pbr_glass.mtlx b/Materials/Examples/OpenPbr/open_pbr_glass.mtlx new file mode 100644 index 0000000000..f2e82e8e65 --- /dev/null +++ b/Materials/Examples/OpenPbr/open_pbr_glass.mtlx @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/Materials/Examples/OpenPbr/open_pbr_honey.mtlx b/Materials/Examples/OpenPbr/open_pbr_honey.mtlx new file mode 100644 index 0000000000..aff78bee1a --- /dev/null +++ b/Materials/Examples/OpenPbr/open_pbr_honey.mtlx @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/Materials/Examples/OpenPbr/open_pbr_ketchup.mtlx b/Materials/Examples/OpenPbr/open_pbr_ketchup.mtlx new file mode 100644 index 0000000000..78e2d0a833 --- /dev/null +++ b/Materials/Examples/OpenPbr/open_pbr_ketchup.mtlx @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/Materials/Examples/OpenPbr/open_pbr_lightbulb.mtlx b/Materials/Examples/OpenPbr/open_pbr_lightbulb.mtlx new file mode 100644 index 0000000000..7e1218cffd --- /dev/null +++ b/Materials/Examples/OpenPbr/open_pbr_lightbulb.mtlx @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/Materials/Examples/OpenPbr/open_pbr_pearl.mtlx b/Materials/Examples/OpenPbr/open_pbr_pearl.mtlx new file mode 100644 index 0000000000..cc716420cb --- /dev/null +++ b/Materials/Examples/OpenPbr/open_pbr_pearl.mtlx @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/OpenPbr/open_pbr_soapbubble.mtlx b/Materials/Examples/OpenPbr/open_pbr_soapbubble.mtlx new file mode 100644 index 0000000000..7de701df4e --- /dev/null +++ b/Materials/Examples/OpenPbr/open_pbr_soapbubble.mtlx @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/Materials/Examples/OpenPbr/open_pbr_velvet.mtlx b/Materials/Examples/OpenPbr/open_pbr_velvet.mtlx new file mode 100644 index 0000000000..61c83e2ab2 --- /dev/null +++ b/Materials/Examples/OpenPbr/open_pbr_velvet.mtlx @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/Car_Paint.glsl.frag b/Materials/Examples/StandardSurface/Car_Paint.glsl.frag new file mode 100644 index 0000000000..20d0260727 --- /dev/null +++ b/Materials/Examples/StandardSurface/Car_Paint.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_carpaint_base = 0.500000; +uniform vec3 SR_carpaint_base_color = vec3(0.103779, 0.592120, 0.850649); +uniform float SR_carpaint_diffuse_roughness = 0.000000; +uniform float SR_carpaint_metalness = 0.000000; +uniform float SR_carpaint_specular = 1.000000; +uniform vec3 SR_carpaint_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_carpaint_specular_roughness = 0.400000; +uniform float SR_carpaint_specular_IOR = 1.500000; +uniform float SR_carpaint_specular_anisotropy = 0.500000; +uniform float SR_carpaint_specular_rotation = 0.000000; +uniform float SR_carpaint_transmission = 0.000000; +uniform vec3 SR_carpaint_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_carpaint_transmission_depth = 0.000000; +uniform vec3 SR_carpaint_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_carpaint_transmission_scatter_anisotropy = 0.000000; +uniform float SR_carpaint_transmission_dispersion = 0.000000; +uniform float SR_carpaint_transmission_extra_roughness = 0.000000; +uniform float SR_carpaint_subsurface = 0.000000; +uniform vec3 SR_carpaint_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_carpaint_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_carpaint_subsurface_scale = 1.000000; +uniform float SR_carpaint_subsurface_anisotropy = 0.000000; +uniform float SR_carpaint_sheen = 0.000000; +uniform vec3 SR_carpaint_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_carpaint_sheen_roughness = 0.300000; +uniform float SR_carpaint_coat = 1.000000; +uniform vec3 SR_carpaint_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_carpaint_coat_roughness = 0.000000; +uniform float SR_carpaint_coat_anisotropy = 0.000000; +uniform float SR_carpaint_coat_rotation = 0.000000; +uniform float SR_carpaint_coat_IOR = 1.500000; +uniform float SR_carpaint_coat_affect_color = 0.000000; +uniform float SR_carpaint_coat_affect_roughness = 0.000000; +uniform float SR_carpaint_thin_film_thickness = 0.000000; +uniform float SR_carpaint_thin_film_IOR = 1.500000; +uniform float SR_carpaint_emission = 0.000000; +uniform vec3 SR_carpaint_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_carpaint_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_carpaint_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_carpaint_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_carpaint_base, SR_carpaint_base_color, SR_carpaint_diffuse_roughness, SR_carpaint_metalness, SR_carpaint_specular, SR_carpaint_specular_color, SR_carpaint_specular_roughness, SR_carpaint_specular_IOR, SR_carpaint_specular_anisotropy, SR_carpaint_specular_rotation, SR_carpaint_transmission, SR_carpaint_transmission_color, SR_carpaint_transmission_depth, SR_carpaint_transmission_scatter, SR_carpaint_transmission_scatter_anisotropy, SR_carpaint_transmission_dispersion, SR_carpaint_transmission_extra_roughness, SR_carpaint_subsurface, SR_carpaint_subsurface_color, SR_carpaint_subsurface_radius, SR_carpaint_subsurface_scale, SR_carpaint_subsurface_anisotropy, SR_carpaint_sheen, SR_carpaint_sheen_color, SR_carpaint_sheen_roughness, SR_carpaint_coat, SR_carpaint_coat_color, SR_carpaint_coat_roughness, SR_carpaint_coat_anisotropy, SR_carpaint_coat_rotation, SR_carpaint_coat_IOR, geomprop_Nworld_out1, SR_carpaint_coat_affect_color, SR_carpaint_coat_affect_roughness, SR_carpaint_thin_film_thickness, SR_carpaint_thin_film_IOR, SR_carpaint_emission, SR_carpaint_emission_color, SR_carpaint_opacity, SR_carpaint_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_carpaint_out); + material Car_Paint_out = SR_carpaint_out; + out1 = vec4(Car_Paint_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Car_Paint.glsl.vert b/Materials/Examples/StandardSurface/Car_Paint.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/Car_Paint.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Car_Paint.mdl b/Materials/Examples/StandardSurface/Car_Paint.mdl new file mode 100644 index 0000000000..ea4e6907d6 --- /dev/null +++ b/Materials/Examples/StandardSurface/Car_Paint.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Car_Paint +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_carpaint_base = 0.500000 + [[ + materialx::core::origin("SR_carpaint/base") + ]], + color SR_carpaint_base_color = color(0.103779, 0.592120, 0.850649) + [[ + materialx::core::origin("SR_carpaint/base_color") + ]], + float SR_carpaint_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_carpaint/diffuse_roughness") + ]], + float SR_carpaint_metalness = 0.000000 + [[ + materialx::core::origin("SR_carpaint/metalness") + ]], + float SR_carpaint_specular = 1.000000 + [[ + materialx::core::origin("SR_carpaint/specular") + ]], + color SR_carpaint_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_carpaint/specular_color") + ]], + float SR_carpaint_specular_roughness = 0.400000 + [[ + materialx::core::origin("SR_carpaint/specular_roughness") + ]], + uniform float SR_carpaint_specular_IOR = 1.500000 + [[ + materialx::core::origin("SR_carpaint/specular_IOR") + ]], + float SR_carpaint_specular_anisotropy = 0.500000 + [[ + materialx::core::origin("SR_carpaint/specular_anisotropy") + ]], + float SR_carpaint_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_carpaint/specular_rotation") + ]], + float SR_carpaint_transmission = 0.000000 + [[ + materialx::core::origin("SR_carpaint/transmission") + ]], + color SR_carpaint_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_carpaint/transmission_color") + ]], + float SR_carpaint_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_carpaint/transmission_depth") + ]], + color SR_carpaint_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_carpaint/transmission_scatter") + ]], + float SR_carpaint_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_carpaint/transmission_scatter_anisotropy") + ]], + float SR_carpaint_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_carpaint/transmission_dispersion") + ]], + float SR_carpaint_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_carpaint/transmission_extra_roughness") + ]], + float SR_carpaint_subsurface = 0.000000 + [[ + materialx::core::origin("SR_carpaint/subsurface") + ]], + color SR_carpaint_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_carpaint/subsurface_color") + ]], + color SR_carpaint_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_carpaint/subsurface_radius") + ]], + float SR_carpaint_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_carpaint/subsurface_scale") + ]], + float SR_carpaint_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_carpaint/subsurface_anisotropy") + ]], + float SR_carpaint_sheen = 0.000000 + [[ + materialx::core::origin("SR_carpaint/sheen") + ]], + color SR_carpaint_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_carpaint/sheen_color") + ]], + float SR_carpaint_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_carpaint/sheen_roughness") + ]], + float SR_carpaint_coat = 1.000000 + [[ + materialx::core::origin("SR_carpaint/coat") + ]], + color SR_carpaint_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_carpaint/coat_color") + ]], + float SR_carpaint_coat_roughness = 0.000000 + [[ + materialx::core::origin("SR_carpaint/coat_roughness") + ]], + float SR_carpaint_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_carpaint/coat_anisotropy") + ]], + float SR_carpaint_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_carpaint/coat_rotation") + ]], + uniform float SR_carpaint_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_carpaint/coat_IOR") + ]], + float SR_carpaint_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_carpaint/coat_affect_color") + ]], + float SR_carpaint_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_carpaint/coat_affect_roughness") + ]], + float SR_carpaint_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_carpaint/thin_film_thickness") + ]], + float SR_carpaint_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_carpaint/thin_film_IOR") + ]], + float SR_carpaint_emission = 0.000000 + [[ + materialx::core::origin("SR_carpaint/emission") + ]], + color SR_carpaint_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_carpaint/emission_color") + ]], + color SR_carpaint_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_carpaint/opacity") + ]], + bool SR_carpaint_thin_walled = false + [[ + materialx::core::origin("SR_carpaint/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_carpaint_out = NG_standard_surface_surfaceshader_100(SR_carpaint_base, SR_carpaint_base_color, SR_carpaint_diffuse_roughness, SR_carpaint_metalness, SR_carpaint_specular, SR_carpaint_specular_color, SR_carpaint_specular_roughness, SR_carpaint_specular_IOR, SR_carpaint_specular_anisotropy, SR_carpaint_specular_rotation, SR_carpaint_transmission, SR_carpaint_transmission_color, SR_carpaint_transmission_depth, SR_carpaint_transmission_scatter, SR_carpaint_transmission_scatter_anisotropy, SR_carpaint_transmission_dispersion, SR_carpaint_transmission_extra_roughness, SR_carpaint_subsurface, SR_carpaint_subsurface_color, SR_carpaint_subsurface_radius, SR_carpaint_subsurface_scale, SR_carpaint_subsurface_anisotropy, SR_carpaint_sheen, SR_carpaint_sheen_color, SR_carpaint_sheen_roughness, SR_carpaint_coat, SR_carpaint_coat_color, SR_carpaint_coat_roughness, SR_carpaint_coat_anisotropy, SR_carpaint_coat_rotation, SR_carpaint_coat_IOR, geomprop_Nworld_out1, SR_carpaint_coat_affect_color, SR_carpaint_coat_affect_roughness, SR_carpaint_thin_film_thickness, SR_carpaint_thin_film_IOR, SR_carpaint_emission, SR_carpaint_emission_color, SR_carpaint_opacity, SR_carpaint_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Car_Paint_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_carpaint_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Car_Paint_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Car_Paint.msl.frag b/Materials/Examples/StandardSurface/Car_Paint.msl.frag new file mode 100644 index 0000000000..34f2a20860 --- /dev/null +++ b/Materials/Examples/StandardSurface/Car_Paint.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_carpaint_base; + vec3 SR_carpaint_base_color; + float SR_carpaint_diffuse_roughness; + float SR_carpaint_metalness; + float SR_carpaint_specular; + vec3 SR_carpaint_specular_color; + float SR_carpaint_specular_roughness; + float SR_carpaint_specular_IOR; + float SR_carpaint_specular_anisotropy; + float SR_carpaint_specular_rotation; + float SR_carpaint_transmission; + vec3 SR_carpaint_transmission_color; + float SR_carpaint_transmission_depth; + vec3 SR_carpaint_transmission_scatter; + float SR_carpaint_transmission_scatter_anisotropy; + float SR_carpaint_transmission_dispersion; + float SR_carpaint_transmission_extra_roughness; + float SR_carpaint_subsurface; + vec3 SR_carpaint_subsurface_color; + vec3 SR_carpaint_subsurface_radius; + float SR_carpaint_subsurface_scale; + float SR_carpaint_subsurface_anisotropy; + float SR_carpaint_sheen; + vec3 SR_carpaint_sheen_color; + float SR_carpaint_sheen_roughness; + float SR_carpaint_coat; + vec3 SR_carpaint_coat_color; + float SR_carpaint_coat_roughness; + float SR_carpaint_coat_anisotropy; + float SR_carpaint_coat_rotation; + float SR_carpaint_coat_IOR; + float SR_carpaint_coat_affect_color; + float SR_carpaint_coat_affect_roughness; + float SR_carpaint_thin_film_thickness; + float SR_carpaint_thin_film_IOR; + float SR_carpaint_emission; + vec3 SR_carpaint_emission_color; + vec3 SR_carpaint_opacity; + bool SR_carpaint_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_carpaint_base + + , vec3 SR_carpaint_base_color + + , float SR_carpaint_diffuse_roughness + + , float SR_carpaint_metalness + + , float SR_carpaint_specular + + , vec3 SR_carpaint_specular_color + + , float SR_carpaint_specular_roughness + + , float SR_carpaint_specular_IOR + + , float SR_carpaint_specular_anisotropy + + , float SR_carpaint_specular_rotation + + , float SR_carpaint_transmission + + , vec3 SR_carpaint_transmission_color + + , float SR_carpaint_transmission_depth + + , vec3 SR_carpaint_transmission_scatter + + , float SR_carpaint_transmission_scatter_anisotropy + + , float SR_carpaint_transmission_dispersion + + , float SR_carpaint_transmission_extra_roughness + + , float SR_carpaint_subsurface + + , vec3 SR_carpaint_subsurface_color + + , vec3 SR_carpaint_subsurface_radius + + , float SR_carpaint_subsurface_scale + + , float SR_carpaint_subsurface_anisotropy + + , float SR_carpaint_sheen + + , vec3 SR_carpaint_sheen_color + + , float SR_carpaint_sheen_roughness + + , float SR_carpaint_coat + + , vec3 SR_carpaint_coat_color + + , float SR_carpaint_coat_roughness + + , float SR_carpaint_coat_anisotropy + + , float SR_carpaint_coat_rotation + + , float SR_carpaint_coat_IOR + + , float SR_carpaint_coat_affect_color + + , float SR_carpaint_coat_affect_roughness + + , float SR_carpaint_thin_film_thickness + + , float SR_carpaint_thin_film_IOR + + , float SR_carpaint_emission + + , vec3 SR_carpaint_emission_color + + , vec3 SR_carpaint_opacity + + , bool SR_carpaint_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_carpaint_base(SR_carpaint_base) + + , SR_carpaint_base_color(SR_carpaint_base_color) + + , SR_carpaint_diffuse_roughness(SR_carpaint_diffuse_roughness) + + , SR_carpaint_metalness(SR_carpaint_metalness) + + , SR_carpaint_specular(SR_carpaint_specular) + + , SR_carpaint_specular_color(SR_carpaint_specular_color) + + , SR_carpaint_specular_roughness(SR_carpaint_specular_roughness) + + , SR_carpaint_specular_IOR(SR_carpaint_specular_IOR) + + , SR_carpaint_specular_anisotropy(SR_carpaint_specular_anisotropy) + + , SR_carpaint_specular_rotation(SR_carpaint_specular_rotation) + + , SR_carpaint_transmission(SR_carpaint_transmission) + + , SR_carpaint_transmission_color(SR_carpaint_transmission_color) + + , SR_carpaint_transmission_depth(SR_carpaint_transmission_depth) + + , SR_carpaint_transmission_scatter(SR_carpaint_transmission_scatter) + + , SR_carpaint_transmission_scatter_anisotropy(SR_carpaint_transmission_scatter_anisotropy) + + , SR_carpaint_transmission_dispersion(SR_carpaint_transmission_dispersion) + + , SR_carpaint_transmission_extra_roughness(SR_carpaint_transmission_extra_roughness) + + , SR_carpaint_subsurface(SR_carpaint_subsurface) + + , SR_carpaint_subsurface_color(SR_carpaint_subsurface_color) + + , SR_carpaint_subsurface_radius(SR_carpaint_subsurface_radius) + + , SR_carpaint_subsurface_scale(SR_carpaint_subsurface_scale) + + , SR_carpaint_subsurface_anisotropy(SR_carpaint_subsurface_anisotropy) + + , SR_carpaint_sheen(SR_carpaint_sheen) + + , SR_carpaint_sheen_color(SR_carpaint_sheen_color) + + , SR_carpaint_sheen_roughness(SR_carpaint_sheen_roughness) + + , SR_carpaint_coat(SR_carpaint_coat) + + , SR_carpaint_coat_color(SR_carpaint_coat_color) + + , SR_carpaint_coat_roughness(SR_carpaint_coat_roughness) + + , SR_carpaint_coat_anisotropy(SR_carpaint_coat_anisotropy) + + , SR_carpaint_coat_rotation(SR_carpaint_coat_rotation) + + , SR_carpaint_coat_IOR(SR_carpaint_coat_IOR) + + , SR_carpaint_coat_affect_color(SR_carpaint_coat_affect_color) + + , SR_carpaint_coat_affect_roughness(SR_carpaint_coat_affect_roughness) + + , SR_carpaint_thin_film_thickness(SR_carpaint_thin_film_thickness) + + , SR_carpaint_thin_film_IOR(SR_carpaint_thin_film_IOR) + + , SR_carpaint_emission(SR_carpaint_emission) + + , SR_carpaint_emission_color(SR_carpaint_emission_color) + + , SR_carpaint_opacity(SR_carpaint_opacity) + + , SR_carpaint_thin_walled(SR_carpaint_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_carpaint_base; + + + vec3 SR_carpaint_base_color; + + + float SR_carpaint_diffuse_roughness; + + + float SR_carpaint_metalness; + + + float SR_carpaint_specular; + + + vec3 SR_carpaint_specular_color; + + + float SR_carpaint_specular_roughness; + + + float SR_carpaint_specular_IOR; + + + float SR_carpaint_specular_anisotropy; + + + float SR_carpaint_specular_rotation; + + + float SR_carpaint_transmission; + + + vec3 SR_carpaint_transmission_color; + + + float SR_carpaint_transmission_depth; + + + vec3 SR_carpaint_transmission_scatter; + + + float SR_carpaint_transmission_scatter_anisotropy; + + + float SR_carpaint_transmission_dispersion; + + + float SR_carpaint_transmission_extra_roughness; + + + float SR_carpaint_subsurface; + + + vec3 SR_carpaint_subsurface_color; + + + vec3 SR_carpaint_subsurface_radius; + + + float SR_carpaint_subsurface_scale; + + + float SR_carpaint_subsurface_anisotropy; + + + float SR_carpaint_sheen; + + + vec3 SR_carpaint_sheen_color; + + + float SR_carpaint_sheen_roughness; + + + float SR_carpaint_coat; + + + vec3 SR_carpaint_coat_color; + + + float SR_carpaint_coat_roughness; + + + float SR_carpaint_coat_anisotropy; + + + float SR_carpaint_coat_rotation; + + + float SR_carpaint_coat_IOR; + + + float SR_carpaint_coat_affect_color; + + + float SR_carpaint_coat_affect_roughness; + + + float SR_carpaint_thin_film_thickness; + + + float SR_carpaint_thin_film_IOR; + + + float SR_carpaint_emission; + + + vec3 SR_carpaint_emission_color; + + + vec3 SR_carpaint_opacity; + + + bool SR_carpaint_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_carpaint_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_carpaint_base, SR_carpaint_base_color, SR_carpaint_diffuse_roughness, SR_carpaint_metalness, SR_carpaint_specular, SR_carpaint_specular_color, SR_carpaint_specular_roughness, SR_carpaint_specular_IOR, SR_carpaint_specular_anisotropy, SR_carpaint_specular_rotation, SR_carpaint_transmission, SR_carpaint_transmission_color, SR_carpaint_transmission_depth, SR_carpaint_transmission_scatter, SR_carpaint_transmission_scatter_anisotropy, SR_carpaint_transmission_dispersion, SR_carpaint_transmission_extra_roughness, SR_carpaint_subsurface, SR_carpaint_subsurface_color, SR_carpaint_subsurface_radius, SR_carpaint_subsurface_scale, SR_carpaint_subsurface_anisotropy, SR_carpaint_sheen, SR_carpaint_sheen_color, SR_carpaint_sheen_roughness, SR_carpaint_coat, SR_carpaint_coat_color, SR_carpaint_coat_roughness, SR_carpaint_coat_anisotropy, SR_carpaint_coat_rotation, SR_carpaint_coat_IOR, geomprop_Nworld_out1, SR_carpaint_coat_affect_color, SR_carpaint_coat_affect_roughness, SR_carpaint_thin_film_thickness, SR_carpaint_thin_film_IOR, SR_carpaint_emission, SR_carpaint_emission_color, SR_carpaint_opacity, SR_carpaint_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_carpaint_out); + material Car_Paint_out = SR_carpaint_out; + out1 = float4(Car_Paint_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_carpaint_base + , u_pub.SR_carpaint_base_color + , u_pub.SR_carpaint_diffuse_roughness + , u_pub.SR_carpaint_metalness + , u_pub.SR_carpaint_specular + , u_pub.SR_carpaint_specular_color + , u_pub.SR_carpaint_specular_roughness + , u_pub.SR_carpaint_specular_IOR + , u_pub.SR_carpaint_specular_anisotropy + , u_pub.SR_carpaint_specular_rotation + , u_pub.SR_carpaint_transmission + , u_pub.SR_carpaint_transmission_color + , u_pub.SR_carpaint_transmission_depth + , u_pub.SR_carpaint_transmission_scatter + , u_pub.SR_carpaint_transmission_scatter_anisotropy + , u_pub.SR_carpaint_transmission_dispersion + , u_pub.SR_carpaint_transmission_extra_roughness + , u_pub.SR_carpaint_subsurface + , u_pub.SR_carpaint_subsurface_color + , u_pub.SR_carpaint_subsurface_radius + , u_pub.SR_carpaint_subsurface_scale + , u_pub.SR_carpaint_subsurface_anisotropy + , u_pub.SR_carpaint_sheen + , u_pub.SR_carpaint_sheen_color + , u_pub.SR_carpaint_sheen_roughness + , u_pub.SR_carpaint_coat + , u_pub.SR_carpaint_coat_color + , u_pub.SR_carpaint_coat_roughness + , u_pub.SR_carpaint_coat_anisotropy + , u_pub.SR_carpaint_coat_rotation + , u_pub.SR_carpaint_coat_IOR + , u_pub.SR_carpaint_coat_affect_color + , u_pub.SR_carpaint_coat_affect_roughness + , u_pub.SR_carpaint_thin_film_thickness + , u_pub.SR_carpaint_thin_film_IOR + , u_pub.SR_carpaint_emission + , u_pub.SR_carpaint_emission_color + , u_pub.SR_carpaint_opacity + , u_pub.SR_carpaint_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Car_Paint.msl.vert b/Materials/Examples/StandardSurface/Car_Paint.msl.vert new file mode 100644 index 0000000000..5c5cb181cd --- /dev/null +++ b/Materials/Examples/StandardSurface/Car_Paint.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_carpaint'. Function already called in this scope. + // Omitted node 'Car_Paint'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Car_Paint.osl b/Materials/Examples/StandardSurface/Car_Paint.osl new file mode 100644 index 0000000000..53be2ff87b --- /dev/null +++ b/Materials/Examples/StandardSurface/Car_Paint.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Car_Paint +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Car_Paint" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_carpaint_base = 0.500000 + [[ + string widget = "number" + ]], + color SR_carpaint_base_color = color(0.103779, 0.592120, 0.850649), + float SR_carpaint_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_metalness = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_specular = 1.000000 + [[ + string widget = "number" + ]], + color SR_carpaint_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_carpaint_specular_roughness = 0.400000 + [[ + string widget = "number" + ]], + float SR_carpaint_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_carpaint_specular_anisotropy = 0.500000 + [[ + string widget = "number" + ]], + float SR_carpaint_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_carpaint_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_carpaint_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_carpaint_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_carpaint_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_carpaint_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_carpaint_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_carpaint_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_carpaint_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_carpaint_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_carpaint_coat = 1.000000 + [[ + string widget = "number" + ]], + color SR_carpaint_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_carpaint_coat_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_carpaint_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_carpaint_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_carpaint_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_carpaint_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_carpaint_opacity = color(1.000000, 1.000000, 1.000000), + int SR_carpaint_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_carpaint_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_carpaint_base, SR_carpaint_base_color, SR_carpaint_diffuse_roughness, SR_carpaint_metalness, SR_carpaint_specular, SR_carpaint_specular_color, SR_carpaint_specular_roughness, SR_carpaint_specular_IOR, SR_carpaint_specular_anisotropy, SR_carpaint_specular_rotation, SR_carpaint_transmission, SR_carpaint_transmission_color, SR_carpaint_transmission_depth, SR_carpaint_transmission_scatter, SR_carpaint_transmission_scatter_anisotropy, SR_carpaint_transmission_dispersion, SR_carpaint_transmission_extra_roughness, SR_carpaint_subsurface, SR_carpaint_subsurface_color, SR_carpaint_subsurface_radius, SR_carpaint_subsurface_scale, SR_carpaint_subsurface_anisotropy, SR_carpaint_sheen, SR_carpaint_sheen_color, SR_carpaint_sheen_roughness, SR_carpaint_coat, SR_carpaint_coat_color, SR_carpaint_coat_roughness, SR_carpaint_coat_anisotropy, SR_carpaint_coat_rotation, SR_carpaint_coat_IOR, geomprop_Nworld_out1, SR_carpaint_coat_affect_color, SR_carpaint_coat_affect_roughness, SR_carpaint_thin_film_thickness, SR_carpaint_thin_film_IOR, SR_carpaint_emission, SR_carpaint_emission_color, SR_carpaint_opacity, SR_carpaint_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_carpaint_out); + MATERIAL Car_Paint_out = mx_surfacematerial(SR_carpaint_out, backsurfaceshader, displacementshader1); + out = Car_Paint_out; +} + diff --git a/Materials/Examples/StandardSurface/Chrome.glsl.frag b/Materials/Examples/StandardSurface/Chrome.glsl.frag new file mode 100644 index 0000000000..344f4463b8 --- /dev/null +++ b/Materials/Examples/StandardSurface/Chrome.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_chrome_base = 1.000000; +uniform vec3 SR_chrome_base_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_chrome_diffuse_roughness = 0.000000; +uniform float SR_chrome_metalness = 1.000000; +uniform float SR_chrome_specular = 1.000000; +uniform vec3 SR_chrome_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_chrome_specular_roughness = 0.000000; +uniform float SR_chrome_specular_IOR = 1.500000; +uniform float SR_chrome_specular_anisotropy = 0.000000; +uniform float SR_chrome_specular_rotation = 0.000000; +uniform float SR_chrome_transmission = 0.000000; +uniform vec3 SR_chrome_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_chrome_transmission_depth = 0.000000; +uniform vec3 SR_chrome_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_chrome_transmission_scatter_anisotropy = 0.000000; +uniform float SR_chrome_transmission_dispersion = 0.000000; +uniform float SR_chrome_transmission_extra_roughness = 0.000000; +uniform float SR_chrome_subsurface = 0.000000; +uniform vec3 SR_chrome_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_chrome_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_chrome_subsurface_scale = 1.000000; +uniform float SR_chrome_subsurface_anisotropy = 0.000000; +uniform float SR_chrome_sheen = 0.000000; +uniform vec3 SR_chrome_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_chrome_sheen_roughness = 0.300000; +uniform float SR_chrome_coat = 0.000000; +uniform vec3 SR_chrome_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_chrome_coat_roughness = 0.100000; +uniform float SR_chrome_coat_anisotropy = 0.000000; +uniform float SR_chrome_coat_rotation = 0.000000; +uniform float SR_chrome_coat_IOR = 1.500000; +uniform float SR_chrome_coat_affect_color = 0.000000; +uniform float SR_chrome_coat_affect_roughness = 0.000000; +uniform float SR_chrome_thin_film_thickness = 0.000000; +uniform float SR_chrome_thin_film_IOR = 1.500000; +uniform float SR_chrome_emission = 0.000000; +uniform vec3 SR_chrome_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_chrome_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_chrome_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_chrome_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_chrome_base, SR_chrome_base_color, SR_chrome_diffuse_roughness, SR_chrome_metalness, SR_chrome_specular, SR_chrome_specular_color, SR_chrome_specular_roughness, SR_chrome_specular_IOR, SR_chrome_specular_anisotropy, SR_chrome_specular_rotation, SR_chrome_transmission, SR_chrome_transmission_color, SR_chrome_transmission_depth, SR_chrome_transmission_scatter, SR_chrome_transmission_scatter_anisotropy, SR_chrome_transmission_dispersion, SR_chrome_transmission_extra_roughness, SR_chrome_subsurface, SR_chrome_subsurface_color, SR_chrome_subsurface_radius, SR_chrome_subsurface_scale, SR_chrome_subsurface_anisotropy, SR_chrome_sheen, SR_chrome_sheen_color, SR_chrome_sheen_roughness, SR_chrome_coat, SR_chrome_coat_color, SR_chrome_coat_roughness, SR_chrome_coat_anisotropy, SR_chrome_coat_rotation, SR_chrome_coat_IOR, geomprop_Nworld_out1, SR_chrome_coat_affect_color, SR_chrome_coat_affect_roughness, SR_chrome_thin_film_thickness, SR_chrome_thin_film_IOR, SR_chrome_emission, SR_chrome_emission_color, SR_chrome_opacity, SR_chrome_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_chrome_out); + material Chrome_out = SR_chrome_out; + out1 = vec4(Chrome_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Chrome.glsl.vert b/Materials/Examples/StandardSurface/Chrome.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/Chrome.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Chrome.mdl b/Materials/Examples/StandardSurface/Chrome.mdl new file mode 100644 index 0000000000..e2555aba8d --- /dev/null +++ b/Materials/Examples/StandardSurface/Chrome.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Chrome +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_chrome_base = 1.000000 + [[ + materialx::core::origin("SR_chrome/base") + ]], + color SR_chrome_base_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_chrome/base_color") + ]], + float SR_chrome_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_chrome/diffuse_roughness") + ]], + float SR_chrome_metalness = 1.000000 + [[ + materialx::core::origin("SR_chrome/metalness") + ]], + float SR_chrome_specular = 1.000000 + [[ + materialx::core::origin("SR_chrome/specular") + ]], + color SR_chrome_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_chrome/specular_color") + ]], + float SR_chrome_specular_roughness = 0.000000 + [[ + materialx::core::origin("SR_chrome/specular_roughness") + ]], + uniform float SR_chrome_specular_IOR = 1.500000 + [[ + materialx::core::origin("SR_chrome/specular_IOR") + ]], + float SR_chrome_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_chrome/specular_anisotropy") + ]], + float SR_chrome_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_chrome/specular_rotation") + ]], + float SR_chrome_transmission = 0.000000 + [[ + materialx::core::origin("SR_chrome/transmission") + ]], + color SR_chrome_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_chrome/transmission_color") + ]], + float SR_chrome_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_chrome/transmission_depth") + ]], + color SR_chrome_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_chrome/transmission_scatter") + ]], + float SR_chrome_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_chrome/transmission_scatter_anisotropy") + ]], + float SR_chrome_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_chrome/transmission_dispersion") + ]], + float SR_chrome_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_chrome/transmission_extra_roughness") + ]], + float SR_chrome_subsurface = 0.000000 + [[ + materialx::core::origin("SR_chrome/subsurface") + ]], + color SR_chrome_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_chrome/subsurface_color") + ]], + color SR_chrome_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_chrome/subsurface_radius") + ]], + float SR_chrome_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_chrome/subsurface_scale") + ]], + float SR_chrome_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_chrome/subsurface_anisotropy") + ]], + float SR_chrome_sheen = 0.000000 + [[ + materialx::core::origin("SR_chrome/sheen") + ]], + color SR_chrome_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_chrome/sheen_color") + ]], + float SR_chrome_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_chrome/sheen_roughness") + ]], + float SR_chrome_coat = 0.000000 + [[ + materialx::core::origin("SR_chrome/coat") + ]], + color SR_chrome_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_chrome/coat_color") + ]], + float SR_chrome_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_chrome/coat_roughness") + ]], + float SR_chrome_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_chrome/coat_anisotropy") + ]], + float SR_chrome_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_chrome/coat_rotation") + ]], + uniform float SR_chrome_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_chrome/coat_IOR") + ]], + float SR_chrome_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_chrome/coat_affect_color") + ]], + float SR_chrome_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_chrome/coat_affect_roughness") + ]], + float SR_chrome_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_chrome/thin_film_thickness") + ]], + float SR_chrome_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_chrome/thin_film_IOR") + ]], + float SR_chrome_emission = 0.000000 + [[ + materialx::core::origin("SR_chrome/emission") + ]], + color SR_chrome_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_chrome/emission_color") + ]], + color SR_chrome_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_chrome/opacity") + ]], + bool SR_chrome_thin_walled = false + [[ + materialx::core::origin("SR_chrome/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_chrome_out = NG_standard_surface_surfaceshader_100(SR_chrome_base, SR_chrome_base_color, SR_chrome_diffuse_roughness, SR_chrome_metalness, SR_chrome_specular, SR_chrome_specular_color, SR_chrome_specular_roughness, SR_chrome_specular_IOR, SR_chrome_specular_anisotropy, SR_chrome_specular_rotation, SR_chrome_transmission, SR_chrome_transmission_color, SR_chrome_transmission_depth, SR_chrome_transmission_scatter, SR_chrome_transmission_scatter_anisotropy, SR_chrome_transmission_dispersion, SR_chrome_transmission_extra_roughness, SR_chrome_subsurface, SR_chrome_subsurface_color, SR_chrome_subsurface_radius, SR_chrome_subsurface_scale, SR_chrome_subsurface_anisotropy, SR_chrome_sheen, SR_chrome_sheen_color, SR_chrome_sheen_roughness, SR_chrome_coat, SR_chrome_coat_color, SR_chrome_coat_roughness, SR_chrome_coat_anisotropy, SR_chrome_coat_rotation, SR_chrome_coat_IOR, geomprop_Nworld_out1, SR_chrome_coat_affect_color, SR_chrome_coat_affect_roughness, SR_chrome_thin_film_thickness, SR_chrome_thin_film_IOR, SR_chrome_emission, SR_chrome_emission_color, SR_chrome_opacity, SR_chrome_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Chrome_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_chrome_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Chrome_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Chrome.msl.frag b/Materials/Examples/StandardSurface/Chrome.msl.frag new file mode 100644 index 0000000000..8694ae7cf2 --- /dev/null +++ b/Materials/Examples/StandardSurface/Chrome.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_chrome_base; + vec3 SR_chrome_base_color; + float SR_chrome_diffuse_roughness; + float SR_chrome_metalness; + float SR_chrome_specular; + vec3 SR_chrome_specular_color; + float SR_chrome_specular_roughness; + float SR_chrome_specular_IOR; + float SR_chrome_specular_anisotropy; + float SR_chrome_specular_rotation; + float SR_chrome_transmission; + vec3 SR_chrome_transmission_color; + float SR_chrome_transmission_depth; + vec3 SR_chrome_transmission_scatter; + float SR_chrome_transmission_scatter_anisotropy; + float SR_chrome_transmission_dispersion; + float SR_chrome_transmission_extra_roughness; + float SR_chrome_subsurface; + vec3 SR_chrome_subsurface_color; + vec3 SR_chrome_subsurface_radius; + float SR_chrome_subsurface_scale; + float SR_chrome_subsurface_anisotropy; + float SR_chrome_sheen; + vec3 SR_chrome_sheen_color; + float SR_chrome_sheen_roughness; + float SR_chrome_coat; + vec3 SR_chrome_coat_color; + float SR_chrome_coat_roughness; + float SR_chrome_coat_anisotropy; + float SR_chrome_coat_rotation; + float SR_chrome_coat_IOR; + float SR_chrome_coat_affect_color; + float SR_chrome_coat_affect_roughness; + float SR_chrome_thin_film_thickness; + float SR_chrome_thin_film_IOR; + float SR_chrome_emission; + vec3 SR_chrome_emission_color; + vec3 SR_chrome_opacity; + bool SR_chrome_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_chrome_base + + , vec3 SR_chrome_base_color + + , float SR_chrome_diffuse_roughness + + , float SR_chrome_metalness + + , float SR_chrome_specular + + , vec3 SR_chrome_specular_color + + , float SR_chrome_specular_roughness + + , float SR_chrome_specular_IOR + + , float SR_chrome_specular_anisotropy + + , float SR_chrome_specular_rotation + + , float SR_chrome_transmission + + , vec3 SR_chrome_transmission_color + + , float SR_chrome_transmission_depth + + , vec3 SR_chrome_transmission_scatter + + , float SR_chrome_transmission_scatter_anisotropy + + , float SR_chrome_transmission_dispersion + + , float SR_chrome_transmission_extra_roughness + + , float SR_chrome_subsurface + + , vec3 SR_chrome_subsurface_color + + , vec3 SR_chrome_subsurface_radius + + , float SR_chrome_subsurface_scale + + , float SR_chrome_subsurface_anisotropy + + , float SR_chrome_sheen + + , vec3 SR_chrome_sheen_color + + , float SR_chrome_sheen_roughness + + , float SR_chrome_coat + + , vec3 SR_chrome_coat_color + + , float SR_chrome_coat_roughness + + , float SR_chrome_coat_anisotropy + + , float SR_chrome_coat_rotation + + , float SR_chrome_coat_IOR + + , float SR_chrome_coat_affect_color + + , float SR_chrome_coat_affect_roughness + + , float SR_chrome_thin_film_thickness + + , float SR_chrome_thin_film_IOR + + , float SR_chrome_emission + + , vec3 SR_chrome_emission_color + + , vec3 SR_chrome_opacity + + , bool SR_chrome_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_chrome_base(SR_chrome_base) + + , SR_chrome_base_color(SR_chrome_base_color) + + , SR_chrome_diffuse_roughness(SR_chrome_diffuse_roughness) + + , SR_chrome_metalness(SR_chrome_metalness) + + , SR_chrome_specular(SR_chrome_specular) + + , SR_chrome_specular_color(SR_chrome_specular_color) + + , SR_chrome_specular_roughness(SR_chrome_specular_roughness) + + , SR_chrome_specular_IOR(SR_chrome_specular_IOR) + + , SR_chrome_specular_anisotropy(SR_chrome_specular_anisotropy) + + , SR_chrome_specular_rotation(SR_chrome_specular_rotation) + + , SR_chrome_transmission(SR_chrome_transmission) + + , SR_chrome_transmission_color(SR_chrome_transmission_color) + + , SR_chrome_transmission_depth(SR_chrome_transmission_depth) + + , SR_chrome_transmission_scatter(SR_chrome_transmission_scatter) + + , SR_chrome_transmission_scatter_anisotropy(SR_chrome_transmission_scatter_anisotropy) + + , SR_chrome_transmission_dispersion(SR_chrome_transmission_dispersion) + + , SR_chrome_transmission_extra_roughness(SR_chrome_transmission_extra_roughness) + + , SR_chrome_subsurface(SR_chrome_subsurface) + + , SR_chrome_subsurface_color(SR_chrome_subsurface_color) + + , SR_chrome_subsurface_radius(SR_chrome_subsurface_radius) + + , SR_chrome_subsurface_scale(SR_chrome_subsurface_scale) + + , SR_chrome_subsurface_anisotropy(SR_chrome_subsurface_anisotropy) + + , SR_chrome_sheen(SR_chrome_sheen) + + , SR_chrome_sheen_color(SR_chrome_sheen_color) + + , SR_chrome_sheen_roughness(SR_chrome_sheen_roughness) + + , SR_chrome_coat(SR_chrome_coat) + + , SR_chrome_coat_color(SR_chrome_coat_color) + + , SR_chrome_coat_roughness(SR_chrome_coat_roughness) + + , SR_chrome_coat_anisotropy(SR_chrome_coat_anisotropy) + + , SR_chrome_coat_rotation(SR_chrome_coat_rotation) + + , SR_chrome_coat_IOR(SR_chrome_coat_IOR) + + , SR_chrome_coat_affect_color(SR_chrome_coat_affect_color) + + , SR_chrome_coat_affect_roughness(SR_chrome_coat_affect_roughness) + + , SR_chrome_thin_film_thickness(SR_chrome_thin_film_thickness) + + , SR_chrome_thin_film_IOR(SR_chrome_thin_film_IOR) + + , SR_chrome_emission(SR_chrome_emission) + + , SR_chrome_emission_color(SR_chrome_emission_color) + + , SR_chrome_opacity(SR_chrome_opacity) + + , SR_chrome_thin_walled(SR_chrome_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_chrome_base; + + + vec3 SR_chrome_base_color; + + + float SR_chrome_diffuse_roughness; + + + float SR_chrome_metalness; + + + float SR_chrome_specular; + + + vec3 SR_chrome_specular_color; + + + float SR_chrome_specular_roughness; + + + float SR_chrome_specular_IOR; + + + float SR_chrome_specular_anisotropy; + + + float SR_chrome_specular_rotation; + + + float SR_chrome_transmission; + + + vec3 SR_chrome_transmission_color; + + + float SR_chrome_transmission_depth; + + + vec3 SR_chrome_transmission_scatter; + + + float SR_chrome_transmission_scatter_anisotropy; + + + float SR_chrome_transmission_dispersion; + + + float SR_chrome_transmission_extra_roughness; + + + float SR_chrome_subsurface; + + + vec3 SR_chrome_subsurface_color; + + + vec3 SR_chrome_subsurface_radius; + + + float SR_chrome_subsurface_scale; + + + float SR_chrome_subsurface_anisotropy; + + + float SR_chrome_sheen; + + + vec3 SR_chrome_sheen_color; + + + float SR_chrome_sheen_roughness; + + + float SR_chrome_coat; + + + vec3 SR_chrome_coat_color; + + + float SR_chrome_coat_roughness; + + + float SR_chrome_coat_anisotropy; + + + float SR_chrome_coat_rotation; + + + float SR_chrome_coat_IOR; + + + float SR_chrome_coat_affect_color; + + + float SR_chrome_coat_affect_roughness; + + + float SR_chrome_thin_film_thickness; + + + float SR_chrome_thin_film_IOR; + + + float SR_chrome_emission; + + + vec3 SR_chrome_emission_color; + + + vec3 SR_chrome_opacity; + + + bool SR_chrome_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_chrome_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_chrome_base, SR_chrome_base_color, SR_chrome_diffuse_roughness, SR_chrome_metalness, SR_chrome_specular, SR_chrome_specular_color, SR_chrome_specular_roughness, SR_chrome_specular_IOR, SR_chrome_specular_anisotropy, SR_chrome_specular_rotation, SR_chrome_transmission, SR_chrome_transmission_color, SR_chrome_transmission_depth, SR_chrome_transmission_scatter, SR_chrome_transmission_scatter_anisotropy, SR_chrome_transmission_dispersion, SR_chrome_transmission_extra_roughness, SR_chrome_subsurface, SR_chrome_subsurface_color, SR_chrome_subsurface_radius, SR_chrome_subsurface_scale, SR_chrome_subsurface_anisotropy, SR_chrome_sheen, SR_chrome_sheen_color, SR_chrome_sheen_roughness, SR_chrome_coat, SR_chrome_coat_color, SR_chrome_coat_roughness, SR_chrome_coat_anisotropy, SR_chrome_coat_rotation, SR_chrome_coat_IOR, geomprop_Nworld_out1, SR_chrome_coat_affect_color, SR_chrome_coat_affect_roughness, SR_chrome_thin_film_thickness, SR_chrome_thin_film_IOR, SR_chrome_emission, SR_chrome_emission_color, SR_chrome_opacity, SR_chrome_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_chrome_out); + material Chrome_out = SR_chrome_out; + out1 = float4(Chrome_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_chrome_base + , u_pub.SR_chrome_base_color + , u_pub.SR_chrome_diffuse_roughness + , u_pub.SR_chrome_metalness + , u_pub.SR_chrome_specular + , u_pub.SR_chrome_specular_color + , u_pub.SR_chrome_specular_roughness + , u_pub.SR_chrome_specular_IOR + , u_pub.SR_chrome_specular_anisotropy + , u_pub.SR_chrome_specular_rotation + , u_pub.SR_chrome_transmission + , u_pub.SR_chrome_transmission_color + , u_pub.SR_chrome_transmission_depth + , u_pub.SR_chrome_transmission_scatter + , u_pub.SR_chrome_transmission_scatter_anisotropy + , u_pub.SR_chrome_transmission_dispersion + , u_pub.SR_chrome_transmission_extra_roughness + , u_pub.SR_chrome_subsurface + , u_pub.SR_chrome_subsurface_color + , u_pub.SR_chrome_subsurface_radius + , u_pub.SR_chrome_subsurface_scale + , u_pub.SR_chrome_subsurface_anisotropy + , u_pub.SR_chrome_sheen + , u_pub.SR_chrome_sheen_color + , u_pub.SR_chrome_sheen_roughness + , u_pub.SR_chrome_coat + , u_pub.SR_chrome_coat_color + , u_pub.SR_chrome_coat_roughness + , u_pub.SR_chrome_coat_anisotropy + , u_pub.SR_chrome_coat_rotation + , u_pub.SR_chrome_coat_IOR + , u_pub.SR_chrome_coat_affect_color + , u_pub.SR_chrome_coat_affect_roughness + , u_pub.SR_chrome_thin_film_thickness + , u_pub.SR_chrome_thin_film_IOR + , u_pub.SR_chrome_emission + , u_pub.SR_chrome_emission_color + , u_pub.SR_chrome_opacity + , u_pub.SR_chrome_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Chrome.msl.vert b/Materials/Examples/StandardSurface/Chrome.msl.vert new file mode 100644 index 0000000000..4ca40c4b7f --- /dev/null +++ b/Materials/Examples/StandardSurface/Chrome.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_chrome'. Function already called in this scope. + // Omitted node 'Chrome'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Chrome.osl b/Materials/Examples/StandardSurface/Chrome.osl new file mode 100644 index 0000000000..7f5e14c4c7 --- /dev/null +++ b/Materials/Examples/StandardSurface/Chrome.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Chrome +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Chrome" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_chrome_base = 1.000000 + [[ + string widget = "number" + ]], + color SR_chrome_base_color = color(1.000000, 1.000000, 1.000000), + float SR_chrome_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_metalness = 1.000000 + [[ + string widget = "number" + ]], + float SR_chrome_specular = 1.000000 + [[ + string widget = "number" + ]], + color SR_chrome_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_chrome_specular_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_chrome_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_chrome_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_chrome_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_chrome_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_chrome_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_chrome_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_chrome_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_chrome_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_chrome_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_chrome_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_chrome_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_chrome_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_chrome_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_chrome_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_chrome_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_chrome_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_chrome_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_chrome_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_chrome_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_chrome_opacity = color(1.000000, 1.000000, 1.000000), + int SR_chrome_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_chrome_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_chrome_base, SR_chrome_base_color, SR_chrome_diffuse_roughness, SR_chrome_metalness, SR_chrome_specular, SR_chrome_specular_color, SR_chrome_specular_roughness, SR_chrome_specular_IOR, SR_chrome_specular_anisotropy, SR_chrome_specular_rotation, SR_chrome_transmission, SR_chrome_transmission_color, SR_chrome_transmission_depth, SR_chrome_transmission_scatter, SR_chrome_transmission_scatter_anisotropy, SR_chrome_transmission_dispersion, SR_chrome_transmission_extra_roughness, SR_chrome_subsurface, SR_chrome_subsurface_color, SR_chrome_subsurface_radius, SR_chrome_subsurface_scale, SR_chrome_subsurface_anisotropy, SR_chrome_sheen, SR_chrome_sheen_color, SR_chrome_sheen_roughness, SR_chrome_coat, SR_chrome_coat_color, SR_chrome_coat_roughness, SR_chrome_coat_anisotropy, SR_chrome_coat_rotation, SR_chrome_coat_IOR, geomprop_Nworld_out1, SR_chrome_coat_affect_color, SR_chrome_coat_affect_roughness, SR_chrome_thin_film_thickness, SR_chrome_thin_film_IOR, SR_chrome_emission, SR_chrome_emission_color, SR_chrome_opacity, SR_chrome_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_chrome_out); + MATERIAL Chrome_out = mx_surfacematerial(SR_chrome_out, backsurfaceshader, displacementshader1); + out = Chrome_out; +} + diff --git a/Materials/Examples/StandardSurface/Copper.glsl.frag b/Materials/Examples/StandardSurface/Copper.glsl.frag new file mode 100644 index 0000000000..d2976a0488 --- /dev/null +++ b/Materials/Examples/StandardSurface/Copper.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_copper_base = 1.000000; +uniform vec3 SR_copper_base_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_copper_diffuse_roughness = 0.000000; +uniform float SR_copper_metalness = 1.000000; +uniform float SR_copper_specular = 0.000000; +uniform vec3 SR_copper_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_copper_specular_roughness = 0.250000; +uniform float SR_copper_specular_IOR = 1.500000; +uniform float SR_copper_specular_anisotropy = 0.000000; +uniform float SR_copper_specular_rotation = 0.000000; +uniform float SR_copper_transmission = 0.000000; +uniform vec3 SR_copper_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_copper_transmission_depth = 0.000000; +uniform vec3 SR_copper_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_copper_transmission_scatter_anisotropy = 0.000000; +uniform float SR_copper_transmission_dispersion = 0.000000; +uniform float SR_copper_transmission_extra_roughness = 0.000000; +uniform float SR_copper_subsurface = 0.000000; +uniform vec3 SR_copper_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_copper_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_copper_subsurface_scale = 1.000000; +uniform float SR_copper_subsurface_anisotropy = 0.000000; +uniform float SR_copper_sheen = 0.000000; +uniform vec3 SR_copper_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_copper_sheen_roughness = 0.300000; +uniform float SR_copper_coat = 1.000000; +uniform vec3 SR_copper_coat_color = vec3(0.964680, 0.376263, 0.258183); +uniform float SR_copper_coat_roughness = 0.200000; +uniform float SR_copper_coat_anisotropy = 0.000000; +uniform float SR_copper_coat_rotation = 0.000000; +uniform float SR_copper_coat_IOR = 1.500000; +uniform float SR_copper_coat_affect_color = 0.000000; +uniform float SR_copper_coat_affect_roughness = 0.000000; +uniform float SR_copper_thin_film_thickness = 0.000000; +uniform float SR_copper_thin_film_IOR = 1.500000; +uniform float SR_copper_emission = 0.000000; +uniform vec3 SR_copper_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_copper_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_copper_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_copper_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_copper_base, SR_copper_base_color, SR_copper_diffuse_roughness, SR_copper_metalness, SR_copper_specular, SR_copper_specular_color, SR_copper_specular_roughness, SR_copper_specular_IOR, SR_copper_specular_anisotropy, SR_copper_specular_rotation, SR_copper_transmission, SR_copper_transmission_color, SR_copper_transmission_depth, SR_copper_transmission_scatter, SR_copper_transmission_scatter_anisotropy, SR_copper_transmission_dispersion, SR_copper_transmission_extra_roughness, SR_copper_subsurface, SR_copper_subsurface_color, SR_copper_subsurface_radius, SR_copper_subsurface_scale, SR_copper_subsurface_anisotropy, SR_copper_sheen, SR_copper_sheen_color, SR_copper_sheen_roughness, SR_copper_coat, SR_copper_coat_color, SR_copper_coat_roughness, SR_copper_coat_anisotropy, SR_copper_coat_rotation, SR_copper_coat_IOR, geomprop_Nworld_out1, SR_copper_coat_affect_color, SR_copper_coat_affect_roughness, SR_copper_thin_film_thickness, SR_copper_thin_film_IOR, SR_copper_emission, SR_copper_emission_color, SR_copper_opacity, SR_copper_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_copper_out); + material Copper_out = SR_copper_out; + out1 = vec4(Copper_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Copper.glsl.vert b/Materials/Examples/StandardSurface/Copper.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/Copper.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Copper.mdl b/Materials/Examples/StandardSurface/Copper.mdl new file mode 100644 index 0000000000..0265614fe5 --- /dev/null +++ b/Materials/Examples/StandardSurface/Copper.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Copper +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_copper_base = 1.000000 + [[ + materialx::core::origin("SR_copper/base") + ]], + color SR_copper_base_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_copper/base_color") + ]], + float SR_copper_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_copper/diffuse_roughness") + ]], + float SR_copper_metalness = 1.000000 + [[ + materialx::core::origin("SR_copper/metalness") + ]], + float SR_copper_specular = 0.000000 + [[ + materialx::core::origin("SR_copper/specular") + ]], + color SR_copper_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_copper/specular_color") + ]], + float SR_copper_specular_roughness = 0.250000 + [[ + materialx::core::origin("SR_copper/specular_roughness") + ]], + uniform float SR_copper_specular_IOR = 1.500000 + [[ + materialx::core::origin("SR_copper/specular_IOR") + ]], + float SR_copper_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_copper/specular_anisotropy") + ]], + float SR_copper_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_copper/specular_rotation") + ]], + float SR_copper_transmission = 0.000000 + [[ + materialx::core::origin("SR_copper/transmission") + ]], + color SR_copper_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_copper/transmission_color") + ]], + float SR_copper_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_copper/transmission_depth") + ]], + color SR_copper_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_copper/transmission_scatter") + ]], + float SR_copper_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_copper/transmission_scatter_anisotropy") + ]], + float SR_copper_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_copper/transmission_dispersion") + ]], + float SR_copper_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_copper/transmission_extra_roughness") + ]], + float SR_copper_subsurface = 0.000000 + [[ + materialx::core::origin("SR_copper/subsurface") + ]], + color SR_copper_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_copper/subsurface_color") + ]], + color SR_copper_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_copper/subsurface_radius") + ]], + float SR_copper_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_copper/subsurface_scale") + ]], + float SR_copper_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_copper/subsurface_anisotropy") + ]], + float SR_copper_sheen = 0.000000 + [[ + materialx::core::origin("SR_copper/sheen") + ]], + color SR_copper_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_copper/sheen_color") + ]], + float SR_copper_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_copper/sheen_roughness") + ]], + float SR_copper_coat = 1.000000 + [[ + materialx::core::origin("SR_copper/coat") + ]], + color SR_copper_coat_color = color(0.964680, 0.376263, 0.258183) + [[ + materialx::core::origin("SR_copper/coat_color") + ]], + float SR_copper_coat_roughness = 0.200000 + [[ + materialx::core::origin("SR_copper/coat_roughness") + ]], + float SR_copper_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_copper/coat_anisotropy") + ]], + float SR_copper_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_copper/coat_rotation") + ]], + uniform float SR_copper_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_copper/coat_IOR") + ]], + float SR_copper_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_copper/coat_affect_color") + ]], + float SR_copper_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_copper/coat_affect_roughness") + ]], + float SR_copper_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_copper/thin_film_thickness") + ]], + float SR_copper_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_copper/thin_film_IOR") + ]], + float SR_copper_emission = 0.000000 + [[ + materialx::core::origin("SR_copper/emission") + ]], + color SR_copper_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_copper/emission_color") + ]], + color SR_copper_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_copper/opacity") + ]], + bool SR_copper_thin_walled = false + [[ + materialx::core::origin("SR_copper/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_copper_out = NG_standard_surface_surfaceshader_100(SR_copper_base, SR_copper_base_color, SR_copper_diffuse_roughness, SR_copper_metalness, SR_copper_specular, SR_copper_specular_color, SR_copper_specular_roughness, SR_copper_specular_IOR, SR_copper_specular_anisotropy, SR_copper_specular_rotation, SR_copper_transmission, SR_copper_transmission_color, SR_copper_transmission_depth, SR_copper_transmission_scatter, SR_copper_transmission_scatter_anisotropy, SR_copper_transmission_dispersion, SR_copper_transmission_extra_roughness, SR_copper_subsurface, SR_copper_subsurface_color, SR_copper_subsurface_radius, SR_copper_subsurface_scale, SR_copper_subsurface_anisotropy, SR_copper_sheen, SR_copper_sheen_color, SR_copper_sheen_roughness, SR_copper_coat, SR_copper_coat_color, SR_copper_coat_roughness, SR_copper_coat_anisotropy, SR_copper_coat_rotation, SR_copper_coat_IOR, geomprop_Nworld_out1, SR_copper_coat_affect_color, SR_copper_coat_affect_roughness, SR_copper_thin_film_thickness, SR_copper_thin_film_IOR, SR_copper_emission, SR_copper_emission_color, SR_copper_opacity, SR_copper_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Copper_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_copper_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Copper_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Copper.msl.frag b/Materials/Examples/StandardSurface/Copper.msl.frag new file mode 100644 index 0000000000..547080800e --- /dev/null +++ b/Materials/Examples/StandardSurface/Copper.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_copper_base; + vec3 SR_copper_base_color; + float SR_copper_diffuse_roughness; + float SR_copper_metalness; + float SR_copper_specular; + vec3 SR_copper_specular_color; + float SR_copper_specular_roughness; + float SR_copper_specular_IOR; + float SR_copper_specular_anisotropy; + float SR_copper_specular_rotation; + float SR_copper_transmission; + vec3 SR_copper_transmission_color; + float SR_copper_transmission_depth; + vec3 SR_copper_transmission_scatter; + float SR_copper_transmission_scatter_anisotropy; + float SR_copper_transmission_dispersion; + float SR_copper_transmission_extra_roughness; + float SR_copper_subsurface; + vec3 SR_copper_subsurface_color; + vec3 SR_copper_subsurface_radius; + float SR_copper_subsurface_scale; + float SR_copper_subsurface_anisotropy; + float SR_copper_sheen; + vec3 SR_copper_sheen_color; + float SR_copper_sheen_roughness; + float SR_copper_coat; + vec3 SR_copper_coat_color; + float SR_copper_coat_roughness; + float SR_copper_coat_anisotropy; + float SR_copper_coat_rotation; + float SR_copper_coat_IOR; + float SR_copper_coat_affect_color; + float SR_copper_coat_affect_roughness; + float SR_copper_thin_film_thickness; + float SR_copper_thin_film_IOR; + float SR_copper_emission; + vec3 SR_copper_emission_color; + vec3 SR_copper_opacity; + bool SR_copper_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_copper_base + + , vec3 SR_copper_base_color + + , float SR_copper_diffuse_roughness + + , float SR_copper_metalness + + , float SR_copper_specular + + , vec3 SR_copper_specular_color + + , float SR_copper_specular_roughness + + , float SR_copper_specular_IOR + + , float SR_copper_specular_anisotropy + + , float SR_copper_specular_rotation + + , float SR_copper_transmission + + , vec3 SR_copper_transmission_color + + , float SR_copper_transmission_depth + + , vec3 SR_copper_transmission_scatter + + , float SR_copper_transmission_scatter_anisotropy + + , float SR_copper_transmission_dispersion + + , float SR_copper_transmission_extra_roughness + + , float SR_copper_subsurface + + , vec3 SR_copper_subsurface_color + + , vec3 SR_copper_subsurface_radius + + , float SR_copper_subsurface_scale + + , float SR_copper_subsurface_anisotropy + + , float SR_copper_sheen + + , vec3 SR_copper_sheen_color + + , float SR_copper_sheen_roughness + + , float SR_copper_coat + + , vec3 SR_copper_coat_color + + , float SR_copper_coat_roughness + + , float SR_copper_coat_anisotropy + + , float SR_copper_coat_rotation + + , float SR_copper_coat_IOR + + , float SR_copper_coat_affect_color + + , float SR_copper_coat_affect_roughness + + , float SR_copper_thin_film_thickness + + , float SR_copper_thin_film_IOR + + , float SR_copper_emission + + , vec3 SR_copper_emission_color + + , vec3 SR_copper_opacity + + , bool SR_copper_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_copper_base(SR_copper_base) + + , SR_copper_base_color(SR_copper_base_color) + + , SR_copper_diffuse_roughness(SR_copper_diffuse_roughness) + + , SR_copper_metalness(SR_copper_metalness) + + , SR_copper_specular(SR_copper_specular) + + , SR_copper_specular_color(SR_copper_specular_color) + + , SR_copper_specular_roughness(SR_copper_specular_roughness) + + , SR_copper_specular_IOR(SR_copper_specular_IOR) + + , SR_copper_specular_anisotropy(SR_copper_specular_anisotropy) + + , SR_copper_specular_rotation(SR_copper_specular_rotation) + + , SR_copper_transmission(SR_copper_transmission) + + , SR_copper_transmission_color(SR_copper_transmission_color) + + , SR_copper_transmission_depth(SR_copper_transmission_depth) + + , SR_copper_transmission_scatter(SR_copper_transmission_scatter) + + , SR_copper_transmission_scatter_anisotropy(SR_copper_transmission_scatter_anisotropy) + + , SR_copper_transmission_dispersion(SR_copper_transmission_dispersion) + + , SR_copper_transmission_extra_roughness(SR_copper_transmission_extra_roughness) + + , SR_copper_subsurface(SR_copper_subsurface) + + , SR_copper_subsurface_color(SR_copper_subsurface_color) + + , SR_copper_subsurface_radius(SR_copper_subsurface_radius) + + , SR_copper_subsurface_scale(SR_copper_subsurface_scale) + + , SR_copper_subsurface_anisotropy(SR_copper_subsurface_anisotropy) + + , SR_copper_sheen(SR_copper_sheen) + + , SR_copper_sheen_color(SR_copper_sheen_color) + + , SR_copper_sheen_roughness(SR_copper_sheen_roughness) + + , SR_copper_coat(SR_copper_coat) + + , SR_copper_coat_color(SR_copper_coat_color) + + , SR_copper_coat_roughness(SR_copper_coat_roughness) + + , SR_copper_coat_anisotropy(SR_copper_coat_anisotropy) + + , SR_copper_coat_rotation(SR_copper_coat_rotation) + + , SR_copper_coat_IOR(SR_copper_coat_IOR) + + , SR_copper_coat_affect_color(SR_copper_coat_affect_color) + + , SR_copper_coat_affect_roughness(SR_copper_coat_affect_roughness) + + , SR_copper_thin_film_thickness(SR_copper_thin_film_thickness) + + , SR_copper_thin_film_IOR(SR_copper_thin_film_IOR) + + , SR_copper_emission(SR_copper_emission) + + , SR_copper_emission_color(SR_copper_emission_color) + + , SR_copper_opacity(SR_copper_opacity) + + , SR_copper_thin_walled(SR_copper_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_copper_base; + + + vec3 SR_copper_base_color; + + + float SR_copper_diffuse_roughness; + + + float SR_copper_metalness; + + + float SR_copper_specular; + + + vec3 SR_copper_specular_color; + + + float SR_copper_specular_roughness; + + + float SR_copper_specular_IOR; + + + float SR_copper_specular_anisotropy; + + + float SR_copper_specular_rotation; + + + float SR_copper_transmission; + + + vec3 SR_copper_transmission_color; + + + float SR_copper_transmission_depth; + + + vec3 SR_copper_transmission_scatter; + + + float SR_copper_transmission_scatter_anisotropy; + + + float SR_copper_transmission_dispersion; + + + float SR_copper_transmission_extra_roughness; + + + float SR_copper_subsurface; + + + vec3 SR_copper_subsurface_color; + + + vec3 SR_copper_subsurface_radius; + + + float SR_copper_subsurface_scale; + + + float SR_copper_subsurface_anisotropy; + + + float SR_copper_sheen; + + + vec3 SR_copper_sheen_color; + + + float SR_copper_sheen_roughness; + + + float SR_copper_coat; + + + vec3 SR_copper_coat_color; + + + float SR_copper_coat_roughness; + + + float SR_copper_coat_anisotropy; + + + float SR_copper_coat_rotation; + + + float SR_copper_coat_IOR; + + + float SR_copper_coat_affect_color; + + + float SR_copper_coat_affect_roughness; + + + float SR_copper_thin_film_thickness; + + + float SR_copper_thin_film_IOR; + + + float SR_copper_emission; + + + vec3 SR_copper_emission_color; + + + vec3 SR_copper_opacity; + + + bool SR_copper_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_copper_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_copper_base, SR_copper_base_color, SR_copper_diffuse_roughness, SR_copper_metalness, SR_copper_specular, SR_copper_specular_color, SR_copper_specular_roughness, SR_copper_specular_IOR, SR_copper_specular_anisotropy, SR_copper_specular_rotation, SR_copper_transmission, SR_copper_transmission_color, SR_copper_transmission_depth, SR_copper_transmission_scatter, SR_copper_transmission_scatter_anisotropy, SR_copper_transmission_dispersion, SR_copper_transmission_extra_roughness, SR_copper_subsurface, SR_copper_subsurface_color, SR_copper_subsurface_radius, SR_copper_subsurface_scale, SR_copper_subsurface_anisotropy, SR_copper_sheen, SR_copper_sheen_color, SR_copper_sheen_roughness, SR_copper_coat, SR_copper_coat_color, SR_copper_coat_roughness, SR_copper_coat_anisotropy, SR_copper_coat_rotation, SR_copper_coat_IOR, geomprop_Nworld_out1, SR_copper_coat_affect_color, SR_copper_coat_affect_roughness, SR_copper_thin_film_thickness, SR_copper_thin_film_IOR, SR_copper_emission, SR_copper_emission_color, SR_copper_opacity, SR_copper_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_copper_out); + material Copper_out = SR_copper_out; + out1 = float4(Copper_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_copper_base + , u_pub.SR_copper_base_color + , u_pub.SR_copper_diffuse_roughness + , u_pub.SR_copper_metalness + , u_pub.SR_copper_specular + , u_pub.SR_copper_specular_color + , u_pub.SR_copper_specular_roughness + , u_pub.SR_copper_specular_IOR + , u_pub.SR_copper_specular_anisotropy + , u_pub.SR_copper_specular_rotation + , u_pub.SR_copper_transmission + , u_pub.SR_copper_transmission_color + , u_pub.SR_copper_transmission_depth + , u_pub.SR_copper_transmission_scatter + , u_pub.SR_copper_transmission_scatter_anisotropy + , u_pub.SR_copper_transmission_dispersion + , u_pub.SR_copper_transmission_extra_roughness + , u_pub.SR_copper_subsurface + , u_pub.SR_copper_subsurface_color + , u_pub.SR_copper_subsurface_radius + , u_pub.SR_copper_subsurface_scale + , u_pub.SR_copper_subsurface_anisotropy + , u_pub.SR_copper_sheen + , u_pub.SR_copper_sheen_color + , u_pub.SR_copper_sheen_roughness + , u_pub.SR_copper_coat + , u_pub.SR_copper_coat_color + , u_pub.SR_copper_coat_roughness + , u_pub.SR_copper_coat_anisotropy + , u_pub.SR_copper_coat_rotation + , u_pub.SR_copper_coat_IOR + , u_pub.SR_copper_coat_affect_color + , u_pub.SR_copper_coat_affect_roughness + , u_pub.SR_copper_thin_film_thickness + , u_pub.SR_copper_thin_film_IOR + , u_pub.SR_copper_emission + , u_pub.SR_copper_emission_color + , u_pub.SR_copper_opacity + , u_pub.SR_copper_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Copper.msl.vert b/Materials/Examples/StandardSurface/Copper.msl.vert new file mode 100644 index 0000000000..f288bc0081 --- /dev/null +++ b/Materials/Examples/StandardSurface/Copper.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_copper'. Function already called in this scope. + // Omitted node 'Copper'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Copper.osl b/Materials/Examples/StandardSurface/Copper.osl new file mode 100644 index 0000000000..da3a5430a7 --- /dev/null +++ b/Materials/Examples/StandardSurface/Copper.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Copper +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Copper" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_copper_base = 1.000000 + [[ + string widget = "number" + ]], + color SR_copper_base_color = color(1.000000, 1.000000, 1.000000), + float SR_copper_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_copper_metalness = 1.000000 + [[ + string widget = "number" + ]], + float SR_copper_specular = 0.000000 + [[ + string widget = "number" + ]], + color SR_copper_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_copper_specular_roughness = 0.250000 + [[ + string widget = "number" + ]], + float SR_copper_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_copper_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_copper_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_copper_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_copper_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_copper_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_copper_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_copper_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_copper_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_copper_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_copper_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_copper_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_copper_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_copper_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_copper_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_copper_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_copper_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_copper_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_copper_coat = 1.000000 + [[ + string widget = "number" + ]], + color SR_copper_coat_color = color(0.964680, 0.376263, 0.258183), + float SR_copper_coat_roughness = 0.200000 + [[ + string widget = "number" + ]], + float SR_copper_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_copper_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_copper_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_copper_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_copper_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_copper_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_copper_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_copper_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_copper_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_copper_opacity = color(1.000000, 1.000000, 1.000000), + int SR_copper_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_copper_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_copper_base, SR_copper_base_color, SR_copper_diffuse_roughness, SR_copper_metalness, SR_copper_specular, SR_copper_specular_color, SR_copper_specular_roughness, SR_copper_specular_IOR, SR_copper_specular_anisotropy, SR_copper_specular_rotation, SR_copper_transmission, SR_copper_transmission_color, SR_copper_transmission_depth, SR_copper_transmission_scatter, SR_copper_transmission_scatter_anisotropy, SR_copper_transmission_dispersion, SR_copper_transmission_extra_roughness, SR_copper_subsurface, SR_copper_subsurface_color, SR_copper_subsurface_radius, SR_copper_subsurface_scale, SR_copper_subsurface_anisotropy, SR_copper_sheen, SR_copper_sheen_color, SR_copper_sheen_roughness, SR_copper_coat, SR_copper_coat_color, SR_copper_coat_roughness, SR_copper_coat_anisotropy, SR_copper_coat_rotation, SR_copper_coat_IOR, geomprop_Nworld_out1, SR_copper_coat_affect_color, SR_copper_coat_affect_roughness, SR_copper_thin_film_thickness, SR_copper_thin_film_IOR, SR_copper_emission, SR_copper_emission_color, SR_copper_opacity, SR_copper_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_copper_out); + MATERIAL Copper_out = mx_surfacematerial(SR_copper_out, backsurfaceshader, displacementshader1); + out = Copper_out; +} + diff --git a/Materials/Examples/StandardSurface/Default.glsl.frag b/Materials/Examples/StandardSurface/Default.glsl.frag new file mode 100644 index 0000000000..4c2bf078b1 --- /dev/null +++ b/Materials/Examples/StandardSurface/Default.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_default_base = 1.000000; +uniform vec3 SR_default_base_color = vec3(0.800000, 0.800000, 0.800000); +uniform float SR_default_diffuse_roughness = 0.000000; +uniform float SR_default_metalness = 0.000000; +uniform float SR_default_specular = 1.000000; +uniform vec3 SR_default_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_default_specular_roughness = 0.200000; +uniform float SR_default_specular_IOR = 1.500000; +uniform float SR_default_specular_anisotropy = 0.000000; +uniform float SR_default_specular_rotation = 0.000000; +uniform float SR_default_transmission = 0.000000; +uniform vec3 SR_default_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_default_transmission_depth = 0.000000; +uniform vec3 SR_default_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_default_transmission_scatter_anisotropy = 0.000000; +uniform float SR_default_transmission_dispersion = 0.000000; +uniform float SR_default_transmission_extra_roughness = 0.000000; +uniform float SR_default_subsurface = 0.000000; +uniform vec3 SR_default_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_default_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_default_subsurface_scale = 1.000000; +uniform float SR_default_subsurface_anisotropy = 0.000000; +uniform float SR_default_sheen = 0.000000; +uniform vec3 SR_default_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_default_sheen_roughness = 0.300000; +uniform float SR_default_coat = 0.000000; +uniform vec3 SR_default_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_default_coat_roughness = 0.100000; +uniform float SR_default_coat_anisotropy = 0.000000; +uniform float SR_default_coat_rotation = 0.000000; +uniform float SR_default_coat_IOR = 1.500000; +uniform float SR_default_coat_affect_color = 0.000000; +uniform float SR_default_coat_affect_roughness = 0.000000; +uniform float SR_default_thin_film_thickness = 0.000000; +uniform float SR_default_thin_film_IOR = 1.500000; +uniform float SR_default_emission = 0.000000; +uniform vec3 SR_default_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_default_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_default_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_default_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_default_base, SR_default_base_color, SR_default_diffuse_roughness, SR_default_metalness, SR_default_specular, SR_default_specular_color, SR_default_specular_roughness, SR_default_specular_IOR, SR_default_specular_anisotropy, SR_default_specular_rotation, SR_default_transmission, SR_default_transmission_color, SR_default_transmission_depth, SR_default_transmission_scatter, SR_default_transmission_scatter_anisotropy, SR_default_transmission_dispersion, SR_default_transmission_extra_roughness, SR_default_subsurface, SR_default_subsurface_color, SR_default_subsurface_radius, SR_default_subsurface_scale, SR_default_subsurface_anisotropy, SR_default_sheen, SR_default_sheen_color, SR_default_sheen_roughness, SR_default_coat, SR_default_coat_color, SR_default_coat_roughness, SR_default_coat_anisotropy, SR_default_coat_rotation, SR_default_coat_IOR, geomprop_Nworld_out1, SR_default_coat_affect_color, SR_default_coat_affect_roughness, SR_default_thin_film_thickness, SR_default_thin_film_IOR, SR_default_emission, SR_default_emission_color, SR_default_opacity, SR_default_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_default_out); + material Default_out = SR_default_out; + out1 = vec4(Default_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Default.glsl.vert b/Materials/Examples/StandardSurface/Default.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/Default.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Default.mdl b/Materials/Examples/StandardSurface/Default.mdl new file mode 100644 index 0000000000..938568604e --- /dev/null +++ b/Materials/Examples/StandardSurface/Default.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Default +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_default_base = 1.000000 + [[ + materialx::core::origin("SR_default/base") + ]], + color SR_default_base_color = color(0.800000, 0.800000, 0.800000) + [[ + materialx::core::origin("SR_default/base_color") + ]], + float SR_default_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_default/diffuse_roughness") + ]], + float SR_default_metalness = 0.000000 + [[ + materialx::core::origin("SR_default/metalness") + ]], + float SR_default_specular = 1.000000 + [[ + materialx::core::origin("SR_default/specular") + ]], + color SR_default_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_default/specular_color") + ]], + float SR_default_specular_roughness = 0.200000 + [[ + materialx::core::origin("SR_default/specular_roughness") + ]], + uniform float SR_default_specular_IOR = 1.500000 + [[ + materialx::core::origin("SR_default/specular_IOR") + ]], + float SR_default_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_default/specular_anisotropy") + ]], + float SR_default_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_default/specular_rotation") + ]], + float SR_default_transmission = 0.000000 + [[ + materialx::core::origin("SR_default/transmission") + ]], + color SR_default_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_default/transmission_color") + ]], + float SR_default_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_default/transmission_depth") + ]], + color SR_default_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_default/transmission_scatter") + ]], + float SR_default_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_default/transmission_scatter_anisotropy") + ]], + float SR_default_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_default/transmission_dispersion") + ]], + float SR_default_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_default/transmission_extra_roughness") + ]], + float SR_default_subsurface = 0.000000 + [[ + materialx::core::origin("SR_default/subsurface") + ]], + color SR_default_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_default/subsurface_color") + ]], + color SR_default_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_default/subsurface_radius") + ]], + float SR_default_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_default/subsurface_scale") + ]], + float SR_default_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_default/subsurface_anisotropy") + ]], + float SR_default_sheen = 0.000000 + [[ + materialx::core::origin("SR_default/sheen") + ]], + color SR_default_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_default/sheen_color") + ]], + float SR_default_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_default/sheen_roughness") + ]], + float SR_default_coat = 0.000000 + [[ + materialx::core::origin("SR_default/coat") + ]], + color SR_default_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_default/coat_color") + ]], + float SR_default_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_default/coat_roughness") + ]], + float SR_default_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_default/coat_anisotropy") + ]], + float SR_default_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_default/coat_rotation") + ]], + uniform float SR_default_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_default/coat_IOR") + ]], + float SR_default_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_default/coat_affect_color") + ]], + float SR_default_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_default/coat_affect_roughness") + ]], + float SR_default_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_default/thin_film_thickness") + ]], + float SR_default_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_default/thin_film_IOR") + ]], + float SR_default_emission = 0.000000 + [[ + materialx::core::origin("SR_default/emission") + ]], + color SR_default_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_default/emission_color") + ]], + color SR_default_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_default/opacity") + ]], + bool SR_default_thin_walled = false + [[ + materialx::core::origin("SR_default/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_default_out = NG_standard_surface_surfaceshader_100(SR_default_base, SR_default_base_color, SR_default_diffuse_roughness, SR_default_metalness, SR_default_specular, SR_default_specular_color, SR_default_specular_roughness, SR_default_specular_IOR, SR_default_specular_anisotropy, SR_default_specular_rotation, SR_default_transmission, SR_default_transmission_color, SR_default_transmission_depth, SR_default_transmission_scatter, SR_default_transmission_scatter_anisotropy, SR_default_transmission_dispersion, SR_default_transmission_extra_roughness, SR_default_subsurface, SR_default_subsurface_color, SR_default_subsurface_radius, SR_default_subsurface_scale, SR_default_subsurface_anisotropy, SR_default_sheen, SR_default_sheen_color, SR_default_sheen_roughness, SR_default_coat, SR_default_coat_color, SR_default_coat_roughness, SR_default_coat_anisotropy, SR_default_coat_rotation, SR_default_coat_IOR, geomprop_Nworld_out1, SR_default_coat_affect_color, SR_default_coat_affect_roughness, SR_default_thin_film_thickness, SR_default_thin_film_IOR, SR_default_emission, SR_default_emission_color, SR_default_opacity, SR_default_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Default_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_default_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Default_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Default.msl.frag b/Materials/Examples/StandardSurface/Default.msl.frag new file mode 100644 index 0000000000..43f01d90e1 --- /dev/null +++ b/Materials/Examples/StandardSurface/Default.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_default_base; + vec3 SR_default_base_color; + float SR_default_diffuse_roughness; + float SR_default_metalness; + float SR_default_specular; + vec3 SR_default_specular_color; + float SR_default_specular_roughness; + float SR_default_specular_IOR; + float SR_default_specular_anisotropy; + float SR_default_specular_rotation; + float SR_default_transmission; + vec3 SR_default_transmission_color; + float SR_default_transmission_depth; + vec3 SR_default_transmission_scatter; + float SR_default_transmission_scatter_anisotropy; + float SR_default_transmission_dispersion; + float SR_default_transmission_extra_roughness; + float SR_default_subsurface; + vec3 SR_default_subsurface_color; + vec3 SR_default_subsurface_radius; + float SR_default_subsurface_scale; + float SR_default_subsurface_anisotropy; + float SR_default_sheen; + vec3 SR_default_sheen_color; + float SR_default_sheen_roughness; + float SR_default_coat; + vec3 SR_default_coat_color; + float SR_default_coat_roughness; + float SR_default_coat_anisotropy; + float SR_default_coat_rotation; + float SR_default_coat_IOR; + float SR_default_coat_affect_color; + float SR_default_coat_affect_roughness; + float SR_default_thin_film_thickness; + float SR_default_thin_film_IOR; + float SR_default_emission; + vec3 SR_default_emission_color; + vec3 SR_default_opacity; + bool SR_default_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_default_base + + , vec3 SR_default_base_color + + , float SR_default_diffuse_roughness + + , float SR_default_metalness + + , float SR_default_specular + + , vec3 SR_default_specular_color + + , float SR_default_specular_roughness + + , float SR_default_specular_IOR + + , float SR_default_specular_anisotropy + + , float SR_default_specular_rotation + + , float SR_default_transmission + + , vec3 SR_default_transmission_color + + , float SR_default_transmission_depth + + , vec3 SR_default_transmission_scatter + + , float SR_default_transmission_scatter_anisotropy + + , float SR_default_transmission_dispersion + + , float SR_default_transmission_extra_roughness + + , float SR_default_subsurface + + , vec3 SR_default_subsurface_color + + , vec3 SR_default_subsurface_radius + + , float SR_default_subsurface_scale + + , float SR_default_subsurface_anisotropy + + , float SR_default_sheen + + , vec3 SR_default_sheen_color + + , float SR_default_sheen_roughness + + , float SR_default_coat + + , vec3 SR_default_coat_color + + , float SR_default_coat_roughness + + , float SR_default_coat_anisotropy + + , float SR_default_coat_rotation + + , float SR_default_coat_IOR + + , float SR_default_coat_affect_color + + , float SR_default_coat_affect_roughness + + , float SR_default_thin_film_thickness + + , float SR_default_thin_film_IOR + + , float SR_default_emission + + , vec3 SR_default_emission_color + + , vec3 SR_default_opacity + + , bool SR_default_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_default_base(SR_default_base) + + , SR_default_base_color(SR_default_base_color) + + , SR_default_diffuse_roughness(SR_default_diffuse_roughness) + + , SR_default_metalness(SR_default_metalness) + + , SR_default_specular(SR_default_specular) + + , SR_default_specular_color(SR_default_specular_color) + + , SR_default_specular_roughness(SR_default_specular_roughness) + + , SR_default_specular_IOR(SR_default_specular_IOR) + + , SR_default_specular_anisotropy(SR_default_specular_anisotropy) + + , SR_default_specular_rotation(SR_default_specular_rotation) + + , SR_default_transmission(SR_default_transmission) + + , SR_default_transmission_color(SR_default_transmission_color) + + , SR_default_transmission_depth(SR_default_transmission_depth) + + , SR_default_transmission_scatter(SR_default_transmission_scatter) + + , SR_default_transmission_scatter_anisotropy(SR_default_transmission_scatter_anisotropy) + + , SR_default_transmission_dispersion(SR_default_transmission_dispersion) + + , SR_default_transmission_extra_roughness(SR_default_transmission_extra_roughness) + + , SR_default_subsurface(SR_default_subsurface) + + , SR_default_subsurface_color(SR_default_subsurface_color) + + , SR_default_subsurface_radius(SR_default_subsurface_radius) + + , SR_default_subsurface_scale(SR_default_subsurface_scale) + + , SR_default_subsurface_anisotropy(SR_default_subsurface_anisotropy) + + , SR_default_sheen(SR_default_sheen) + + , SR_default_sheen_color(SR_default_sheen_color) + + , SR_default_sheen_roughness(SR_default_sheen_roughness) + + , SR_default_coat(SR_default_coat) + + , SR_default_coat_color(SR_default_coat_color) + + , SR_default_coat_roughness(SR_default_coat_roughness) + + , SR_default_coat_anisotropy(SR_default_coat_anisotropy) + + , SR_default_coat_rotation(SR_default_coat_rotation) + + , SR_default_coat_IOR(SR_default_coat_IOR) + + , SR_default_coat_affect_color(SR_default_coat_affect_color) + + , SR_default_coat_affect_roughness(SR_default_coat_affect_roughness) + + , SR_default_thin_film_thickness(SR_default_thin_film_thickness) + + , SR_default_thin_film_IOR(SR_default_thin_film_IOR) + + , SR_default_emission(SR_default_emission) + + , SR_default_emission_color(SR_default_emission_color) + + , SR_default_opacity(SR_default_opacity) + + , SR_default_thin_walled(SR_default_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_default_base; + + + vec3 SR_default_base_color; + + + float SR_default_diffuse_roughness; + + + float SR_default_metalness; + + + float SR_default_specular; + + + vec3 SR_default_specular_color; + + + float SR_default_specular_roughness; + + + float SR_default_specular_IOR; + + + float SR_default_specular_anisotropy; + + + float SR_default_specular_rotation; + + + float SR_default_transmission; + + + vec3 SR_default_transmission_color; + + + float SR_default_transmission_depth; + + + vec3 SR_default_transmission_scatter; + + + float SR_default_transmission_scatter_anisotropy; + + + float SR_default_transmission_dispersion; + + + float SR_default_transmission_extra_roughness; + + + float SR_default_subsurface; + + + vec3 SR_default_subsurface_color; + + + vec3 SR_default_subsurface_radius; + + + float SR_default_subsurface_scale; + + + float SR_default_subsurface_anisotropy; + + + float SR_default_sheen; + + + vec3 SR_default_sheen_color; + + + float SR_default_sheen_roughness; + + + float SR_default_coat; + + + vec3 SR_default_coat_color; + + + float SR_default_coat_roughness; + + + float SR_default_coat_anisotropy; + + + float SR_default_coat_rotation; + + + float SR_default_coat_IOR; + + + float SR_default_coat_affect_color; + + + float SR_default_coat_affect_roughness; + + + float SR_default_thin_film_thickness; + + + float SR_default_thin_film_IOR; + + + float SR_default_emission; + + + vec3 SR_default_emission_color; + + + vec3 SR_default_opacity; + + + bool SR_default_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_default_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_default_base, SR_default_base_color, SR_default_diffuse_roughness, SR_default_metalness, SR_default_specular, SR_default_specular_color, SR_default_specular_roughness, SR_default_specular_IOR, SR_default_specular_anisotropy, SR_default_specular_rotation, SR_default_transmission, SR_default_transmission_color, SR_default_transmission_depth, SR_default_transmission_scatter, SR_default_transmission_scatter_anisotropy, SR_default_transmission_dispersion, SR_default_transmission_extra_roughness, SR_default_subsurface, SR_default_subsurface_color, SR_default_subsurface_radius, SR_default_subsurface_scale, SR_default_subsurface_anisotropy, SR_default_sheen, SR_default_sheen_color, SR_default_sheen_roughness, SR_default_coat, SR_default_coat_color, SR_default_coat_roughness, SR_default_coat_anisotropy, SR_default_coat_rotation, SR_default_coat_IOR, geomprop_Nworld_out1, SR_default_coat_affect_color, SR_default_coat_affect_roughness, SR_default_thin_film_thickness, SR_default_thin_film_IOR, SR_default_emission, SR_default_emission_color, SR_default_opacity, SR_default_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_default_out); + material Default_out = SR_default_out; + out1 = float4(Default_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_default_base + , u_pub.SR_default_base_color + , u_pub.SR_default_diffuse_roughness + , u_pub.SR_default_metalness + , u_pub.SR_default_specular + , u_pub.SR_default_specular_color + , u_pub.SR_default_specular_roughness + , u_pub.SR_default_specular_IOR + , u_pub.SR_default_specular_anisotropy + , u_pub.SR_default_specular_rotation + , u_pub.SR_default_transmission + , u_pub.SR_default_transmission_color + , u_pub.SR_default_transmission_depth + , u_pub.SR_default_transmission_scatter + , u_pub.SR_default_transmission_scatter_anisotropy + , u_pub.SR_default_transmission_dispersion + , u_pub.SR_default_transmission_extra_roughness + , u_pub.SR_default_subsurface + , u_pub.SR_default_subsurface_color + , u_pub.SR_default_subsurface_radius + , u_pub.SR_default_subsurface_scale + , u_pub.SR_default_subsurface_anisotropy + , u_pub.SR_default_sheen + , u_pub.SR_default_sheen_color + , u_pub.SR_default_sheen_roughness + , u_pub.SR_default_coat + , u_pub.SR_default_coat_color + , u_pub.SR_default_coat_roughness + , u_pub.SR_default_coat_anisotropy + , u_pub.SR_default_coat_rotation + , u_pub.SR_default_coat_IOR + , u_pub.SR_default_coat_affect_color + , u_pub.SR_default_coat_affect_roughness + , u_pub.SR_default_thin_film_thickness + , u_pub.SR_default_thin_film_IOR + , u_pub.SR_default_emission + , u_pub.SR_default_emission_color + , u_pub.SR_default_opacity + , u_pub.SR_default_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Default.msl.vert b/Materials/Examples/StandardSurface/Default.msl.vert new file mode 100644 index 0000000000..6fc79de9f8 --- /dev/null +++ b/Materials/Examples/StandardSurface/Default.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_default'. Function already called in this scope. + // Omitted node 'Default'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Default.osl b/Materials/Examples/StandardSurface/Default.osl new file mode 100644 index 0000000000..becb8ada16 --- /dev/null +++ b/Materials/Examples/StandardSurface/Default.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Default +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Default" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_default_base = 1.000000 + [[ + string widget = "number" + ]], + color SR_default_base_color = color(0.800000, 0.800000, 0.800000), + float SR_default_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_metalness = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_specular = 1.000000 + [[ + string widget = "number" + ]], + color SR_default_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_default_specular_roughness = 0.200000 + [[ + string widget = "number" + ]], + float SR_default_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_default_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_default_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_default_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_default_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_default_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_default_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_default_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_default_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_default_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_default_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_default_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_default_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_default_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_default_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_default_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_default_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_default_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_default_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_default_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_default_opacity = color(1.000000, 1.000000, 1.000000), + int SR_default_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_default_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_default_base, SR_default_base_color, SR_default_diffuse_roughness, SR_default_metalness, SR_default_specular, SR_default_specular_color, SR_default_specular_roughness, SR_default_specular_IOR, SR_default_specular_anisotropy, SR_default_specular_rotation, SR_default_transmission, SR_default_transmission_color, SR_default_transmission_depth, SR_default_transmission_scatter, SR_default_transmission_scatter_anisotropy, SR_default_transmission_dispersion, SR_default_transmission_extra_roughness, SR_default_subsurface, SR_default_subsurface_color, SR_default_subsurface_radius, SR_default_subsurface_scale, SR_default_subsurface_anisotropy, SR_default_sheen, SR_default_sheen_color, SR_default_sheen_roughness, SR_default_coat, SR_default_coat_color, SR_default_coat_roughness, SR_default_coat_anisotropy, SR_default_coat_rotation, SR_default_coat_IOR, geomprop_Nworld_out1, SR_default_coat_affect_color, SR_default_coat_affect_roughness, SR_default_thin_film_thickness, SR_default_thin_film_IOR, SR_default_emission, SR_default_emission_color, SR_default_opacity, SR_default_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_default_out); + MATERIAL Default_out = mx_surfacematerial(SR_default_out, backsurfaceshader, displacementshader1); + out = Default_out; +} + diff --git a/Materials/Examples/StandardSurface/Glass.glsl.frag b/Materials/Examples/StandardSurface/Glass.glsl.frag new file mode 100644 index 0000000000..11fc0aeb02 --- /dev/null +++ b/Materials/Examples/StandardSurface/Glass.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_glass_base = 0.000000; +uniform vec3 SR_glass_base_color = vec3(0.800000, 0.800000, 0.800000); +uniform float SR_glass_diffuse_roughness = 0.000000; +uniform float SR_glass_metalness = 0.000000; +uniform float SR_glass_specular = 1.000000; +uniform vec3 SR_glass_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_glass_specular_roughness = 0.010000; +uniform float SR_glass_specular_IOR = 1.520000; +uniform float SR_glass_specular_anisotropy = 0.000000; +uniform float SR_glass_specular_rotation = 0.000000; +uniform float SR_glass_transmission = 1.000000; +uniform vec3 SR_glass_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_glass_transmission_depth = 0.000000; +uniform vec3 SR_glass_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_glass_transmission_scatter_anisotropy = 0.000000; +uniform float SR_glass_transmission_dispersion = 0.000000; +uniform float SR_glass_transmission_extra_roughness = 0.000000; +uniform float SR_glass_subsurface = 0.000000; +uniform vec3 SR_glass_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_glass_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_glass_subsurface_scale = 1.000000; +uniform float SR_glass_subsurface_anisotropy = 0.000000; +uniform float SR_glass_sheen = 0.000000; +uniform vec3 SR_glass_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_glass_sheen_roughness = 0.300000; +uniform float SR_glass_coat = 0.000000; +uniform vec3 SR_glass_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_glass_coat_roughness = 0.100000; +uniform float SR_glass_coat_anisotropy = 0.000000; +uniform float SR_glass_coat_rotation = 0.000000; +uniform float SR_glass_coat_IOR = 1.500000; +uniform float SR_glass_coat_affect_color = 0.000000; +uniform float SR_glass_coat_affect_roughness = 0.000000; +uniform float SR_glass_thin_film_thickness = 0.000000; +uniform float SR_glass_thin_film_IOR = 1.500000; +uniform float SR_glass_emission = 0.000000; +uniform vec3 SR_glass_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_glass_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_glass_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_glass_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_glass_base, SR_glass_base_color, SR_glass_diffuse_roughness, SR_glass_metalness, SR_glass_specular, SR_glass_specular_color, SR_glass_specular_roughness, SR_glass_specular_IOR, SR_glass_specular_anisotropy, SR_glass_specular_rotation, SR_glass_transmission, SR_glass_transmission_color, SR_glass_transmission_depth, SR_glass_transmission_scatter, SR_glass_transmission_scatter_anisotropy, SR_glass_transmission_dispersion, SR_glass_transmission_extra_roughness, SR_glass_subsurface, SR_glass_subsurface_color, SR_glass_subsurface_radius, SR_glass_subsurface_scale, SR_glass_subsurface_anisotropy, SR_glass_sheen, SR_glass_sheen_color, SR_glass_sheen_roughness, SR_glass_coat, SR_glass_coat_color, SR_glass_coat_roughness, SR_glass_coat_anisotropy, SR_glass_coat_rotation, SR_glass_coat_IOR, geomprop_Nworld_out1, SR_glass_coat_affect_color, SR_glass_coat_affect_roughness, SR_glass_thin_film_thickness, SR_glass_thin_film_IOR, SR_glass_emission, SR_glass_emission_color, SR_glass_opacity, SR_glass_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_glass_out); + material Glass_out = SR_glass_out; + out1 = vec4(Glass_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Glass.glsl.vert b/Materials/Examples/StandardSurface/Glass.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/Glass.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Glass.mdl b/Materials/Examples/StandardSurface/Glass.mdl new file mode 100644 index 0000000000..08d27c2ad6 --- /dev/null +++ b/Materials/Examples/StandardSurface/Glass.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Glass +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_glass_base = 0.000000 + [[ + materialx::core::origin("SR_glass/base") + ]], + color SR_glass_base_color = color(0.800000, 0.800000, 0.800000) + [[ + materialx::core::origin("SR_glass/base_color") + ]], + float SR_glass_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_glass/diffuse_roughness") + ]], + float SR_glass_metalness = 0.000000 + [[ + materialx::core::origin("SR_glass/metalness") + ]], + float SR_glass_specular = 1.000000 + [[ + materialx::core::origin("SR_glass/specular") + ]], + color SR_glass_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass/specular_color") + ]], + float SR_glass_specular_roughness = 0.010000 + [[ + materialx::core::origin("SR_glass/specular_roughness") + ]], + uniform float SR_glass_specular_IOR = 1.520000 + [[ + materialx::core::origin("SR_glass/specular_IOR") + ]], + float SR_glass_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_glass/specular_anisotropy") + ]], + float SR_glass_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_glass/specular_rotation") + ]], + float SR_glass_transmission = 1.000000 + [[ + materialx::core::origin("SR_glass/transmission") + ]], + color SR_glass_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass/transmission_color") + ]], + float SR_glass_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_glass/transmission_depth") + ]], + color SR_glass_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_glass/transmission_scatter") + ]], + float SR_glass_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_glass/transmission_scatter_anisotropy") + ]], + float SR_glass_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_glass/transmission_dispersion") + ]], + float SR_glass_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_glass/transmission_extra_roughness") + ]], + float SR_glass_subsurface = 0.000000 + [[ + materialx::core::origin("SR_glass/subsurface") + ]], + color SR_glass_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass/subsurface_color") + ]], + color SR_glass_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass/subsurface_radius") + ]], + float SR_glass_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_glass/subsurface_scale") + ]], + float SR_glass_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_glass/subsurface_anisotropy") + ]], + float SR_glass_sheen = 0.000000 + [[ + materialx::core::origin("SR_glass/sheen") + ]], + color SR_glass_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass/sheen_color") + ]], + float SR_glass_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_glass/sheen_roughness") + ]], + float SR_glass_coat = 0.000000 + [[ + materialx::core::origin("SR_glass/coat") + ]], + color SR_glass_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass/coat_color") + ]], + float SR_glass_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_glass/coat_roughness") + ]], + float SR_glass_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_glass/coat_anisotropy") + ]], + float SR_glass_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_glass/coat_rotation") + ]], + uniform float SR_glass_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_glass/coat_IOR") + ]], + float SR_glass_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_glass/coat_affect_color") + ]], + float SR_glass_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_glass/coat_affect_roughness") + ]], + float SR_glass_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_glass/thin_film_thickness") + ]], + float SR_glass_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_glass/thin_film_IOR") + ]], + float SR_glass_emission = 0.000000 + [[ + materialx::core::origin("SR_glass/emission") + ]], + color SR_glass_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass/emission_color") + ]], + color SR_glass_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass/opacity") + ]], + bool SR_glass_thin_walled = false + [[ + materialx::core::origin("SR_glass/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_glass_out = NG_standard_surface_surfaceshader_100(SR_glass_base, SR_glass_base_color, SR_glass_diffuse_roughness, SR_glass_metalness, SR_glass_specular, SR_glass_specular_color, SR_glass_specular_roughness, SR_glass_specular_IOR, SR_glass_specular_anisotropy, SR_glass_specular_rotation, SR_glass_transmission, SR_glass_transmission_color, SR_glass_transmission_depth, SR_glass_transmission_scatter, SR_glass_transmission_scatter_anisotropy, SR_glass_transmission_dispersion, SR_glass_transmission_extra_roughness, SR_glass_subsurface, SR_glass_subsurface_color, SR_glass_subsurface_radius, SR_glass_subsurface_scale, SR_glass_subsurface_anisotropy, SR_glass_sheen, SR_glass_sheen_color, SR_glass_sheen_roughness, SR_glass_coat, SR_glass_coat_color, SR_glass_coat_roughness, SR_glass_coat_anisotropy, SR_glass_coat_rotation, SR_glass_coat_IOR, geomprop_Nworld_out1, SR_glass_coat_affect_color, SR_glass_coat_affect_roughness, SR_glass_thin_film_thickness, SR_glass_thin_film_IOR, SR_glass_emission, SR_glass_emission_color, SR_glass_opacity, SR_glass_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Glass_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_glass_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Glass_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Glass.msl.frag b/Materials/Examples/StandardSurface/Glass.msl.frag new file mode 100644 index 0000000000..1706d5d9d6 --- /dev/null +++ b/Materials/Examples/StandardSurface/Glass.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_glass_base; + vec3 SR_glass_base_color; + float SR_glass_diffuse_roughness; + float SR_glass_metalness; + float SR_glass_specular; + vec3 SR_glass_specular_color; + float SR_glass_specular_roughness; + float SR_glass_specular_IOR; + float SR_glass_specular_anisotropy; + float SR_glass_specular_rotation; + float SR_glass_transmission; + vec3 SR_glass_transmission_color; + float SR_glass_transmission_depth; + vec3 SR_glass_transmission_scatter; + float SR_glass_transmission_scatter_anisotropy; + float SR_glass_transmission_dispersion; + float SR_glass_transmission_extra_roughness; + float SR_glass_subsurface; + vec3 SR_glass_subsurface_color; + vec3 SR_glass_subsurface_radius; + float SR_glass_subsurface_scale; + float SR_glass_subsurface_anisotropy; + float SR_glass_sheen; + vec3 SR_glass_sheen_color; + float SR_glass_sheen_roughness; + float SR_glass_coat; + vec3 SR_glass_coat_color; + float SR_glass_coat_roughness; + float SR_glass_coat_anisotropy; + float SR_glass_coat_rotation; + float SR_glass_coat_IOR; + float SR_glass_coat_affect_color; + float SR_glass_coat_affect_roughness; + float SR_glass_thin_film_thickness; + float SR_glass_thin_film_IOR; + float SR_glass_emission; + vec3 SR_glass_emission_color; + vec3 SR_glass_opacity; + bool SR_glass_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_glass_base + + , vec3 SR_glass_base_color + + , float SR_glass_diffuse_roughness + + , float SR_glass_metalness + + , float SR_glass_specular + + , vec3 SR_glass_specular_color + + , float SR_glass_specular_roughness + + , float SR_glass_specular_IOR + + , float SR_glass_specular_anisotropy + + , float SR_glass_specular_rotation + + , float SR_glass_transmission + + , vec3 SR_glass_transmission_color + + , float SR_glass_transmission_depth + + , vec3 SR_glass_transmission_scatter + + , float SR_glass_transmission_scatter_anisotropy + + , float SR_glass_transmission_dispersion + + , float SR_glass_transmission_extra_roughness + + , float SR_glass_subsurface + + , vec3 SR_glass_subsurface_color + + , vec3 SR_glass_subsurface_radius + + , float SR_glass_subsurface_scale + + , float SR_glass_subsurface_anisotropy + + , float SR_glass_sheen + + , vec3 SR_glass_sheen_color + + , float SR_glass_sheen_roughness + + , float SR_glass_coat + + , vec3 SR_glass_coat_color + + , float SR_glass_coat_roughness + + , float SR_glass_coat_anisotropy + + , float SR_glass_coat_rotation + + , float SR_glass_coat_IOR + + , float SR_glass_coat_affect_color + + , float SR_glass_coat_affect_roughness + + , float SR_glass_thin_film_thickness + + , float SR_glass_thin_film_IOR + + , float SR_glass_emission + + , vec3 SR_glass_emission_color + + , vec3 SR_glass_opacity + + , bool SR_glass_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_glass_base(SR_glass_base) + + , SR_glass_base_color(SR_glass_base_color) + + , SR_glass_diffuse_roughness(SR_glass_diffuse_roughness) + + , SR_glass_metalness(SR_glass_metalness) + + , SR_glass_specular(SR_glass_specular) + + , SR_glass_specular_color(SR_glass_specular_color) + + , SR_glass_specular_roughness(SR_glass_specular_roughness) + + , SR_glass_specular_IOR(SR_glass_specular_IOR) + + , SR_glass_specular_anisotropy(SR_glass_specular_anisotropy) + + , SR_glass_specular_rotation(SR_glass_specular_rotation) + + , SR_glass_transmission(SR_glass_transmission) + + , SR_glass_transmission_color(SR_glass_transmission_color) + + , SR_glass_transmission_depth(SR_glass_transmission_depth) + + , SR_glass_transmission_scatter(SR_glass_transmission_scatter) + + , SR_glass_transmission_scatter_anisotropy(SR_glass_transmission_scatter_anisotropy) + + , SR_glass_transmission_dispersion(SR_glass_transmission_dispersion) + + , SR_glass_transmission_extra_roughness(SR_glass_transmission_extra_roughness) + + , SR_glass_subsurface(SR_glass_subsurface) + + , SR_glass_subsurface_color(SR_glass_subsurface_color) + + , SR_glass_subsurface_radius(SR_glass_subsurface_radius) + + , SR_glass_subsurface_scale(SR_glass_subsurface_scale) + + , SR_glass_subsurface_anisotropy(SR_glass_subsurface_anisotropy) + + , SR_glass_sheen(SR_glass_sheen) + + , SR_glass_sheen_color(SR_glass_sheen_color) + + , SR_glass_sheen_roughness(SR_glass_sheen_roughness) + + , SR_glass_coat(SR_glass_coat) + + , SR_glass_coat_color(SR_glass_coat_color) + + , SR_glass_coat_roughness(SR_glass_coat_roughness) + + , SR_glass_coat_anisotropy(SR_glass_coat_anisotropy) + + , SR_glass_coat_rotation(SR_glass_coat_rotation) + + , SR_glass_coat_IOR(SR_glass_coat_IOR) + + , SR_glass_coat_affect_color(SR_glass_coat_affect_color) + + , SR_glass_coat_affect_roughness(SR_glass_coat_affect_roughness) + + , SR_glass_thin_film_thickness(SR_glass_thin_film_thickness) + + , SR_glass_thin_film_IOR(SR_glass_thin_film_IOR) + + , SR_glass_emission(SR_glass_emission) + + , SR_glass_emission_color(SR_glass_emission_color) + + , SR_glass_opacity(SR_glass_opacity) + + , SR_glass_thin_walled(SR_glass_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_glass_base; + + + vec3 SR_glass_base_color; + + + float SR_glass_diffuse_roughness; + + + float SR_glass_metalness; + + + float SR_glass_specular; + + + vec3 SR_glass_specular_color; + + + float SR_glass_specular_roughness; + + + float SR_glass_specular_IOR; + + + float SR_glass_specular_anisotropy; + + + float SR_glass_specular_rotation; + + + float SR_glass_transmission; + + + vec3 SR_glass_transmission_color; + + + float SR_glass_transmission_depth; + + + vec3 SR_glass_transmission_scatter; + + + float SR_glass_transmission_scatter_anisotropy; + + + float SR_glass_transmission_dispersion; + + + float SR_glass_transmission_extra_roughness; + + + float SR_glass_subsurface; + + + vec3 SR_glass_subsurface_color; + + + vec3 SR_glass_subsurface_radius; + + + float SR_glass_subsurface_scale; + + + float SR_glass_subsurface_anisotropy; + + + float SR_glass_sheen; + + + vec3 SR_glass_sheen_color; + + + float SR_glass_sheen_roughness; + + + float SR_glass_coat; + + + vec3 SR_glass_coat_color; + + + float SR_glass_coat_roughness; + + + float SR_glass_coat_anisotropy; + + + float SR_glass_coat_rotation; + + + float SR_glass_coat_IOR; + + + float SR_glass_coat_affect_color; + + + float SR_glass_coat_affect_roughness; + + + float SR_glass_thin_film_thickness; + + + float SR_glass_thin_film_IOR; + + + float SR_glass_emission; + + + vec3 SR_glass_emission_color; + + + vec3 SR_glass_opacity; + + + bool SR_glass_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_glass_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_glass_base, SR_glass_base_color, SR_glass_diffuse_roughness, SR_glass_metalness, SR_glass_specular, SR_glass_specular_color, SR_glass_specular_roughness, SR_glass_specular_IOR, SR_glass_specular_anisotropy, SR_glass_specular_rotation, SR_glass_transmission, SR_glass_transmission_color, SR_glass_transmission_depth, SR_glass_transmission_scatter, SR_glass_transmission_scatter_anisotropy, SR_glass_transmission_dispersion, SR_glass_transmission_extra_roughness, SR_glass_subsurface, SR_glass_subsurface_color, SR_glass_subsurface_radius, SR_glass_subsurface_scale, SR_glass_subsurface_anisotropy, SR_glass_sheen, SR_glass_sheen_color, SR_glass_sheen_roughness, SR_glass_coat, SR_glass_coat_color, SR_glass_coat_roughness, SR_glass_coat_anisotropy, SR_glass_coat_rotation, SR_glass_coat_IOR, geomprop_Nworld_out1, SR_glass_coat_affect_color, SR_glass_coat_affect_roughness, SR_glass_thin_film_thickness, SR_glass_thin_film_IOR, SR_glass_emission, SR_glass_emission_color, SR_glass_opacity, SR_glass_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_glass_out); + material Glass_out = SR_glass_out; + out1 = float4(Glass_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_glass_base + , u_pub.SR_glass_base_color + , u_pub.SR_glass_diffuse_roughness + , u_pub.SR_glass_metalness + , u_pub.SR_glass_specular + , u_pub.SR_glass_specular_color + , u_pub.SR_glass_specular_roughness + , u_pub.SR_glass_specular_IOR + , u_pub.SR_glass_specular_anisotropy + , u_pub.SR_glass_specular_rotation + , u_pub.SR_glass_transmission + , u_pub.SR_glass_transmission_color + , u_pub.SR_glass_transmission_depth + , u_pub.SR_glass_transmission_scatter + , u_pub.SR_glass_transmission_scatter_anisotropy + , u_pub.SR_glass_transmission_dispersion + , u_pub.SR_glass_transmission_extra_roughness + , u_pub.SR_glass_subsurface + , u_pub.SR_glass_subsurface_color + , u_pub.SR_glass_subsurface_radius + , u_pub.SR_glass_subsurface_scale + , u_pub.SR_glass_subsurface_anisotropy + , u_pub.SR_glass_sheen + , u_pub.SR_glass_sheen_color + , u_pub.SR_glass_sheen_roughness + , u_pub.SR_glass_coat + , u_pub.SR_glass_coat_color + , u_pub.SR_glass_coat_roughness + , u_pub.SR_glass_coat_anisotropy + , u_pub.SR_glass_coat_rotation + , u_pub.SR_glass_coat_IOR + , u_pub.SR_glass_coat_affect_color + , u_pub.SR_glass_coat_affect_roughness + , u_pub.SR_glass_thin_film_thickness + , u_pub.SR_glass_thin_film_IOR + , u_pub.SR_glass_emission + , u_pub.SR_glass_emission_color + , u_pub.SR_glass_opacity + , u_pub.SR_glass_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Glass.msl.vert b/Materials/Examples/StandardSurface/Glass.msl.vert new file mode 100644 index 0000000000..86460fc6ad --- /dev/null +++ b/Materials/Examples/StandardSurface/Glass.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_glass'. Function already called in this scope. + // Omitted node 'Glass'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Glass.osl b/Materials/Examples/StandardSurface/Glass.osl new file mode 100644 index 0000000000..972016a03f --- /dev/null +++ b/Materials/Examples/StandardSurface/Glass.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Glass +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Glass" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_glass_base = 0.000000 + [[ + string widget = "number" + ]], + color SR_glass_base_color = color(0.800000, 0.800000, 0.800000), + float SR_glass_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_metalness = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_specular = 1.000000 + [[ + string widget = "number" + ]], + color SR_glass_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_glass_specular_roughness = 0.010000 + [[ + string widget = "number" + ]], + float SR_glass_specular_IOR = 1.520000 + [[ + string widget = "number" + ]], + float SR_glass_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_transmission = 1.000000 + [[ + string widget = "number" + ]], + color SR_glass_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_glass_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_glass_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_glass_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_glass_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_glass_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_glass_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_glass_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_glass_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_glass_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_glass_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_glass_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_glass_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_glass_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_glass_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_glass_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_glass_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_glass_opacity = color(1.000000, 1.000000, 1.000000), + int SR_glass_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_glass_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_glass_base, SR_glass_base_color, SR_glass_diffuse_roughness, SR_glass_metalness, SR_glass_specular, SR_glass_specular_color, SR_glass_specular_roughness, SR_glass_specular_IOR, SR_glass_specular_anisotropy, SR_glass_specular_rotation, SR_glass_transmission, SR_glass_transmission_color, SR_glass_transmission_depth, SR_glass_transmission_scatter, SR_glass_transmission_scatter_anisotropy, SR_glass_transmission_dispersion, SR_glass_transmission_extra_roughness, SR_glass_subsurface, SR_glass_subsurface_color, SR_glass_subsurface_radius, SR_glass_subsurface_scale, SR_glass_subsurface_anisotropy, SR_glass_sheen, SR_glass_sheen_color, SR_glass_sheen_roughness, SR_glass_coat, SR_glass_coat_color, SR_glass_coat_roughness, SR_glass_coat_anisotropy, SR_glass_coat_rotation, SR_glass_coat_IOR, geomprop_Nworld_out1, SR_glass_coat_affect_color, SR_glass_coat_affect_roughness, SR_glass_thin_film_thickness, SR_glass_thin_film_IOR, SR_glass_emission, SR_glass_emission_color, SR_glass_opacity, SR_glass_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_glass_out); + MATERIAL Glass_out = mx_surfacematerial(SR_glass_out, backsurfaceshader, displacementshader1); + out = Glass_out; +} + diff --git a/Materials/Examples/StandardSurface/GlassTinted.glsl.frag b/Materials/Examples/StandardSurface/GlassTinted.glsl.frag new file mode 100644 index 0000000000..fe1513aba4 --- /dev/null +++ b/Materials/Examples/StandardSurface/GlassTinted.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_glass_tinted_base = 0.000000; +uniform vec3 SR_glass_tinted_base_color = vec3(0.800000, 0.800000, 0.800000); +uniform float SR_glass_tinted_diffuse_roughness = 0.000000; +uniform float SR_glass_tinted_metalness = 0.000000; +uniform float SR_glass_tinted_specular = 1.000000; +uniform vec3 SR_glass_tinted_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_glass_tinted_specular_roughness = 0.150000; +uniform float SR_glass_tinted_specular_IOR = 1.540000; +uniform float SR_glass_tinted_specular_anisotropy = 0.000000; +uniform float SR_glass_tinted_specular_rotation = 0.000000; +uniform float SR_glass_tinted_transmission = 1.000000; +uniform vec3 SR_glass_tinted_transmission_color = vec3(0.200000, 0.100000, 1.000000); +uniform float SR_glass_tinted_transmission_depth = 0.000000; +uniform vec3 SR_glass_tinted_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_glass_tinted_transmission_scatter_anisotropy = 0.000000; +uniform float SR_glass_tinted_transmission_dispersion = 0.000000; +uniform float SR_glass_tinted_transmission_extra_roughness = 0.000000; +uniform float SR_glass_tinted_subsurface = 0.000000; +uniform vec3 SR_glass_tinted_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_glass_tinted_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_glass_tinted_subsurface_scale = 1.000000; +uniform float SR_glass_tinted_subsurface_anisotropy = 0.000000; +uniform float SR_glass_tinted_sheen = 0.000000; +uniform vec3 SR_glass_tinted_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_glass_tinted_sheen_roughness = 0.300000; +uniform float SR_glass_tinted_coat = 0.000000; +uniform vec3 SR_glass_tinted_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_glass_tinted_coat_roughness = 0.100000; +uniform float SR_glass_tinted_coat_anisotropy = 0.000000; +uniform float SR_glass_tinted_coat_rotation = 0.000000; +uniform float SR_glass_tinted_coat_IOR = 1.500000; +uniform float SR_glass_tinted_coat_affect_color = 0.000000; +uniform float SR_glass_tinted_coat_affect_roughness = 0.000000; +uniform float SR_glass_tinted_thin_film_thickness = 0.000000; +uniform float SR_glass_tinted_thin_film_IOR = 1.500000; +uniform float SR_glass_tinted_emission = 0.000000; +uniform vec3 SR_glass_tinted_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_glass_tinted_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_glass_tinted_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_glass_tinted_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_glass_tinted_base, SR_glass_tinted_base_color, SR_glass_tinted_diffuse_roughness, SR_glass_tinted_metalness, SR_glass_tinted_specular, SR_glass_tinted_specular_color, SR_glass_tinted_specular_roughness, SR_glass_tinted_specular_IOR, SR_glass_tinted_specular_anisotropy, SR_glass_tinted_specular_rotation, SR_glass_tinted_transmission, SR_glass_tinted_transmission_color, SR_glass_tinted_transmission_depth, SR_glass_tinted_transmission_scatter, SR_glass_tinted_transmission_scatter_anisotropy, SR_glass_tinted_transmission_dispersion, SR_glass_tinted_transmission_extra_roughness, SR_glass_tinted_subsurface, SR_glass_tinted_subsurface_color, SR_glass_tinted_subsurface_radius, SR_glass_tinted_subsurface_scale, SR_glass_tinted_subsurface_anisotropy, SR_glass_tinted_sheen, SR_glass_tinted_sheen_color, SR_glass_tinted_sheen_roughness, SR_glass_tinted_coat, SR_glass_tinted_coat_color, SR_glass_tinted_coat_roughness, SR_glass_tinted_coat_anisotropy, SR_glass_tinted_coat_rotation, SR_glass_tinted_coat_IOR, geomprop_Nworld_out1, SR_glass_tinted_coat_affect_color, SR_glass_tinted_coat_affect_roughness, SR_glass_tinted_thin_film_thickness, SR_glass_tinted_thin_film_IOR, SR_glass_tinted_emission, SR_glass_tinted_emission_color, SR_glass_tinted_opacity, SR_glass_tinted_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_glass_tinted_out); + material GlassTinted_out = SR_glass_tinted_out; + out1 = vec4(GlassTinted_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/GlassTinted.glsl.vert b/Materials/Examples/StandardSurface/GlassTinted.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/GlassTinted.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/GlassTinted.mdl b/Materials/Examples/StandardSurface/GlassTinted.mdl new file mode 100644 index 0000000000..c098a413d5 --- /dev/null +++ b/Materials/Examples/StandardSurface/GlassTinted.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material GlassTinted +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_glass_tinted_base = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/base") + ]], + color SR_glass_tinted_base_color = color(0.800000, 0.800000, 0.800000) + [[ + materialx::core::origin("SR_glass_tinted/base_color") + ]], + float SR_glass_tinted_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/diffuse_roughness") + ]], + float SR_glass_tinted_metalness = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/metalness") + ]], + float SR_glass_tinted_specular = 1.000000 + [[ + materialx::core::origin("SR_glass_tinted/specular") + ]], + color SR_glass_tinted_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass_tinted/specular_color") + ]], + float SR_glass_tinted_specular_roughness = 0.150000 + [[ + materialx::core::origin("SR_glass_tinted/specular_roughness") + ]], + uniform float SR_glass_tinted_specular_IOR = 1.540000 + [[ + materialx::core::origin("SR_glass_tinted/specular_IOR") + ]], + float SR_glass_tinted_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/specular_anisotropy") + ]], + float SR_glass_tinted_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/specular_rotation") + ]], + float SR_glass_tinted_transmission = 1.000000 + [[ + materialx::core::origin("SR_glass_tinted/transmission") + ]], + color SR_glass_tinted_transmission_color = color(0.200000, 0.100000, 1.000000) + [[ + materialx::core::origin("SR_glass_tinted/transmission_color") + ]], + float SR_glass_tinted_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/transmission_depth") + ]], + color SR_glass_tinted_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_glass_tinted/transmission_scatter") + ]], + float SR_glass_tinted_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/transmission_scatter_anisotropy") + ]], + float SR_glass_tinted_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/transmission_dispersion") + ]], + float SR_glass_tinted_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/transmission_extra_roughness") + ]], + float SR_glass_tinted_subsurface = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/subsurface") + ]], + color SR_glass_tinted_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass_tinted/subsurface_color") + ]], + color SR_glass_tinted_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass_tinted/subsurface_radius") + ]], + float SR_glass_tinted_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_glass_tinted/subsurface_scale") + ]], + float SR_glass_tinted_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/subsurface_anisotropy") + ]], + float SR_glass_tinted_sheen = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/sheen") + ]], + color SR_glass_tinted_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass_tinted/sheen_color") + ]], + float SR_glass_tinted_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_glass_tinted/sheen_roughness") + ]], + float SR_glass_tinted_coat = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/coat") + ]], + color SR_glass_tinted_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass_tinted/coat_color") + ]], + float SR_glass_tinted_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_glass_tinted/coat_roughness") + ]], + float SR_glass_tinted_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/coat_anisotropy") + ]], + float SR_glass_tinted_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/coat_rotation") + ]], + uniform float SR_glass_tinted_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_glass_tinted/coat_IOR") + ]], + float SR_glass_tinted_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/coat_affect_color") + ]], + float SR_glass_tinted_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/coat_affect_roughness") + ]], + float SR_glass_tinted_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/thin_film_thickness") + ]], + float SR_glass_tinted_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_glass_tinted/thin_film_IOR") + ]], + float SR_glass_tinted_emission = 0.000000 + [[ + materialx::core::origin("SR_glass_tinted/emission") + ]], + color SR_glass_tinted_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass_tinted/emission_color") + ]], + color SR_glass_tinted_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_glass_tinted/opacity") + ]], + bool SR_glass_tinted_thin_walled = false + [[ + materialx::core::origin("SR_glass_tinted/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_glass_tinted_out = NG_standard_surface_surfaceshader_100(SR_glass_tinted_base, SR_glass_tinted_base_color, SR_glass_tinted_diffuse_roughness, SR_glass_tinted_metalness, SR_glass_tinted_specular, SR_glass_tinted_specular_color, SR_glass_tinted_specular_roughness, SR_glass_tinted_specular_IOR, SR_glass_tinted_specular_anisotropy, SR_glass_tinted_specular_rotation, SR_glass_tinted_transmission, SR_glass_tinted_transmission_color, SR_glass_tinted_transmission_depth, SR_glass_tinted_transmission_scatter, SR_glass_tinted_transmission_scatter_anisotropy, SR_glass_tinted_transmission_dispersion, SR_glass_tinted_transmission_extra_roughness, SR_glass_tinted_subsurface, SR_glass_tinted_subsurface_color, SR_glass_tinted_subsurface_radius, SR_glass_tinted_subsurface_scale, SR_glass_tinted_subsurface_anisotropy, SR_glass_tinted_sheen, SR_glass_tinted_sheen_color, SR_glass_tinted_sheen_roughness, SR_glass_tinted_coat, SR_glass_tinted_coat_color, SR_glass_tinted_coat_roughness, SR_glass_tinted_coat_anisotropy, SR_glass_tinted_coat_rotation, SR_glass_tinted_coat_IOR, geomprop_Nworld_out1, SR_glass_tinted_coat_affect_color, SR_glass_tinted_coat_affect_roughness, SR_glass_tinted_thin_film_thickness, SR_glass_tinted_thin_film_IOR, SR_glass_tinted_emission, SR_glass_tinted_emission_color, SR_glass_tinted_opacity, SR_glass_tinted_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material GlassTinted_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_glass_tinted_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = GlassTinted_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/GlassTinted.msl.frag b/Materials/Examples/StandardSurface/GlassTinted.msl.frag new file mode 100644 index 0000000000..b3113c4424 --- /dev/null +++ b/Materials/Examples/StandardSurface/GlassTinted.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_glass_tinted_base; + vec3 SR_glass_tinted_base_color; + float SR_glass_tinted_diffuse_roughness; + float SR_glass_tinted_metalness; + float SR_glass_tinted_specular; + vec3 SR_glass_tinted_specular_color; + float SR_glass_tinted_specular_roughness; + float SR_glass_tinted_specular_IOR; + float SR_glass_tinted_specular_anisotropy; + float SR_glass_tinted_specular_rotation; + float SR_glass_tinted_transmission; + vec3 SR_glass_tinted_transmission_color; + float SR_glass_tinted_transmission_depth; + vec3 SR_glass_tinted_transmission_scatter; + float SR_glass_tinted_transmission_scatter_anisotropy; + float SR_glass_tinted_transmission_dispersion; + float SR_glass_tinted_transmission_extra_roughness; + float SR_glass_tinted_subsurface; + vec3 SR_glass_tinted_subsurface_color; + vec3 SR_glass_tinted_subsurface_radius; + float SR_glass_tinted_subsurface_scale; + float SR_glass_tinted_subsurface_anisotropy; + float SR_glass_tinted_sheen; + vec3 SR_glass_tinted_sheen_color; + float SR_glass_tinted_sheen_roughness; + float SR_glass_tinted_coat; + vec3 SR_glass_tinted_coat_color; + float SR_glass_tinted_coat_roughness; + float SR_glass_tinted_coat_anisotropy; + float SR_glass_tinted_coat_rotation; + float SR_glass_tinted_coat_IOR; + float SR_glass_tinted_coat_affect_color; + float SR_glass_tinted_coat_affect_roughness; + float SR_glass_tinted_thin_film_thickness; + float SR_glass_tinted_thin_film_IOR; + float SR_glass_tinted_emission; + vec3 SR_glass_tinted_emission_color; + vec3 SR_glass_tinted_opacity; + bool SR_glass_tinted_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_glass_tinted_base + + , vec3 SR_glass_tinted_base_color + + , float SR_glass_tinted_diffuse_roughness + + , float SR_glass_tinted_metalness + + , float SR_glass_tinted_specular + + , vec3 SR_glass_tinted_specular_color + + , float SR_glass_tinted_specular_roughness + + , float SR_glass_tinted_specular_IOR + + , float SR_glass_tinted_specular_anisotropy + + , float SR_glass_tinted_specular_rotation + + , float SR_glass_tinted_transmission + + , vec3 SR_glass_tinted_transmission_color + + , float SR_glass_tinted_transmission_depth + + , vec3 SR_glass_tinted_transmission_scatter + + , float SR_glass_tinted_transmission_scatter_anisotropy + + , float SR_glass_tinted_transmission_dispersion + + , float SR_glass_tinted_transmission_extra_roughness + + , float SR_glass_tinted_subsurface + + , vec3 SR_glass_tinted_subsurface_color + + , vec3 SR_glass_tinted_subsurface_radius + + , float SR_glass_tinted_subsurface_scale + + , float SR_glass_tinted_subsurface_anisotropy + + , float SR_glass_tinted_sheen + + , vec3 SR_glass_tinted_sheen_color + + , float SR_glass_tinted_sheen_roughness + + , float SR_glass_tinted_coat + + , vec3 SR_glass_tinted_coat_color + + , float SR_glass_tinted_coat_roughness + + , float SR_glass_tinted_coat_anisotropy + + , float SR_glass_tinted_coat_rotation + + , float SR_glass_tinted_coat_IOR + + , float SR_glass_tinted_coat_affect_color + + , float SR_glass_tinted_coat_affect_roughness + + , float SR_glass_tinted_thin_film_thickness + + , float SR_glass_tinted_thin_film_IOR + + , float SR_glass_tinted_emission + + , vec3 SR_glass_tinted_emission_color + + , vec3 SR_glass_tinted_opacity + + , bool SR_glass_tinted_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_glass_tinted_base(SR_glass_tinted_base) + + , SR_glass_tinted_base_color(SR_glass_tinted_base_color) + + , SR_glass_tinted_diffuse_roughness(SR_glass_tinted_diffuse_roughness) + + , SR_glass_tinted_metalness(SR_glass_tinted_metalness) + + , SR_glass_tinted_specular(SR_glass_tinted_specular) + + , SR_glass_tinted_specular_color(SR_glass_tinted_specular_color) + + , SR_glass_tinted_specular_roughness(SR_glass_tinted_specular_roughness) + + , SR_glass_tinted_specular_IOR(SR_glass_tinted_specular_IOR) + + , SR_glass_tinted_specular_anisotropy(SR_glass_tinted_specular_anisotropy) + + , SR_glass_tinted_specular_rotation(SR_glass_tinted_specular_rotation) + + , SR_glass_tinted_transmission(SR_glass_tinted_transmission) + + , SR_glass_tinted_transmission_color(SR_glass_tinted_transmission_color) + + , SR_glass_tinted_transmission_depth(SR_glass_tinted_transmission_depth) + + , SR_glass_tinted_transmission_scatter(SR_glass_tinted_transmission_scatter) + + , SR_glass_tinted_transmission_scatter_anisotropy(SR_glass_tinted_transmission_scatter_anisotropy) + + , SR_glass_tinted_transmission_dispersion(SR_glass_tinted_transmission_dispersion) + + , SR_glass_tinted_transmission_extra_roughness(SR_glass_tinted_transmission_extra_roughness) + + , SR_glass_tinted_subsurface(SR_glass_tinted_subsurface) + + , SR_glass_tinted_subsurface_color(SR_glass_tinted_subsurface_color) + + , SR_glass_tinted_subsurface_radius(SR_glass_tinted_subsurface_radius) + + , SR_glass_tinted_subsurface_scale(SR_glass_tinted_subsurface_scale) + + , SR_glass_tinted_subsurface_anisotropy(SR_glass_tinted_subsurface_anisotropy) + + , SR_glass_tinted_sheen(SR_glass_tinted_sheen) + + , SR_glass_tinted_sheen_color(SR_glass_tinted_sheen_color) + + , SR_glass_tinted_sheen_roughness(SR_glass_tinted_sheen_roughness) + + , SR_glass_tinted_coat(SR_glass_tinted_coat) + + , SR_glass_tinted_coat_color(SR_glass_tinted_coat_color) + + , SR_glass_tinted_coat_roughness(SR_glass_tinted_coat_roughness) + + , SR_glass_tinted_coat_anisotropy(SR_glass_tinted_coat_anisotropy) + + , SR_glass_tinted_coat_rotation(SR_glass_tinted_coat_rotation) + + , SR_glass_tinted_coat_IOR(SR_glass_tinted_coat_IOR) + + , SR_glass_tinted_coat_affect_color(SR_glass_tinted_coat_affect_color) + + , SR_glass_tinted_coat_affect_roughness(SR_glass_tinted_coat_affect_roughness) + + , SR_glass_tinted_thin_film_thickness(SR_glass_tinted_thin_film_thickness) + + , SR_glass_tinted_thin_film_IOR(SR_glass_tinted_thin_film_IOR) + + , SR_glass_tinted_emission(SR_glass_tinted_emission) + + , SR_glass_tinted_emission_color(SR_glass_tinted_emission_color) + + , SR_glass_tinted_opacity(SR_glass_tinted_opacity) + + , SR_glass_tinted_thin_walled(SR_glass_tinted_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_glass_tinted_base; + + + vec3 SR_glass_tinted_base_color; + + + float SR_glass_tinted_diffuse_roughness; + + + float SR_glass_tinted_metalness; + + + float SR_glass_tinted_specular; + + + vec3 SR_glass_tinted_specular_color; + + + float SR_glass_tinted_specular_roughness; + + + float SR_glass_tinted_specular_IOR; + + + float SR_glass_tinted_specular_anisotropy; + + + float SR_glass_tinted_specular_rotation; + + + float SR_glass_tinted_transmission; + + + vec3 SR_glass_tinted_transmission_color; + + + float SR_glass_tinted_transmission_depth; + + + vec3 SR_glass_tinted_transmission_scatter; + + + float SR_glass_tinted_transmission_scatter_anisotropy; + + + float SR_glass_tinted_transmission_dispersion; + + + float SR_glass_tinted_transmission_extra_roughness; + + + float SR_glass_tinted_subsurface; + + + vec3 SR_glass_tinted_subsurface_color; + + + vec3 SR_glass_tinted_subsurface_radius; + + + float SR_glass_tinted_subsurface_scale; + + + float SR_glass_tinted_subsurface_anisotropy; + + + float SR_glass_tinted_sheen; + + + vec3 SR_glass_tinted_sheen_color; + + + float SR_glass_tinted_sheen_roughness; + + + float SR_glass_tinted_coat; + + + vec3 SR_glass_tinted_coat_color; + + + float SR_glass_tinted_coat_roughness; + + + float SR_glass_tinted_coat_anisotropy; + + + float SR_glass_tinted_coat_rotation; + + + float SR_glass_tinted_coat_IOR; + + + float SR_glass_tinted_coat_affect_color; + + + float SR_glass_tinted_coat_affect_roughness; + + + float SR_glass_tinted_thin_film_thickness; + + + float SR_glass_tinted_thin_film_IOR; + + + float SR_glass_tinted_emission; + + + vec3 SR_glass_tinted_emission_color; + + + vec3 SR_glass_tinted_opacity; + + + bool SR_glass_tinted_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_glass_tinted_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_glass_tinted_base, SR_glass_tinted_base_color, SR_glass_tinted_diffuse_roughness, SR_glass_tinted_metalness, SR_glass_tinted_specular, SR_glass_tinted_specular_color, SR_glass_tinted_specular_roughness, SR_glass_tinted_specular_IOR, SR_glass_tinted_specular_anisotropy, SR_glass_tinted_specular_rotation, SR_glass_tinted_transmission, SR_glass_tinted_transmission_color, SR_glass_tinted_transmission_depth, SR_glass_tinted_transmission_scatter, SR_glass_tinted_transmission_scatter_anisotropy, SR_glass_tinted_transmission_dispersion, SR_glass_tinted_transmission_extra_roughness, SR_glass_tinted_subsurface, SR_glass_tinted_subsurface_color, SR_glass_tinted_subsurface_radius, SR_glass_tinted_subsurface_scale, SR_glass_tinted_subsurface_anisotropy, SR_glass_tinted_sheen, SR_glass_tinted_sheen_color, SR_glass_tinted_sheen_roughness, SR_glass_tinted_coat, SR_glass_tinted_coat_color, SR_glass_tinted_coat_roughness, SR_glass_tinted_coat_anisotropy, SR_glass_tinted_coat_rotation, SR_glass_tinted_coat_IOR, geomprop_Nworld_out1, SR_glass_tinted_coat_affect_color, SR_glass_tinted_coat_affect_roughness, SR_glass_tinted_thin_film_thickness, SR_glass_tinted_thin_film_IOR, SR_glass_tinted_emission, SR_glass_tinted_emission_color, SR_glass_tinted_opacity, SR_glass_tinted_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_glass_tinted_out); + material GlassTinted_out = SR_glass_tinted_out; + out1 = float4(GlassTinted_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_glass_tinted_base + , u_pub.SR_glass_tinted_base_color + , u_pub.SR_glass_tinted_diffuse_roughness + , u_pub.SR_glass_tinted_metalness + , u_pub.SR_glass_tinted_specular + , u_pub.SR_glass_tinted_specular_color + , u_pub.SR_glass_tinted_specular_roughness + , u_pub.SR_glass_tinted_specular_IOR + , u_pub.SR_glass_tinted_specular_anisotropy + , u_pub.SR_glass_tinted_specular_rotation + , u_pub.SR_glass_tinted_transmission + , u_pub.SR_glass_tinted_transmission_color + , u_pub.SR_glass_tinted_transmission_depth + , u_pub.SR_glass_tinted_transmission_scatter + , u_pub.SR_glass_tinted_transmission_scatter_anisotropy + , u_pub.SR_glass_tinted_transmission_dispersion + , u_pub.SR_glass_tinted_transmission_extra_roughness + , u_pub.SR_glass_tinted_subsurface + , u_pub.SR_glass_tinted_subsurface_color + , u_pub.SR_glass_tinted_subsurface_radius + , u_pub.SR_glass_tinted_subsurface_scale + , u_pub.SR_glass_tinted_subsurface_anisotropy + , u_pub.SR_glass_tinted_sheen + , u_pub.SR_glass_tinted_sheen_color + , u_pub.SR_glass_tinted_sheen_roughness + , u_pub.SR_glass_tinted_coat + , u_pub.SR_glass_tinted_coat_color + , u_pub.SR_glass_tinted_coat_roughness + , u_pub.SR_glass_tinted_coat_anisotropy + , u_pub.SR_glass_tinted_coat_rotation + , u_pub.SR_glass_tinted_coat_IOR + , u_pub.SR_glass_tinted_coat_affect_color + , u_pub.SR_glass_tinted_coat_affect_roughness + , u_pub.SR_glass_tinted_thin_film_thickness + , u_pub.SR_glass_tinted_thin_film_IOR + , u_pub.SR_glass_tinted_emission + , u_pub.SR_glass_tinted_emission_color + , u_pub.SR_glass_tinted_opacity + , u_pub.SR_glass_tinted_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/GlassTinted.msl.vert b/Materials/Examples/StandardSurface/GlassTinted.msl.vert new file mode 100644 index 0000000000..718aa2001c --- /dev/null +++ b/Materials/Examples/StandardSurface/GlassTinted.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_glass_tinted'. Function already called in this scope. + // Omitted node 'GlassTinted'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/GlassTinted.osl b/Materials/Examples/StandardSurface/GlassTinted.osl new file mode 100644 index 0000000000..b5ab6b7969 --- /dev/null +++ b/Materials/Examples/StandardSurface/GlassTinted.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader GlassTinted +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "GlassTinted" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_glass_tinted_base = 0.000000 + [[ + string widget = "number" + ]], + color SR_glass_tinted_base_color = color(0.800000, 0.800000, 0.800000), + float SR_glass_tinted_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_metalness = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_specular = 1.000000 + [[ + string widget = "number" + ]], + color SR_glass_tinted_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_glass_tinted_specular_roughness = 0.150000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_specular_IOR = 1.540000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_transmission = 1.000000 + [[ + string widget = "number" + ]], + color SR_glass_tinted_transmission_color = color(0.200000, 0.100000, 1.000000), + float SR_glass_tinted_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_glass_tinted_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_glass_tinted_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_glass_tinted_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_glass_tinted_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_glass_tinted_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_glass_tinted_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_glass_tinted_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_glass_tinted_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_glass_tinted_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_glass_tinted_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_glass_tinted_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_glass_tinted_opacity = color(1.000000, 1.000000, 1.000000), + int SR_glass_tinted_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_glass_tinted_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_glass_tinted_base, SR_glass_tinted_base_color, SR_glass_tinted_diffuse_roughness, SR_glass_tinted_metalness, SR_glass_tinted_specular, SR_glass_tinted_specular_color, SR_glass_tinted_specular_roughness, SR_glass_tinted_specular_IOR, SR_glass_tinted_specular_anisotropy, SR_glass_tinted_specular_rotation, SR_glass_tinted_transmission, SR_glass_tinted_transmission_color, SR_glass_tinted_transmission_depth, SR_glass_tinted_transmission_scatter, SR_glass_tinted_transmission_scatter_anisotropy, SR_glass_tinted_transmission_dispersion, SR_glass_tinted_transmission_extra_roughness, SR_glass_tinted_subsurface, SR_glass_tinted_subsurface_color, SR_glass_tinted_subsurface_radius, SR_glass_tinted_subsurface_scale, SR_glass_tinted_subsurface_anisotropy, SR_glass_tinted_sheen, SR_glass_tinted_sheen_color, SR_glass_tinted_sheen_roughness, SR_glass_tinted_coat, SR_glass_tinted_coat_color, SR_glass_tinted_coat_roughness, SR_glass_tinted_coat_anisotropy, SR_glass_tinted_coat_rotation, SR_glass_tinted_coat_IOR, geomprop_Nworld_out1, SR_glass_tinted_coat_affect_color, SR_glass_tinted_coat_affect_roughness, SR_glass_tinted_thin_film_thickness, SR_glass_tinted_thin_film_IOR, SR_glass_tinted_emission, SR_glass_tinted_emission_color, SR_glass_tinted_opacity, SR_glass_tinted_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_glass_tinted_out); + MATERIAL GlassTinted_out = mx_surfacematerial(SR_glass_tinted_out, backsurfaceshader, displacementshader1); + out = GlassTinted_out; +} + diff --git a/Materials/Examples/StandardSurface/Gold.glsl.frag b/Materials/Examples/StandardSurface/Gold.glsl.frag new file mode 100644 index 0000000000..f509fff19f --- /dev/null +++ b/Materials/Examples/StandardSurface/Gold.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_gold_base = 1.000000; +uniform vec3 SR_gold_base_color = vec3(0.944000, 0.776000, 0.373000); +uniform float SR_gold_diffuse_roughness = 0.000000; +uniform float SR_gold_metalness = 1.000000; +uniform float SR_gold_specular = 1.000000; +uniform vec3 SR_gold_specular_color = vec3(0.998000, 0.981000, 0.751000); +uniform float SR_gold_specular_roughness = 0.020000; +uniform float SR_gold_specular_IOR = 1.500000; +uniform float SR_gold_specular_anisotropy = 0.000000; +uniform float SR_gold_specular_rotation = 0.000000; +uniform float SR_gold_transmission = 0.000000; +uniform vec3 SR_gold_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_gold_transmission_depth = 0.000000; +uniform vec3 SR_gold_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_gold_transmission_scatter_anisotropy = 0.000000; +uniform float SR_gold_transmission_dispersion = 0.000000; +uniform float SR_gold_transmission_extra_roughness = 0.000000; +uniform float SR_gold_subsurface = 0.000000; +uniform vec3 SR_gold_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_gold_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_gold_subsurface_scale = 1.000000; +uniform float SR_gold_subsurface_anisotropy = 0.000000; +uniform float SR_gold_sheen = 0.000000; +uniform vec3 SR_gold_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_gold_sheen_roughness = 0.300000; +uniform float SR_gold_coat = 0.000000; +uniform vec3 SR_gold_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_gold_coat_roughness = 0.100000; +uniform float SR_gold_coat_anisotropy = 0.000000; +uniform float SR_gold_coat_rotation = 0.000000; +uniform float SR_gold_coat_IOR = 1.500000; +uniform float SR_gold_coat_affect_color = 0.000000; +uniform float SR_gold_coat_affect_roughness = 0.000000; +uniform float SR_gold_thin_film_thickness = 0.000000; +uniform float SR_gold_thin_film_IOR = 1.500000; +uniform float SR_gold_emission = 0.000000; +uniform vec3 SR_gold_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_gold_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_gold_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_gold_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_gold_base, SR_gold_base_color, SR_gold_diffuse_roughness, SR_gold_metalness, SR_gold_specular, SR_gold_specular_color, SR_gold_specular_roughness, SR_gold_specular_IOR, SR_gold_specular_anisotropy, SR_gold_specular_rotation, SR_gold_transmission, SR_gold_transmission_color, SR_gold_transmission_depth, SR_gold_transmission_scatter, SR_gold_transmission_scatter_anisotropy, SR_gold_transmission_dispersion, SR_gold_transmission_extra_roughness, SR_gold_subsurface, SR_gold_subsurface_color, SR_gold_subsurface_radius, SR_gold_subsurface_scale, SR_gold_subsurface_anisotropy, SR_gold_sheen, SR_gold_sheen_color, SR_gold_sheen_roughness, SR_gold_coat, SR_gold_coat_color, SR_gold_coat_roughness, SR_gold_coat_anisotropy, SR_gold_coat_rotation, SR_gold_coat_IOR, geomprop_Nworld_out1, SR_gold_coat_affect_color, SR_gold_coat_affect_roughness, SR_gold_thin_film_thickness, SR_gold_thin_film_IOR, SR_gold_emission, SR_gold_emission_color, SR_gold_opacity, SR_gold_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_gold_out); + material Gold_out = SR_gold_out; + out1 = vec4(Gold_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Gold.glsl.vert b/Materials/Examples/StandardSurface/Gold.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/Gold.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Gold.mdl b/Materials/Examples/StandardSurface/Gold.mdl new file mode 100644 index 0000000000..1f4f01bcfa --- /dev/null +++ b/Materials/Examples/StandardSurface/Gold.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Gold +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_gold_base = 1.000000 + [[ + materialx::core::origin("SR_gold/base") + ]], + color SR_gold_base_color = color(0.944000, 0.776000, 0.373000) + [[ + materialx::core::origin("SR_gold/base_color") + ]], + float SR_gold_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_gold/diffuse_roughness") + ]], + float SR_gold_metalness = 1.000000 + [[ + materialx::core::origin("SR_gold/metalness") + ]], + float SR_gold_specular = 1.000000 + [[ + materialx::core::origin("SR_gold/specular") + ]], + color SR_gold_specular_color = color(0.998000, 0.981000, 0.751000) + [[ + materialx::core::origin("SR_gold/specular_color") + ]], + float SR_gold_specular_roughness = 0.020000 + [[ + materialx::core::origin("SR_gold/specular_roughness") + ]], + uniform float SR_gold_specular_IOR = 1.500000 + [[ + materialx::core::origin("SR_gold/specular_IOR") + ]], + float SR_gold_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_gold/specular_anisotropy") + ]], + float SR_gold_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_gold/specular_rotation") + ]], + float SR_gold_transmission = 0.000000 + [[ + materialx::core::origin("SR_gold/transmission") + ]], + color SR_gold_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_gold/transmission_color") + ]], + float SR_gold_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_gold/transmission_depth") + ]], + color SR_gold_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_gold/transmission_scatter") + ]], + float SR_gold_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_gold/transmission_scatter_anisotropy") + ]], + float SR_gold_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_gold/transmission_dispersion") + ]], + float SR_gold_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_gold/transmission_extra_roughness") + ]], + float SR_gold_subsurface = 0.000000 + [[ + materialx::core::origin("SR_gold/subsurface") + ]], + color SR_gold_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_gold/subsurface_color") + ]], + color SR_gold_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_gold/subsurface_radius") + ]], + float SR_gold_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_gold/subsurface_scale") + ]], + float SR_gold_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_gold/subsurface_anisotropy") + ]], + float SR_gold_sheen = 0.000000 + [[ + materialx::core::origin("SR_gold/sheen") + ]], + color SR_gold_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_gold/sheen_color") + ]], + float SR_gold_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_gold/sheen_roughness") + ]], + float SR_gold_coat = 0.000000 + [[ + materialx::core::origin("SR_gold/coat") + ]], + color SR_gold_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_gold/coat_color") + ]], + float SR_gold_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_gold/coat_roughness") + ]], + float SR_gold_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_gold/coat_anisotropy") + ]], + float SR_gold_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_gold/coat_rotation") + ]], + uniform float SR_gold_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_gold/coat_IOR") + ]], + float SR_gold_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_gold/coat_affect_color") + ]], + float SR_gold_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_gold/coat_affect_roughness") + ]], + float SR_gold_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_gold/thin_film_thickness") + ]], + float SR_gold_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_gold/thin_film_IOR") + ]], + float SR_gold_emission = 0.000000 + [[ + materialx::core::origin("SR_gold/emission") + ]], + color SR_gold_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_gold/emission_color") + ]], + color SR_gold_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_gold/opacity") + ]], + bool SR_gold_thin_walled = false + [[ + materialx::core::origin("SR_gold/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_gold_out = NG_standard_surface_surfaceshader_100(SR_gold_base, SR_gold_base_color, SR_gold_diffuse_roughness, SR_gold_metalness, SR_gold_specular, SR_gold_specular_color, SR_gold_specular_roughness, SR_gold_specular_IOR, SR_gold_specular_anisotropy, SR_gold_specular_rotation, SR_gold_transmission, SR_gold_transmission_color, SR_gold_transmission_depth, SR_gold_transmission_scatter, SR_gold_transmission_scatter_anisotropy, SR_gold_transmission_dispersion, SR_gold_transmission_extra_roughness, SR_gold_subsurface, SR_gold_subsurface_color, SR_gold_subsurface_radius, SR_gold_subsurface_scale, SR_gold_subsurface_anisotropy, SR_gold_sheen, SR_gold_sheen_color, SR_gold_sheen_roughness, SR_gold_coat, SR_gold_coat_color, SR_gold_coat_roughness, SR_gold_coat_anisotropy, SR_gold_coat_rotation, SR_gold_coat_IOR, geomprop_Nworld_out1, SR_gold_coat_affect_color, SR_gold_coat_affect_roughness, SR_gold_thin_film_thickness, SR_gold_thin_film_IOR, SR_gold_emission, SR_gold_emission_color, SR_gold_opacity, SR_gold_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Gold_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_gold_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Gold_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Gold.msl.frag b/Materials/Examples/StandardSurface/Gold.msl.frag new file mode 100644 index 0000000000..0e0c2e490e --- /dev/null +++ b/Materials/Examples/StandardSurface/Gold.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_gold_base; + vec3 SR_gold_base_color; + float SR_gold_diffuse_roughness; + float SR_gold_metalness; + float SR_gold_specular; + vec3 SR_gold_specular_color; + float SR_gold_specular_roughness; + float SR_gold_specular_IOR; + float SR_gold_specular_anisotropy; + float SR_gold_specular_rotation; + float SR_gold_transmission; + vec3 SR_gold_transmission_color; + float SR_gold_transmission_depth; + vec3 SR_gold_transmission_scatter; + float SR_gold_transmission_scatter_anisotropy; + float SR_gold_transmission_dispersion; + float SR_gold_transmission_extra_roughness; + float SR_gold_subsurface; + vec3 SR_gold_subsurface_color; + vec3 SR_gold_subsurface_radius; + float SR_gold_subsurface_scale; + float SR_gold_subsurface_anisotropy; + float SR_gold_sheen; + vec3 SR_gold_sheen_color; + float SR_gold_sheen_roughness; + float SR_gold_coat; + vec3 SR_gold_coat_color; + float SR_gold_coat_roughness; + float SR_gold_coat_anisotropy; + float SR_gold_coat_rotation; + float SR_gold_coat_IOR; + float SR_gold_coat_affect_color; + float SR_gold_coat_affect_roughness; + float SR_gold_thin_film_thickness; + float SR_gold_thin_film_IOR; + float SR_gold_emission; + vec3 SR_gold_emission_color; + vec3 SR_gold_opacity; + bool SR_gold_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_gold_base + + , vec3 SR_gold_base_color + + , float SR_gold_diffuse_roughness + + , float SR_gold_metalness + + , float SR_gold_specular + + , vec3 SR_gold_specular_color + + , float SR_gold_specular_roughness + + , float SR_gold_specular_IOR + + , float SR_gold_specular_anisotropy + + , float SR_gold_specular_rotation + + , float SR_gold_transmission + + , vec3 SR_gold_transmission_color + + , float SR_gold_transmission_depth + + , vec3 SR_gold_transmission_scatter + + , float SR_gold_transmission_scatter_anisotropy + + , float SR_gold_transmission_dispersion + + , float SR_gold_transmission_extra_roughness + + , float SR_gold_subsurface + + , vec3 SR_gold_subsurface_color + + , vec3 SR_gold_subsurface_radius + + , float SR_gold_subsurface_scale + + , float SR_gold_subsurface_anisotropy + + , float SR_gold_sheen + + , vec3 SR_gold_sheen_color + + , float SR_gold_sheen_roughness + + , float SR_gold_coat + + , vec3 SR_gold_coat_color + + , float SR_gold_coat_roughness + + , float SR_gold_coat_anisotropy + + , float SR_gold_coat_rotation + + , float SR_gold_coat_IOR + + , float SR_gold_coat_affect_color + + , float SR_gold_coat_affect_roughness + + , float SR_gold_thin_film_thickness + + , float SR_gold_thin_film_IOR + + , float SR_gold_emission + + , vec3 SR_gold_emission_color + + , vec3 SR_gold_opacity + + , bool SR_gold_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_gold_base(SR_gold_base) + + , SR_gold_base_color(SR_gold_base_color) + + , SR_gold_diffuse_roughness(SR_gold_diffuse_roughness) + + , SR_gold_metalness(SR_gold_metalness) + + , SR_gold_specular(SR_gold_specular) + + , SR_gold_specular_color(SR_gold_specular_color) + + , SR_gold_specular_roughness(SR_gold_specular_roughness) + + , SR_gold_specular_IOR(SR_gold_specular_IOR) + + , SR_gold_specular_anisotropy(SR_gold_specular_anisotropy) + + , SR_gold_specular_rotation(SR_gold_specular_rotation) + + , SR_gold_transmission(SR_gold_transmission) + + , SR_gold_transmission_color(SR_gold_transmission_color) + + , SR_gold_transmission_depth(SR_gold_transmission_depth) + + , SR_gold_transmission_scatter(SR_gold_transmission_scatter) + + , SR_gold_transmission_scatter_anisotropy(SR_gold_transmission_scatter_anisotropy) + + , SR_gold_transmission_dispersion(SR_gold_transmission_dispersion) + + , SR_gold_transmission_extra_roughness(SR_gold_transmission_extra_roughness) + + , SR_gold_subsurface(SR_gold_subsurface) + + , SR_gold_subsurface_color(SR_gold_subsurface_color) + + , SR_gold_subsurface_radius(SR_gold_subsurface_radius) + + , SR_gold_subsurface_scale(SR_gold_subsurface_scale) + + , SR_gold_subsurface_anisotropy(SR_gold_subsurface_anisotropy) + + , SR_gold_sheen(SR_gold_sheen) + + , SR_gold_sheen_color(SR_gold_sheen_color) + + , SR_gold_sheen_roughness(SR_gold_sheen_roughness) + + , SR_gold_coat(SR_gold_coat) + + , SR_gold_coat_color(SR_gold_coat_color) + + , SR_gold_coat_roughness(SR_gold_coat_roughness) + + , SR_gold_coat_anisotropy(SR_gold_coat_anisotropy) + + , SR_gold_coat_rotation(SR_gold_coat_rotation) + + , SR_gold_coat_IOR(SR_gold_coat_IOR) + + , SR_gold_coat_affect_color(SR_gold_coat_affect_color) + + , SR_gold_coat_affect_roughness(SR_gold_coat_affect_roughness) + + , SR_gold_thin_film_thickness(SR_gold_thin_film_thickness) + + , SR_gold_thin_film_IOR(SR_gold_thin_film_IOR) + + , SR_gold_emission(SR_gold_emission) + + , SR_gold_emission_color(SR_gold_emission_color) + + , SR_gold_opacity(SR_gold_opacity) + + , SR_gold_thin_walled(SR_gold_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_gold_base; + + + vec3 SR_gold_base_color; + + + float SR_gold_diffuse_roughness; + + + float SR_gold_metalness; + + + float SR_gold_specular; + + + vec3 SR_gold_specular_color; + + + float SR_gold_specular_roughness; + + + float SR_gold_specular_IOR; + + + float SR_gold_specular_anisotropy; + + + float SR_gold_specular_rotation; + + + float SR_gold_transmission; + + + vec3 SR_gold_transmission_color; + + + float SR_gold_transmission_depth; + + + vec3 SR_gold_transmission_scatter; + + + float SR_gold_transmission_scatter_anisotropy; + + + float SR_gold_transmission_dispersion; + + + float SR_gold_transmission_extra_roughness; + + + float SR_gold_subsurface; + + + vec3 SR_gold_subsurface_color; + + + vec3 SR_gold_subsurface_radius; + + + float SR_gold_subsurface_scale; + + + float SR_gold_subsurface_anisotropy; + + + float SR_gold_sheen; + + + vec3 SR_gold_sheen_color; + + + float SR_gold_sheen_roughness; + + + float SR_gold_coat; + + + vec3 SR_gold_coat_color; + + + float SR_gold_coat_roughness; + + + float SR_gold_coat_anisotropy; + + + float SR_gold_coat_rotation; + + + float SR_gold_coat_IOR; + + + float SR_gold_coat_affect_color; + + + float SR_gold_coat_affect_roughness; + + + float SR_gold_thin_film_thickness; + + + float SR_gold_thin_film_IOR; + + + float SR_gold_emission; + + + vec3 SR_gold_emission_color; + + + vec3 SR_gold_opacity; + + + bool SR_gold_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_gold_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_gold_base, SR_gold_base_color, SR_gold_diffuse_roughness, SR_gold_metalness, SR_gold_specular, SR_gold_specular_color, SR_gold_specular_roughness, SR_gold_specular_IOR, SR_gold_specular_anisotropy, SR_gold_specular_rotation, SR_gold_transmission, SR_gold_transmission_color, SR_gold_transmission_depth, SR_gold_transmission_scatter, SR_gold_transmission_scatter_anisotropy, SR_gold_transmission_dispersion, SR_gold_transmission_extra_roughness, SR_gold_subsurface, SR_gold_subsurface_color, SR_gold_subsurface_radius, SR_gold_subsurface_scale, SR_gold_subsurface_anisotropy, SR_gold_sheen, SR_gold_sheen_color, SR_gold_sheen_roughness, SR_gold_coat, SR_gold_coat_color, SR_gold_coat_roughness, SR_gold_coat_anisotropy, SR_gold_coat_rotation, SR_gold_coat_IOR, geomprop_Nworld_out1, SR_gold_coat_affect_color, SR_gold_coat_affect_roughness, SR_gold_thin_film_thickness, SR_gold_thin_film_IOR, SR_gold_emission, SR_gold_emission_color, SR_gold_opacity, SR_gold_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_gold_out); + material Gold_out = SR_gold_out; + out1 = float4(Gold_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_gold_base + , u_pub.SR_gold_base_color + , u_pub.SR_gold_diffuse_roughness + , u_pub.SR_gold_metalness + , u_pub.SR_gold_specular + , u_pub.SR_gold_specular_color + , u_pub.SR_gold_specular_roughness + , u_pub.SR_gold_specular_IOR + , u_pub.SR_gold_specular_anisotropy + , u_pub.SR_gold_specular_rotation + , u_pub.SR_gold_transmission + , u_pub.SR_gold_transmission_color + , u_pub.SR_gold_transmission_depth + , u_pub.SR_gold_transmission_scatter + , u_pub.SR_gold_transmission_scatter_anisotropy + , u_pub.SR_gold_transmission_dispersion + , u_pub.SR_gold_transmission_extra_roughness + , u_pub.SR_gold_subsurface + , u_pub.SR_gold_subsurface_color + , u_pub.SR_gold_subsurface_radius + , u_pub.SR_gold_subsurface_scale + , u_pub.SR_gold_subsurface_anisotropy + , u_pub.SR_gold_sheen + , u_pub.SR_gold_sheen_color + , u_pub.SR_gold_sheen_roughness + , u_pub.SR_gold_coat + , u_pub.SR_gold_coat_color + , u_pub.SR_gold_coat_roughness + , u_pub.SR_gold_coat_anisotropy + , u_pub.SR_gold_coat_rotation + , u_pub.SR_gold_coat_IOR + , u_pub.SR_gold_coat_affect_color + , u_pub.SR_gold_coat_affect_roughness + , u_pub.SR_gold_thin_film_thickness + , u_pub.SR_gold_thin_film_IOR + , u_pub.SR_gold_emission + , u_pub.SR_gold_emission_color + , u_pub.SR_gold_opacity + , u_pub.SR_gold_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Gold.msl.vert b/Materials/Examples/StandardSurface/Gold.msl.vert new file mode 100644 index 0000000000..b162911f0c --- /dev/null +++ b/Materials/Examples/StandardSurface/Gold.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_gold'. Function already called in this scope. + // Omitted node 'Gold'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Gold.osl b/Materials/Examples/StandardSurface/Gold.osl new file mode 100644 index 0000000000..44b8fd04d3 --- /dev/null +++ b/Materials/Examples/StandardSurface/Gold.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Gold +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Gold" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_gold_base = 1.000000 + [[ + string widget = "number" + ]], + color SR_gold_base_color = color(0.944000, 0.776000, 0.373000), + float SR_gold_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_gold_metalness = 1.000000 + [[ + string widget = "number" + ]], + float SR_gold_specular = 1.000000 + [[ + string widget = "number" + ]], + color SR_gold_specular_color = color(0.998000, 0.981000, 0.751000), + float SR_gold_specular_roughness = 0.020000 + [[ + string widget = "number" + ]], + float SR_gold_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_gold_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_gold_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_gold_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_gold_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_gold_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_gold_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_gold_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_gold_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_gold_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_gold_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_gold_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_gold_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_gold_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_gold_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_gold_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_gold_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_gold_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_gold_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_gold_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_gold_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_gold_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_gold_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_gold_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_gold_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_gold_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_gold_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_gold_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_gold_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_gold_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_gold_opacity = color(1.000000, 1.000000, 1.000000), + int SR_gold_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_gold_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_gold_base, SR_gold_base_color, SR_gold_diffuse_roughness, SR_gold_metalness, SR_gold_specular, SR_gold_specular_color, SR_gold_specular_roughness, SR_gold_specular_IOR, SR_gold_specular_anisotropy, SR_gold_specular_rotation, SR_gold_transmission, SR_gold_transmission_color, SR_gold_transmission_depth, SR_gold_transmission_scatter, SR_gold_transmission_scatter_anisotropy, SR_gold_transmission_dispersion, SR_gold_transmission_extra_roughness, SR_gold_subsurface, SR_gold_subsurface_color, SR_gold_subsurface_radius, SR_gold_subsurface_scale, SR_gold_subsurface_anisotropy, SR_gold_sheen, SR_gold_sheen_color, SR_gold_sheen_roughness, SR_gold_coat, SR_gold_coat_color, SR_gold_coat_roughness, SR_gold_coat_anisotropy, SR_gold_coat_rotation, SR_gold_coat_IOR, geomprop_Nworld_out1, SR_gold_coat_affect_color, SR_gold_coat_affect_roughness, SR_gold_thin_film_thickness, SR_gold_thin_film_IOR, SR_gold_emission, SR_gold_emission_color, SR_gold_opacity, SR_gold_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_gold_out); + MATERIAL Gold_out = mx_surfacematerial(SR_gold_out, backsurfaceshader, displacementshader1); + out = Gold_out; +} + diff --git a/Materials/Examples/StandardSurface/Greysphere.glsl.frag b/Materials/Examples/StandardSurface/Greysphere.glsl.frag new file mode 100644 index 0000000000..ee49405121 --- /dev/null +++ b/Materials/Examples/StandardSurface/Greysphere.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_greysphere_base = 1.000000; +uniform vec3 SR_greysphere_base_color = vec3(0.180000, 0.180000, 0.180000); +uniform float SR_greysphere_diffuse_roughness = 0.000000; +uniform float SR_greysphere_metalness = 0.000000; +uniform float SR_greysphere_specular = 1.000000; +uniform vec3 SR_greysphere_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_greysphere_specular_roughness = 0.700000; +uniform float SR_greysphere_specular_IOR = 1.500000; +uniform float SR_greysphere_specular_anisotropy = 0.000000; +uniform float SR_greysphere_specular_rotation = 0.000000; +uniform float SR_greysphere_transmission = 0.000000; +uniform vec3 SR_greysphere_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_greysphere_transmission_depth = 0.000000; +uniform vec3 SR_greysphere_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_greysphere_transmission_scatter_anisotropy = 0.000000; +uniform float SR_greysphere_transmission_dispersion = 0.000000; +uniform float SR_greysphere_transmission_extra_roughness = 0.000000; +uniform float SR_greysphere_subsurface = 0.000000; +uniform vec3 SR_greysphere_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_greysphere_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_greysphere_subsurface_scale = 1.000000; +uniform float SR_greysphere_subsurface_anisotropy = 0.000000; +uniform float SR_greysphere_sheen = 0.000000; +uniform vec3 SR_greysphere_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_greysphere_sheen_roughness = 0.300000; +uniform float SR_greysphere_coat = 0.000000; +uniform vec3 SR_greysphere_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_greysphere_coat_roughness = 0.100000; +uniform float SR_greysphere_coat_anisotropy = 0.000000; +uniform float SR_greysphere_coat_rotation = 0.000000; +uniform float SR_greysphere_coat_IOR = 1.500000; +uniform float SR_greysphere_coat_affect_color = 0.000000; +uniform float SR_greysphere_coat_affect_roughness = 0.000000; +uniform float SR_greysphere_thin_film_thickness = 0.000000; +uniform float SR_greysphere_thin_film_IOR = 1.500000; +uniform float SR_greysphere_emission = 0.000000; +uniform vec3 SR_greysphere_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_greysphere_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_greysphere_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_greysphere_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_greysphere_base, SR_greysphere_base_color, SR_greysphere_diffuse_roughness, SR_greysphere_metalness, SR_greysphere_specular, SR_greysphere_specular_color, SR_greysphere_specular_roughness, SR_greysphere_specular_IOR, SR_greysphere_specular_anisotropy, SR_greysphere_specular_rotation, SR_greysphere_transmission, SR_greysphere_transmission_color, SR_greysphere_transmission_depth, SR_greysphere_transmission_scatter, SR_greysphere_transmission_scatter_anisotropy, SR_greysphere_transmission_dispersion, SR_greysphere_transmission_extra_roughness, SR_greysphere_subsurface, SR_greysphere_subsurface_color, SR_greysphere_subsurface_radius, SR_greysphere_subsurface_scale, SR_greysphere_subsurface_anisotropy, SR_greysphere_sheen, SR_greysphere_sheen_color, SR_greysphere_sheen_roughness, SR_greysphere_coat, SR_greysphere_coat_color, SR_greysphere_coat_roughness, SR_greysphere_coat_anisotropy, SR_greysphere_coat_rotation, SR_greysphere_coat_IOR, geomprop_Nworld_out1, SR_greysphere_coat_affect_color, SR_greysphere_coat_affect_roughness, SR_greysphere_thin_film_thickness, SR_greysphere_thin_film_IOR, SR_greysphere_emission, SR_greysphere_emission_color, SR_greysphere_opacity, SR_greysphere_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_greysphere_out); + material Greysphere_out = SR_greysphere_out; + out1 = vec4(Greysphere_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Greysphere.glsl.vert b/Materials/Examples/StandardSurface/Greysphere.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/Greysphere.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Greysphere.mdl b/Materials/Examples/StandardSurface/Greysphere.mdl new file mode 100644 index 0000000000..3fd5dff0eb --- /dev/null +++ b/Materials/Examples/StandardSurface/Greysphere.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Greysphere +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_greysphere_base = 1.000000 + [[ + materialx::core::origin("SR_greysphere/base") + ]], + color SR_greysphere_base_color = color(0.180000, 0.180000, 0.180000) + [[ + materialx::core::origin("SR_greysphere/base_color") + ]], + float SR_greysphere_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_greysphere/diffuse_roughness") + ]], + float SR_greysphere_metalness = 0.000000 + [[ + materialx::core::origin("SR_greysphere/metalness") + ]], + float SR_greysphere_specular = 1.000000 + [[ + materialx::core::origin("SR_greysphere/specular") + ]], + color SR_greysphere_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_greysphere/specular_color") + ]], + float SR_greysphere_specular_roughness = 0.700000 + [[ + materialx::core::origin("SR_greysphere/specular_roughness") + ]], + uniform float SR_greysphere_specular_IOR = 1.500000 + [[ + materialx::core::origin("SR_greysphere/specular_IOR") + ]], + float SR_greysphere_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_greysphere/specular_anisotropy") + ]], + float SR_greysphere_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_greysphere/specular_rotation") + ]], + float SR_greysphere_transmission = 0.000000 + [[ + materialx::core::origin("SR_greysphere/transmission") + ]], + color SR_greysphere_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_greysphere/transmission_color") + ]], + float SR_greysphere_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_greysphere/transmission_depth") + ]], + color SR_greysphere_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_greysphere/transmission_scatter") + ]], + float SR_greysphere_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_greysphere/transmission_scatter_anisotropy") + ]], + float SR_greysphere_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_greysphere/transmission_dispersion") + ]], + float SR_greysphere_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_greysphere/transmission_extra_roughness") + ]], + float SR_greysphere_subsurface = 0.000000 + [[ + materialx::core::origin("SR_greysphere/subsurface") + ]], + color SR_greysphere_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_greysphere/subsurface_color") + ]], + color SR_greysphere_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_greysphere/subsurface_radius") + ]], + float SR_greysphere_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_greysphere/subsurface_scale") + ]], + float SR_greysphere_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_greysphere/subsurface_anisotropy") + ]], + float SR_greysphere_sheen = 0.000000 + [[ + materialx::core::origin("SR_greysphere/sheen") + ]], + color SR_greysphere_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_greysphere/sheen_color") + ]], + float SR_greysphere_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_greysphere/sheen_roughness") + ]], + float SR_greysphere_coat = 0.000000 + [[ + materialx::core::origin("SR_greysphere/coat") + ]], + color SR_greysphere_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_greysphere/coat_color") + ]], + float SR_greysphere_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_greysphere/coat_roughness") + ]], + float SR_greysphere_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_greysphere/coat_anisotropy") + ]], + float SR_greysphere_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_greysphere/coat_rotation") + ]], + uniform float SR_greysphere_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_greysphere/coat_IOR") + ]], + float SR_greysphere_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_greysphere/coat_affect_color") + ]], + float SR_greysphere_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_greysphere/coat_affect_roughness") + ]], + float SR_greysphere_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_greysphere/thin_film_thickness") + ]], + float SR_greysphere_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_greysphere/thin_film_IOR") + ]], + float SR_greysphere_emission = 0.000000 + [[ + materialx::core::origin("SR_greysphere/emission") + ]], + color SR_greysphere_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_greysphere/emission_color") + ]], + color SR_greysphere_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_greysphere/opacity") + ]], + bool SR_greysphere_thin_walled = false + [[ + materialx::core::origin("SR_greysphere/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_greysphere_out = NG_standard_surface_surfaceshader_100(SR_greysphere_base, SR_greysphere_base_color, SR_greysphere_diffuse_roughness, SR_greysphere_metalness, SR_greysphere_specular, SR_greysphere_specular_color, SR_greysphere_specular_roughness, SR_greysphere_specular_IOR, SR_greysphere_specular_anisotropy, SR_greysphere_specular_rotation, SR_greysphere_transmission, SR_greysphere_transmission_color, SR_greysphere_transmission_depth, SR_greysphere_transmission_scatter, SR_greysphere_transmission_scatter_anisotropy, SR_greysphere_transmission_dispersion, SR_greysphere_transmission_extra_roughness, SR_greysphere_subsurface, SR_greysphere_subsurface_color, SR_greysphere_subsurface_radius, SR_greysphere_subsurface_scale, SR_greysphere_subsurface_anisotropy, SR_greysphere_sheen, SR_greysphere_sheen_color, SR_greysphere_sheen_roughness, SR_greysphere_coat, SR_greysphere_coat_color, SR_greysphere_coat_roughness, SR_greysphere_coat_anisotropy, SR_greysphere_coat_rotation, SR_greysphere_coat_IOR, geomprop_Nworld_out1, SR_greysphere_coat_affect_color, SR_greysphere_coat_affect_roughness, SR_greysphere_thin_film_thickness, SR_greysphere_thin_film_IOR, SR_greysphere_emission, SR_greysphere_emission_color, SR_greysphere_opacity, SR_greysphere_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Greysphere_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_greysphere_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Greysphere_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Greysphere.msl.frag b/Materials/Examples/StandardSurface/Greysphere.msl.frag new file mode 100644 index 0000000000..931e845d72 --- /dev/null +++ b/Materials/Examples/StandardSurface/Greysphere.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_greysphere_base; + vec3 SR_greysphere_base_color; + float SR_greysphere_diffuse_roughness; + float SR_greysphere_metalness; + float SR_greysphere_specular; + vec3 SR_greysphere_specular_color; + float SR_greysphere_specular_roughness; + float SR_greysphere_specular_IOR; + float SR_greysphere_specular_anisotropy; + float SR_greysphere_specular_rotation; + float SR_greysphere_transmission; + vec3 SR_greysphere_transmission_color; + float SR_greysphere_transmission_depth; + vec3 SR_greysphere_transmission_scatter; + float SR_greysphere_transmission_scatter_anisotropy; + float SR_greysphere_transmission_dispersion; + float SR_greysphere_transmission_extra_roughness; + float SR_greysphere_subsurface; + vec3 SR_greysphere_subsurface_color; + vec3 SR_greysphere_subsurface_radius; + float SR_greysphere_subsurface_scale; + float SR_greysphere_subsurface_anisotropy; + float SR_greysphere_sheen; + vec3 SR_greysphere_sheen_color; + float SR_greysphere_sheen_roughness; + float SR_greysphere_coat; + vec3 SR_greysphere_coat_color; + float SR_greysphere_coat_roughness; + float SR_greysphere_coat_anisotropy; + float SR_greysphere_coat_rotation; + float SR_greysphere_coat_IOR; + float SR_greysphere_coat_affect_color; + float SR_greysphere_coat_affect_roughness; + float SR_greysphere_thin_film_thickness; + float SR_greysphere_thin_film_IOR; + float SR_greysphere_emission; + vec3 SR_greysphere_emission_color; + vec3 SR_greysphere_opacity; + bool SR_greysphere_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_greysphere_base + + , vec3 SR_greysphere_base_color + + , float SR_greysphere_diffuse_roughness + + , float SR_greysphere_metalness + + , float SR_greysphere_specular + + , vec3 SR_greysphere_specular_color + + , float SR_greysphere_specular_roughness + + , float SR_greysphere_specular_IOR + + , float SR_greysphere_specular_anisotropy + + , float SR_greysphere_specular_rotation + + , float SR_greysphere_transmission + + , vec3 SR_greysphere_transmission_color + + , float SR_greysphere_transmission_depth + + , vec3 SR_greysphere_transmission_scatter + + , float SR_greysphere_transmission_scatter_anisotropy + + , float SR_greysphere_transmission_dispersion + + , float SR_greysphere_transmission_extra_roughness + + , float SR_greysphere_subsurface + + , vec3 SR_greysphere_subsurface_color + + , vec3 SR_greysphere_subsurface_radius + + , float SR_greysphere_subsurface_scale + + , float SR_greysphere_subsurface_anisotropy + + , float SR_greysphere_sheen + + , vec3 SR_greysphere_sheen_color + + , float SR_greysphere_sheen_roughness + + , float SR_greysphere_coat + + , vec3 SR_greysphere_coat_color + + , float SR_greysphere_coat_roughness + + , float SR_greysphere_coat_anisotropy + + , float SR_greysphere_coat_rotation + + , float SR_greysphere_coat_IOR + + , float SR_greysphere_coat_affect_color + + , float SR_greysphere_coat_affect_roughness + + , float SR_greysphere_thin_film_thickness + + , float SR_greysphere_thin_film_IOR + + , float SR_greysphere_emission + + , vec3 SR_greysphere_emission_color + + , vec3 SR_greysphere_opacity + + , bool SR_greysphere_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_greysphere_base(SR_greysphere_base) + + , SR_greysphere_base_color(SR_greysphere_base_color) + + , SR_greysphere_diffuse_roughness(SR_greysphere_diffuse_roughness) + + , SR_greysphere_metalness(SR_greysphere_metalness) + + , SR_greysphere_specular(SR_greysphere_specular) + + , SR_greysphere_specular_color(SR_greysphere_specular_color) + + , SR_greysphere_specular_roughness(SR_greysphere_specular_roughness) + + , SR_greysphere_specular_IOR(SR_greysphere_specular_IOR) + + , SR_greysphere_specular_anisotropy(SR_greysphere_specular_anisotropy) + + , SR_greysphere_specular_rotation(SR_greysphere_specular_rotation) + + , SR_greysphere_transmission(SR_greysphere_transmission) + + , SR_greysphere_transmission_color(SR_greysphere_transmission_color) + + , SR_greysphere_transmission_depth(SR_greysphere_transmission_depth) + + , SR_greysphere_transmission_scatter(SR_greysphere_transmission_scatter) + + , SR_greysphere_transmission_scatter_anisotropy(SR_greysphere_transmission_scatter_anisotropy) + + , SR_greysphere_transmission_dispersion(SR_greysphere_transmission_dispersion) + + , SR_greysphere_transmission_extra_roughness(SR_greysphere_transmission_extra_roughness) + + , SR_greysphere_subsurface(SR_greysphere_subsurface) + + , SR_greysphere_subsurface_color(SR_greysphere_subsurface_color) + + , SR_greysphere_subsurface_radius(SR_greysphere_subsurface_radius) + + , SR_greysphere_subsurface_scale(SR_greysphere_subsurface_scale) + + , SR_greysphere_subsurface_anisotropy(SR_greysphere_subsurface_anisotropy) + + , SR_greysphere_sheen(SR_greysphere_sheen) + + , SR_greysphere_sheen_color(SR_greysphere_sheen_color) + + , SR_greysphere_sheen_roughness(SR_greysphere_sheen_roughness) + + , SR_greysphere_coat(SR_greysphere_coat) + + , SR_greysphere_coat_color(SR_greysphere_coat_color) + + , SR_greysphere_coat_roughness(SR_greysphere_coat_roughness) + + , SR_greysphere_coat_anisotropy(SR_greysphere_coat_anisotropy) + + , SR_greysphere_coat_rotation(SR_greysphere_coat_rotation) + + , SR_greysphere_coat_IOR(SR_greysphere_coat_IOR) + + , SR_greysphere_coat_affect_color(SR_greysphere_coat_affect_color) + + , SR_greysphere_coat_affect_roughness(SR_greysphere_coat_affect_roughness) + + , SR_greysphere_thin_film_thickness(SR_greysphere_thin_film_thickness) + + , SR_greysphere_thin_film_IOR(SR_greysphere_thin_film_IOR) + + , SR_greysphere_emission(SR_greysphere_emission) + + , SR_greysphere_emission_color(SR_greysphere_emission_color) + + , SR_greysphere_opacity(SR_greysphere_opacity) + + , SR_greysphere_thin_walled(SR_greysphere_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_greysphere_base; + + + vec3 SR_greysphere_base_color; + + + float SR_greysphere_diffuse_roughness; + + + float SR_greysphere_metalness; + + + float SR_greysphere_specular; + + + vec3 SR_greysphere_specular_color; + + + float SR_greysphere_specular_roughness; + + + float SR_greysphere_specular_IOR; + + + float SR_greysphere_specular_anisotropy; + + + float SR_greysphere_specular_rotation; + + + float SR_greysphere_transmission; + + + vec3 SR_greysphere_transmission_color; + + + float SR_greysphere_transmission_depth; + + + vec3 SR_greysphere_transmission_scatter; + + + float SR_greysphere_transmission_scatter_anisotropy; + + + float SR_greysphere_transmission_dispersion; + + + float SR_greysphere_transmission_extra_roughness; + + + float SR_greysphere_subsurface; + + + vec3 SR_greysphere_subsurface_color; + + + vec3 SR_greysphere_subsurface_radius; + + + float SR_greysphere_subsurface_scale; + + + float SR_greysphere_subsurface_anisotropy; + + + float SR_greysphere_sheen; + + + vec3 SR_greysphere_sheen_color; + + + float SR_greysphere_sheen_roughness; + + + float SR_greysphere_coat; + + + vec3 SR_greysphere_coat_color; + + + float SR_greysphere_coat_roughness; + + + float SR_greysphere_coat_anisotropy; + + + float SR_greysphere_coat_rotation; + + + float SR_greysphere_coat_IOR; + + + float SR_greysphere_coat_affect_color; + + + float SR_greysphere_coat_affect_roughness; + + + float SR_greysphere_thin_film_thickness; + + + float SR_greysphere_thin_film_IOR; + + + float SR_greysphere_emission; + + + vec3 SR_greysphere_emission_color; + + + vec3 SR_greysphere_opacity; + + + bool SR_greysphere_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_greysphere_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_greysphere_base, SR_greysphere_base_color, SR_greysphere_diffuse_roughness, SR_greysphere_metalness, SR_greysphere_specular, SR_greysphere_specular_color, SR_greysphere_specular_roughness, SR_greysphere_specular_IOR, SR_greysphere_specular_anisotropy, SR_greysphere_specular_rotation, SR_greysphere_transmission, SR_greysphere_transmission_color, SR_greysphere_transmission_depth, SR_greysphere_transmission_scatter, SR_greysphere_transmission_scatter_anisotropy, SR_greysphere_transmission_dispersion, SR_greysphere_transmission_extra_roughness, SR_greysphere_subsurface, SR_greysphere_subsurface_color, SR_greysphere_subsurface_radius, SR_greysphere_subsurface_scale, SR_greysphere_subsurface_anisotropy, SR_greysphere_sheen, SR_greysphere_sheen_color, SR_greysphere_sheen_roughness, SR_greysphere_coat, SR_greysphere_coat_color, SR_greysphere_coat_roughness, SR_greysphere_coat_anisotropy, SR_greysphere_coat_rotation, SR_greysphere_coat_IOR, geomprop_Nworld_out1, SR_greysphere_coat_affect_color, SR_greysphere_coat_affect_roughness, SR_greysphere_thin_film_thickness, SR_greysphere_thin_film_IOR, SR_greysphere_emission, SR_greysphere_emission_color, SR_greysphere_opacity, SR_greysphere_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_greysphere_out); + material Greysphere_out = SR_greysphere_out; + out1 = float4(Greysphere_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_greysphere_base + , u_pub.SR_greysphere_base_color + , u_pub.SR_greysphere_diffuse_roughness + , u_pub.SR_greysphere_metalness + , u_pub.SR_greysphere_specular + , u_pub.SR_greysphere_specular_color + , u_pub.SR_greysphere_specular_roughness + , u_pub.SR_greysphere_specular_IOR + , u_pub.SR_greysphere_specular_anisotropy + , u_pub.SR_greysphere_specular_rotation + , u_pub.SR_greysphere_transmission + , u_pub.SR_greysphere_transmission_color + , u_pub.SR_greysphere_transmission_depth + , u_pub.SR_greysphere_transmission_scatter + , u_pub.SR_greysphere_transmission_scatter_anisotropy + , u_pub.SR_greysphere_transmission_dispersion + , u_pub.SR_greysphere_transmission_extra_roughness + , u_pub.SR_greysphere_subsurface + , u_pub.SR_greysphere_subsurface_color + , u_pub.SR_greysphere_subsurface_radius + , u_pub.SR_greysphere_subsurface_scale + , u_pub.SR_greysphere_subsurface_anisotropy + , u_pub.SR_greysphere_sheen + , u_pub.SR_greysphere_sheen_color + , u_pub.SR_greysphere_sheen_roughness + , u_pub.SR_greysphere_coat + , u_pub.SR_greysphere_coat_color + , u_pub.SR_greysphere_coat_roughness + , u_pub.SR_greysphere_coat_anisotropy + , u_pub.SR_greysphere_coat_rotation + , u_pub.SR_greysphere_coat_IOR + , u_pub.SR_greysphere_coat_affect_color + , u_pub.SR_greysphere_coat_affect_roughness + , u_pub.SR_greysphere_thin_film_thickness + , u_pub.SR_greysphere_thin_film_IOR + , u_pub.SR_greysphere_emission + , u_pub.SR_greysphere_emission_color + , u_pub.SR_greysphere_opacity + , u_pub.SR_greysphere_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Greysphere.msl.vert b/Materials/Examples/StandardSurface/Greysphere.msl.vert new file mode 100644 index 0000000000..9f1fb50bb7 --- /dev/null +++ b/Materials/Examples/StandardSurface/Greysphere.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_greysphere'. Function already called in this scope. + // Omitted node 'Greysphere'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Greysphere.osl b/Materials/Examples/StandardSurface/Greysphere.osl new file mode 100644 index 0000000000..4d505bb10a --- /dev/null +++ b/Materials/Examples/StandardSurface/Greysphere.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Greysphere +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Greysphere" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_greysphere_base = 1.000000 + [[ + string widget = "number" + ]], + color SR_greysphere_base_color = color(0.180000, 0.180000, 0.180000), + float SR_greysphere_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_metalness = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_specular = 1.000000 + [[ + string widget = "number" + ]], + color SR_greysphere_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_greysphere_specular_roughness = 0.700000 + [[ + string widget = "number" + ]], + float SR_greysphere_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_greysphere_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_greysphere_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_greysphere_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_greysphere_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_greysphere_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_greysphere_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_greysphere_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_greysphere_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_greysphere_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_greysphere_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_greysphere_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_greysphere_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_greysphere_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_greysphere_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_greysphere_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_greysphere_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_greysphere_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_greysphere_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_greysphere_opacity = color(1.000000, 1.000000, 1.000000), + int SR_greysphere_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_greysphere_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_greysphere_base, SR_greysphere_base_color, SR_greysphere_diffuse_roughness, SR_greysphere_metalness, SR_greysphere_specular, SR_greysphere_specular_color, SR_greysphere_specular_roughness, SR_greysphere_specular_IOR, SR_greysphere_specular_anisotropy, SR_greysphere_specular_rotation, SR_greysphere_transmission, SR_greysphere_transmission_color, SR_greysphere_transmission_depth, SR_greysphere_transmission_scatter, SR_greysphere_transmission_scatter_anisotropy, SR_greysphere_transmission_dispersion, SR_greysphere_transmission_extra_roughness, SR_greysphere_subsurface, SR_greysphere_subsurface_color, SR_greysphere_subsurface_radius, SR_greysphere_subsurface_scale, SR_greysphere_subsurface_anisotropy, SR_greysphere_sheen, SR_greysphere_sheen_color, SR_greysphere_sheen_roughness, SR_greysphere_coat, SR_greysphere_coat_color, SR_greysphere_coat_roughness, SR_greysphere_coat_anisotropy, SR_greysphere_coat_rotation, SR_greysphere_coat_IOR, geomprop_Nworld_out1, SR_greysphere_coat_affect_color, SR_greysphere_coat_affect_roughness, SR_greysphere_thin_film_thickness, SR_greysphere_thin_film_IOR, SR_greysphere_emission, SR_greysphere_emission_color, SR_greysphere_opacity, SR_greysphere_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_greysphere_out); + MATERIAL Greysphere_out = mx_surfacematerial(SR_greysphere_out, backsurfaceshader, displacementshader1); + out = Greysphere_out; +} + diff --git a/Materials/Examples/StandardSurface/Greysphere_Calibration.glsl.frag b/Materials/Examples/StandardSurface/Greysphere_Calibration.glsl.frag new file mode 100644 index 0000000000..ff7e74b2c2 --- /dev/null +++ b/Materials/Examples/StandardSurface/Greysphere_Calibration.glsl.frag @@ -0,0 +1,1956 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int texcoord1_index = 0; +uniform vec2 place2d_pivot = vec2(0.500000, 0.500000); +uniform vec2 place2d_scale = vec2(0.210000, 0.210000); +uniform float place2d_rotate = 0.000000; +uniform vec2 place2d_offset = vec2(-1.660000, -0.490000); +uniform int place2d_operationorder = 0; +uniform sampler2D image1_file; +uniform int image1_layer = 0; +uniform vec3 image1_default = vec3(0.000000, 0.000000, 0.000000); +uniform int image1_uaddressmode = 1; +uniform int image1_vaddressmode = 1; +uniform int image1_filtertype = 1; +uniform int image1_framerange = 0; +uniform int image1_frameoffset = 0; +uniform int image1_frameendaction = 0; +uniform vec2 image1_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 image1_uv_offset = vec2(0.000000, 0.000000); +uniform float SR_Greysphere_Calibration_base = 1.000000; +uniform float SR_Greysphere_Calibration_diffuse_roughness = 0.000000; +uniform float SR_Greysphere_Calibration_metalness = 0.000000; +uniform float SR_Greysphere_Calibration_specular = 1.000000; +uniform vec3 SR_Greysphere_Calibration_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_Greysphere_Calibration_specular_roughness = 0.700000; +uniform float SR_Greysphere_Calibration_specular_IOR = 1.500000; +uniform float SR_Greysphere_Calibration_specular_anisotropy = 0.000000; +uniform float SR_Greysphere_Calibration_specular_rotation = 0.000000; +uniform float SR_Greysphere_Calibration_transmission = 0.000000; +uniform vec3 SR_Greysphere_Calibration_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_Greysphere_Calibration_transmission_depth = 0.000000; +uniform vec3 SR_Greysphere_Calibration_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_Greysphere_Calibration_transmission_scatter_anisotropy = 0.000000; +uniform float SR_Greysphere_Calibration_transmission_dispersion = 0.000000; +uniform float SR_Greysphere_Calibration_transmission_extra_roughness = 0.000000; +uniform float SR_Greysphere_Calibration_subsurface = 0.000000; +uniform vec3 SR_Greysphere_Calibration_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_Greysphere_Calibration_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_Greysphere_Calibration_subsurface_scale = 1.000000; +uniform float SR_Greysphere_Calibration_subsurface_anisotropy = 0.000000; +uniform float SR_Greysphere_Calibration_sheen = 0.000000; +uniform vec3 SR_Greysphere_Calibration_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_Greysphere_Calibration_sheen_roughness = 0.300000; +uniform float SR_Greysphere_Calibration_coat = 0.000000; +uniform vec3 SR_Greysphere_Calibration_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_Greysphere_Calibration_coat_roughness = 0.100000; +uniform float SR_Greysphere_Calibration_coat_anisotropy = 0.000000; +uniform float SR_Greysphere_Calibration_coat_rotation = 0.000000; +uniform float SR_Greysphere_Calibration_coat_IOR = 1.500000; +uniform float SR_Greysphere_Calibration_coat_affect_color = 0.000000; +uniform float SR_Greysphere_Calibration_coat_affect_roughness = 0.000000; +uniform float SR_Greysphere_Calibration_thin_film_thickness = 0.000000; +uniform float SR_Greysphere_Calibration_thin_film_IOR = 1.500000; +uniform float SR_Greysphere_Calibration_emission = 0.000000; +uniform vec3 SR_Greysphere_Calibration_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_Greysphere_Calibration_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_Greysphere_Calibration_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_rotate_vector2(vec2 _in, float amount, out vec2 result) +{ + float rotationRadians = mx_radians(amount); + float sa = mx_sin(rotationRadians); + float ca = mx_cos(rotationRadians); + result = vec2(ca*_in.x + sa*_in.y, -sa*_in.x + ca*_in.y); +} + +void NG_switch_vector2I(vec2 in1, vec2 in2, vec2 in3, vec2 in4, vec2 in5, vec2 in6, vec2 in7, vec2 in8, vec2 in9, vec2 in10, int which, out vec2 out1) +{ + const int ifgreater_10_value1_tmp = 10; + const vec2 ifgreater_10_in2_tmp = vec2(0.000000, 0.000000); + vec2 ifgreater_10_out = (ifgreater_10_value1_tmp > which) ? in10 : ifgreater_10_in2_tmp; + const int ifgreater_9_value1_tmp = 9; + vec2 ifgreater_9_out = (ifgreater_9_value1_tmp > which) ? in9 : ifgreater_10_out; + const int ifgreater_8_value1_tmp = 8; + vec2 ifgreater_8_out = (ifgreater_8_value1_tmp > which) ? in8 : ifgreater_9_out; + const int ifgreater_7_value1_tmp = 7; + vec2 ifgreater_7_out = (ifgreater_7_value1_tmp > which) ? in7 : ifgreater_8_out; + const int ifgreater_6_value1_tmp = 6; + vec2 ifgreater_6_out = (ifgreater_6_value1_tmp > which) ? in6 : ifgreater_7_out; + const int ifgreater_5_value1_tmp = 5; + vec2 ifgreater_5_out = (ifgreater_5_value1_tmp > which) ? in5 : ifgreater_6_out; + const int ifgreater_4_value1_tmp = 4; + vec2 ifgreater_4_out = (ifgreater_4_value1_tmp > which) ? in4 : ifgreater_5_out; + const int ifgreater_3_value1_tmp = 3; + vec2 ifgreater_3_out = (ifgreater_3_value1_tmp > which) ? in3 : ifgreater_4_out; + const int ifgreater_2_value1_tmp = 2; + vec2 ifgreater_2_out = (ifgreater_2_value1_tmp > which) ? in2 : ifgreater_3_out; + const int ifgreater_1_value1_tmp = 1; + vec2 ifgreater_1_out = (ifgreater_1_value1_tmp > which) ? in1 : ifgreater_2_out; + out1 = ifgreater_1_out; +} + +void NG_place2d_vector2(vec2 texcoord1, vec2 pivot, vec2 scale, float rotate, vec2 offset, int operationorder, out vec2 out1) +{ + vec2 N_subpivot_out = texcoord1 - pivot; + vec2 N_applyscale_out = N_subpivot_out / scale; + vec2 N_applyoffset2_out = N_subpivot_out - offset; + vec2 N_applyrot_out = vec2(0.0); + mx_rotate_vector2(N_applyscale_out, rotate, N_applyrot_out); + vec2 N_applyrot2_out = vec2(0.0); + mx_rotate_vector2(N_applyoffset2_out, rotate, N_applyrot2_out); + vec2 N_applyoffset_out = N_applyrot_out - offset; + vec2 N_applyscale2_out = N_applyrot2_out / scale; + vec2 N_addpivot_out = N_applyoffset_out + pivot; + vec2 N_addpivot2_out = N_applyscale2_out + pivot; + vec2 N_switch_operationorder_out = vec2(0.0); + NG_switch_vector2I(N_addpivot_out, N_addpivot2_out, vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), operationorder, N_switch_operationorder_out); + out1 = N_switch_operationorder_out; +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 texcoord1_out = vd.texcoord_0.xy; + vec2 place2d_out = vec2(0.0); + NG_place2d_vector2(texcoord1_out, place2d_pivot, place2d_scale, place2d_rotate, place2d_offset, place2d_operationorder, place2d_out); + vec3 image1_out = vec3(0.0); + mx_image_color3(image1_file, image1_layer, image1_default, place2d_out, image1_uaddressmode, image1_vaddressmode, image1_filtertype, image1_framerange, image1_frameoffset, image1_frameendaction, image1_uv_scale, image1_uv_offset, image1_out); + surfaceshader SR_Greysphere_Calibration_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_Greysphere_Calibration_base, image1_out, SR_Greysphere_Calibration_diffuse_roughness, SR_Greysphere_Calibration_metalness, SR_Greysphere_Calibration_specular, SR_Greysphere_Calibration_specular_color, SR_Greysphere_Calibration_specular_roughness, SR_Greysphere_Calibration_specular_IOR, SR_Greysphere_Calibration_specular_anisotropy, SR_Greysphere_Calibration_specular_rotation, SR_Greysphere_Calibration_transmission, SR_Greysphere_Calibration_transmission_color, SR_Greysphere_Calibration_transmission_depth, SR_Greysphere_Calibration_transmission_scatter, SR_Greysphere_Calibration_transmission_scatter_anisotropy, SR_Greysphere_Calibration_transmission_dispersion, SR_Greysphere_Calibration_transmission_extra_roughness, SR_Greysphere_Calibration_subsurface, SR_Greysphere_Calibration_subsurface_color, SR_Greysphere_Calibration_subsurface_radius, SR_Greysphere_Calibration_subsurface_scale, SR_Greysphere_Calibration_subsurface_anisotropy, SR_Greysphere_Calibration_sheen, SR_Greysphere_Calibration_sheen_color, SR_Greysphere_Calibration_sheen_roughness, SR_Greysphere_Calibration_coat, SR_Greysphere_Calibration_coat_color, SR_Greysphere_Calibration_coat_roughness, SR_Greysphere_Calibration_coat_anisotropy, SR_Greysphere_Calibration_coat_rotation, SR_Greysphere_Calibration_coat_IOR, geomprop_Nworld_out1, SR_Greysphere_Calibration_coat_affect_color, SR_Greysphere_Calibration_coat_affect_roughness, SR_Greysphere_Calibration_thin_film_thickness, SR_Greysphere_Calibration_thin_film_IOR, SR_Greysphere_Calibration_emission, SR_Greysphere_Calibration_emission_color, SR_Greysphere_Calibration_opacity, SR_Greysphere_Calibration_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_Greysphere_Calibration_out); + material Greysphere_Calibration_out = SR_Greysphere_Calibration_out; + out1 = vec4(Greysphere_Calibration_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Greysphere_Calibration.glsl.vert b/Materials/Examples/StandardSurface/Greysphere_Calibration.glsl.vert new file mode 100644 index 0000000000..60b47d493e --- /dev/null +++ b/Materials/Examples/StandardSurface/Greysphere_Calibration.glsl.vert @@ -0,0 +1,31 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Greysphere_Calibration.mdl b/Materials/Examples/StandardSurface/Greysphere_Calibration.mdl new file mode 100644 index 0000000000..ebfde0142a --- /dev/null +++ b/Materials/Examples/StandardSurface/Greysphere_Calibration.mdl @@ -0,0 +1,427 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +float2 NG_switch_vector2I +( + float2 in1 = float2(0.000000, 0.000000), + float2 in2 = float2(0.000000, 0.000000), + float2 in3 = float2(0.000000, 0.000000), + float2 in4 = float2(0.000000, 0.000000), + float2 in5 = float2(0.000000, 0.000000), + float2 in6 = float2(0.000000, 0.000000), + float2 in7 = float2(0.000000, 0.000000), + float2 in8 = float2(0.000000, 0.000000), + float2 in9 = float2(0.000000, 0.000000), + float2 in10 = float2(0.000000, 0.000000), + int which = 0 +) +{ + float2 ifgreater_10_out = materialx::stdlib_1_8::mx_ifgreater_vector2I(10, which, in10, float2(0.000000, 0.000000)); + float2 ifgreater_9_out = materialx::stdlib_1_8::mx_ifgreater_vector2I(9, which, in9, ifgreater_10_out); + float2 ifgreater_8_out = materialx::stdlib_1_8::mx_ifgreater_vector2I(8, which, in8, ifgreater_9_out); + float2 ifgreater_7_out = materialx::stdlib_1_8::mx_ifgreater_vector2I(7, which, in7, ifgreater_8_out); + float2 ifgreater_6_out = materialx::stdlib_1_8::mx_ifgreater_vector2I(6, which, in6, ifgreater_7_out); + float2 ifgreater_5_out = materialx::stdlib_1_8::mx_ifgreater_vector2I(5, which, in5, ifgreater_6_out); + float2 ifgreater_4_out = materialx::stdlib_1_8::mx_ifgreater_vector2I(4, which, in4, ifgreater_5_out); + float2 ifgreater_3_out = materialx::stdlib_1_8::mx_ifgreater_vector2I(3, which, in3, ifgreater_4_out); + float2 ifgreater_2_out = materialx::stdlib_1_8::mx_ifgreater_vector2I(2, which, in2, ifgreater_3_out); + float2 ifgreater_1_out = materialx::stdlib_1_8::mx_ifgreater_vector2I(1, which, in1, ifgreater_2_out); + return ifgreater_1_out; +} + +float2 NG_place2d_vector2 +( + float2 texcoord = float2(0.000000, 0.000000), + float2 pivot = float2(0.000000, 0.000000), + float2 scale = float2(1.000000, 1.000000), + float rotate = 0.000000, + float2 offset = float2(0.000000, 0.000000), + int operationorder = 0 +) +{ + float2 N_subpivot_out = texcoord - pivot; + float2 N_applyscale_out = N_subpivot_out / scale; + float2 N_applyoffset2_out = N_subpivot_out - offset; + float2 N_applyrot_out = materialx::stdlib_1_8::mx_rotate2d_vector2(mxp_in:N_applyscale_out, mxp_amount:rotate); + float2 N_applyrot2_out = materialx::stdlib_1_8::mx_rotate2d_vector2(mxp_in:N_applyoffset2_out, mxp_amount:rotate); + float2 N_applyoffset_out = N_applyrot_out - offset; + float2 N_applyscale2_out = N_applyrot2_out / scale; + float2 N_addpivot_out = N_applyoffset_out + pivot; + float2 N_addpivot2_out = N_applyscale2_out + pivot; + float2 N_switch_operationorder_out = NG_switch_vector2I(N_addpivot_out, N_addpivot2_out, float2(0.000000, 0.000000), float2(0.000000, 0.000000), float2(0.000000, 0.000000), float2(0.000000, 0.000000), float2(0.000000, 0.000000), float2(0.000000, 0.000000), float2(0.000000, 0.000000), float2(0.000000, 0.000000), operationorder); + return N_switch_operationorder_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Greysphere_Calibration +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int texcoord1_index = 0 + [[ + materialx::core::origin("NG_Greysphere_Calibration/texcoord1/index") + ]], + float2 place2d_pivot = float2(0.500000, 0.500000) + [[ + materialx::core::origin("NG_Greysphere_Calibration/place2d/pivot") + ]], + float2 place2d_scale = float2(0.210000, 0.210000) + [[ + materialx::core::origin("NG_Greysphere_Calibration/place2d/scale") + ]], + float place2d_rotate = 0.000000 + [[ + materialx::core::origin("NG_Greysphere_Calibration/place2d/rotate") + ]], + float2 place2d_offset = float2(-1.660000, -0.490000) + [[ + materialx::core::origin("NG_Greysphere_Calibration/place2d/offset") + ]], + int place2d_operationorder = 0 + [[ + materialx::core::origin("NG_Greysphere_Calibration/place2d/operationorder") + ]], + uniform texture_2d image1_file = texture_2d("../../../Images/greysphere_calibration.png", tex::gamma_linear) + [[ + materialx::core::origin("NG_Greysphere_Calibration/image1/file") + ]], + uniform string image1_layer = "" + [[ + materialx::core::origin("NG_Greysphere_Calibration/image1/layer") + ]], + color image1_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_Greysphere_Calibration/image1/default") + ]], + uniform mx_addressmode_type image1_uaddressmode = mx_addressmode_type_clamp + [[ + materialx::core::origin("NG_Greysphere_Calibration/image1/uaddressmode") + ]], + uniform mx_addressmode_type image1_vaddressmode = mx_addressmode_type_clamp + [[ + materialx::core::origin("NG_Greysphere_Calibration/image1/vaddressmode") + ]], + uniform mx_filterlookup_type image1_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_Greysphere_Calibration/image1/filtertype") + ]], + uniform string image1_framerange = "" + [[ + materialx::core::origin("NG_Greysphere_Calibration/image1/framerange") + ]], + uniform int image1_frameoffset = 0 + [[ + materialx::core::origin("NG_Greysphere_Calibration/image1/frameoffset") + ]], + uniform mx_addressmode_type image1_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_Greysphere_Calibration/image1/frameendaction") + ]], + float SR_Greysphere_Calibration_base = 1.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/base") + ]], + float SR_Greysphere_Calibration_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/diffuse_roughness") + ]], + float SR_Greysphere_Calibration_metalness = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/metalness") + ]], + float SR_Greysphere_Calibration_specular = 1.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/specular") + ]], + color SR_Greysphere_Calibration_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_Greysphere_Calibration/specular_color") + ]], + float SR_Greysphere_Calibration_specular_roughness = 0.700000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/specular_roughness") + ]], + uniform float SR_Greysphere_Calibration_specular_IOR = 1.500000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/specular_IOR") + ]], + float SR_Greysphere_Calibration_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/specular_anisotropy") + ]], + float SR_Greysphere_Calibration_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/specular_rotation") + ]], + float SR_Greysphere_Calibration_transmission = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/transmission") + ]], + color SR_Greysphere_Calibration_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_Greysphere_Calibration/transmission_color") + ]], + float SR_Greysphere_Calibration_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/transmission_depth") + ]], + color SR_Greysphere_Calibration_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_Greysphere_Calibration/transmission_scatter") + ]], + float SR_Greysphere_Calibration_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/transmission_scatter_anisotropy") + ]], + float SR_Greysphere_Calibration_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/transmission_dispersion") + ]], + float SR_Greysphere_Calibration_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/transmission_extra_roughness") + ]], + float SR_Greysphere_Calibration_subsurface = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/subsurface") + ]], + color SR_Greysphere_Calibration_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_Greysphere_Calibration/subsurface_color") + ]], + color SR_Greysphere_Calibration_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_Greysphere_Calibration/subsurface_radius") + ]], + float SR_Greysphere_Calibration_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/subsurface_scale") + ]], + float SR_Greysphere_Calibration_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/subsurface_anisotropy") + ]], + float SR_Greysphere_Calibration_sheen = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/sheen") + ]], + color SR_Greysphere_Calibration_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_Greysphere_Calibration/sheen_color") + ]], + float SR_Greysphere_Calibration_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/sheen_roughness") + ]], + float SR_Greysphere_Calibration_coat = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/coat") + ]], + color SR_Greysphere_Calibration_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_Greysphere_Calibration/coat_color") + ]], + float SR_Greysphere_Calibration_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/coat_roughness") + ]], + float SR_Greysphere_Calibration_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/coat_anisotropy") + ]], + float SR_Greysphere_Calibration_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/coat_rotation") + ]], + uniform float SR_Greysphere_Calibration_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/coat_IOR") + ]], + float SR_Greysphere_Calibration_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/coat_affect_color") + ]], + float SR_Greysphere_Calibration_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/coat_affect_roughness") + ]], + float SR_Greysphere_Calibration_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/thin_film_thickness") + ]], + float SR_Greysphere_Calibration_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/thin_film_IOR") + ]], + float SR_Greysphere_Calibration_emission = 0.000000 + [[ + materialx::core::origin("SR_Greysphere_Calibration/emission") + ]], + color SR_Greysphere_Calibration_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_Greysphere_Calibration/emission_color") + ]], + color SR_Greysphere_Calibration_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_Greysphere_Calibration/opacity") + ]], + bool SR_Greysphere_Calibration_thin_walled = false + [[ + materialx::core::origin("SR_Greysphere_Calibration/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 texcoord1_out = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:texcoord1_index); + float2 place2d_out = NG_place2d_vector2(texcoord1_out, place2d_pivot, place2d_scale, place2d_rotate, place2d_offset, place2d_operationorder); + color image1_out = materialx::stdlib_1_8::mx_image_color3(image1_file, image1_layer, image1_default, place2d_out, image1_uaddressmode, image1_vaddressmode, image1_filtertype, image1_framerange, image1_frameoffset, image1_frameendaction, mxp_flip_v:false); + material SR_Greysphere_Calibration_out = NG_standard_surface_surfaceshader_100(SR_Greysphere_Calibration_base, image1_out, SR_Greysphere_Calibration_diffuse_roughness, SR_Greysphere_Calibration_metalness, SR_Greysphere_Calibration_specular, SR_Greysphere_Calibration_specular_color, SR_Greysphere_Calibration_specular_roughness, SR_Greysphere_Calibration_specular_IOR, SR_Greysphere_Calibration_specular_anisotropy, SR_Greysphere_Calibration_specular_rotation, SR_Greysphere_Calibration_transmission, SR_Greysphere_Calibration_transmission_color, SR_Greysphere_Calibration_transmission_depth, SR_Greysphere_Calibration_transmission_scatter, SR_Greysphere_Calibration_transmission_scatter_anisotropy, SR_Greysphere_Calibration_transmission_dispersion, SR_Greysphere_Calibration_transmission_extra_roughness, SR_Greysphere_Calibration_subsurface, SR_Greysphere_Calibration_subsurface_color, SR_Greysphere_Calibration_subsurface_radius, SR_Greysphere_Calibration_subsurface_scale, SR_Greysphere_Calibration_subsurface_anisotropy, SR_Greysphere_Calibration_sheen, SR_Greysphere_Calibration_sheen_color, SR_Greysphere_Calibration_sheen_roughness, SR_Greysphere_Calibration_coat, SR_Greysphere_Calibration_coat_color, SR_Greysphere_Calibration_coat_roughness, SR_Greysphere_Calibration_coat_anisotropy, SR_Greysphere_Calibration_coat_rotation, SR_Greysphere_Calibration_coat_IOR, geomprop_Nworld_out1, SR_Greysphere_Calibration_coat_affect_color, SR_Greysphere_Calibration_coat_affect_roughness, SR_Greysphere_Calibration_thin_film_thickness, SR_Greysphere_Calibration_thin_film_IOR, SR_Greysphere_Calibration_emission, SR_Greysphere_Calibration_emission_color, SR_Greysphere_Calibration_opacity, SR_Greysphere_Calibration_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Greysphere_Calibration_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_Greysphere_Calibration_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Greysphere_Calibration_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Greysphere_Calibration.msl.frag b/Materials/Examples/StandardSurface/Greysphere_Calibration.msl.frag new file mode 100644 index 0000000000..edfce89efe --- /dev/null +++ b/Materials/Examples/StandardSurface/Greysphere_Calibration.msl.frag @@ -0,0 +1,2716 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int texcoord1_index; + vec2 place2d_pivot; + vec2 place2d_scale; + float place2d_rotate; + vec2 place2d_offset; + int place2d_operationorder; + int image1_layer; + vec3 image1_default; + int image1_uaddressmode; + int image1_vaddressmode; + int image1_filtertype; + int image1_framerange; + int image1_frameoffset; + int image1_frameendaction; + vec2 image1_uv_scale; + vec2 image1_uv_offset; + float SR_Greysphere_Calibration_base; + float SR_Greysphere_Calibration_diffuse_roughness; + float SR_Greysphere_Calibration_metalness; + float SR_Greysphere_Calibration_specular; + vec3 SR_Greysphere_Calibration_specular_color; + float SR_Greysphere_Calibration_specular_roughness; + float SR_Greysphere_Calibration_specular_IOR; + float SR_Greysphere_Calibration_specular_anisotropy; + float SR_Greysphere_Calibration_specular_rotation; + float SR_Greysphere_Calibration_transmission; + vec3 SR_Greysphere_Calibration_transmission_color; + float SR_Greysphere_Calibration_transmission_depth; + vec3 SR_Greysphere_Calibration_transmission_scatter; + float SR_Greysphere_Calibration_transmission_scatter_anisotropy; + float SR_Greysphere_Calibration_transmission_dispersion; + float SR_Greysphere_Calibration_transmission_extra_roughness; + float SR_Greysphere_Calibration_subsurface; + vec3 SR_Greysphere_Calibration_subsurface_color; + vec3 SR_Greysphere_Calibration_subsurface_radius; + float SR_Greysphere_Calibration_subsurface_scale; + float SR_Greysphere_Calibration_subsurface_anisotropy; + float SR_Greysphere_Calibration_sheen; + vec3 SR_Greysphere_Calibration_sheen_color; + float SR_Greysphere_Calibration_sheen_roughness; + float SR_Greysphere_Calibration_coat; + vec3 SR_Greysphere_Calibration_coat_color; + float SR_Greysphere_Calibration_coat_roughness; + float SR_Greysphere_Calibration_coat_anisotropy; + float SR_Greysphere_Calibration_coat_rotation; + float SR_Greysphere_Calibration_coat_IOR; + float SR_Greysphere_Calibration_coat_affect_color; + float SR_Greysphere_Calibration_coat_affect_roughness; + float SR_Greysphere_Calibration_thin_film_thickness; + float SR_Greysphere_Calibration_thin_film_IOR; + float SR_Greysphere_Calibration_emission; + vec3 SR_Greysphere_Calibration_emission_color; + vec3 SR_Greysphere_Calibration_opacity; + bool SR_Greysphere_Calibration_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int texcoord1_index + + , vec2 place2d_pivot + + , vec2 place2d_scale + + , float place2d_rotate + + , vec2 place2d_offset + + , int place2d_operationorder + +, MetalTexture image1_file , int image1_layer + + , vec3 image1_default + + , int image1_uaddressmode + + , int image1_vaddressmode + + , int image1_filtertype + + , int image1_framerange + + , int image1_frameoffset + + , int image1_frameendaction + + , vec2 image1_uv_scale + + , vec2 image1_uv_offset + + , float SR_Greysphere_Calibration_base + + , float SR_Greysphere_Calibration_diffuse_roughness + + , float SR_Greysphere_Calibration_metalness + + , float SR_Greysphere_Calibration_specular + + , vec3 SR_Greysphere_Calibration_specular_color + + , float SR_Greysphere_Calibration_specular_roughness + + , float SR_Greysphere_Calibration_specular_IOR + + , float SR_Greysphere_Calibration_specular_anisotropy + + , float SR_Greysphere_Calibration_specular_rotation + + , float SR_Greysphere_Calibration_transmission + + , vec3 SR_Greysphere_Calibration_transmission_color + + , float SR_Greysphere_Calibration_transmission_depth + + , vec3 SR_Greysphere_Calibration_transmission_scatter + + , float SR_Greysphere_Calibration_transmission_scatter_anisotropy + + , float SR_Greysphere_Calibration_transmission_dispersion + + , float SR_Greysphere_Calibration_transmission_extra_roughness + + , float SR_Greysphere_Calibration_subsurface + + , vec3 SR_Greysphere_Calibration_subsurface_color + + , vec3 SR_Greysphere_Calibration_subsurface_radius + + , float SR_Greysphere_Calibration_subsurface_scale + + , float SR_Greysphere_Calibration_subsurface_anisotropy + + , float SR_Greysphere_Calibration_sheen + + , vec3 SR_Greysphere_Calibration_sheen_color + + , float SR_Greysphere_Calibration_sheen_roughness + + , float SR_Greysphere_Calibration_coat + + , vec3 SR_Greysphere_Calibration_coat_color + + , float SR_Greysphere_Calibration_coat_roughness + + , float SR_Greysphere_Calibration_coat_anisotropy + + , float SR_Greysphere_Calibration_coat_rotation + + , float SR_Greysphere_Calibration_coat_IOR + + , float SR_Greysphere_Calibration_coat_affect_color + + , float SR_Greysphere_Calibration_coat_affect_roughness + + , float SR_Greysphere_Calibration_thin_film_thickness + + , float SR_Greysphere_Calibration_thin_film_IOR + + , float SR_Greysphere_Calibration_emission + + , vec3 SR_Greysphere_Calibration_emission_color + + , vec3 SR_Greysphere_Calibration_opacity + + , bool SR_Greysphere_Calibration_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , texcoord1_index(texcoord1_index) + + , place2d_pivot(place2d_pivot) + + , place2d_scale(place2d_scale) + + , place2d_rotate(place2d_rotate) + + , place2d_offset(place2d_offset) + + , place2d_operationorder(place2d_operationorder) + +, image1_file(image1_file) + , image1_layer(image1_layer) + + , image1_default(image1_default) + + , image1_uaddressmode(image1_uaddressmode) + + , image1_vaddressmode(image1_vaddressmode) + + , image1_filtertype(image1_filtertype) + + , image1_framerange(image1_framerange) + + , image1_frameoffset(image1_frameoffset) + + , image1_frameendaction(image1_frameendaction) + + , image1_uv_scale(image1_uv_scale) + + , image1_uv_offset(image1_uv_offset) + + , SR_Greysphere_Calibration_base(SR_Greysphere_Calibration_base) + + , SR_Greysphere_Calibration_diffuse_roughness(SR_Greysphere_Calibration_diffuse_roughness) + + , SR_Greysphere_Calibration_metalness(SR_Greysphere_Calibration_metalness) + + , SR_Greysphere_Calibration_specular(SR_Greysphere_Calibration_specular) + + , SR_Greysphere_Calibration_specular_color(SR_Greysphere_Calibration_specular_color) + + , SR_Greysphere_Calibration_specular_roughness(SR_Greysphere_Calibration_specular_roughness) + + , SR_Greysphere_Calibration_specular_IOR(SR_Greysphere_Calibration_specular_IOR) + + , SR_Greysphere_Calibration_specular_anisotropy(SR_Greysphere_Calibration_specular_anisotropy) + + , SR_Greysphere_Calibration_specular_rotation(SR_Greysphere_Calibration_specular_rotation) + + , SR_Greysphere_Calibration_transmission(SR_Greysphere_Calibration_transmission) + + , SR_Greysphere_Calibration_transmission_color(SR_Greysphere_Calibration_transmission_color) + + , SR_Greysphere_Calibration_transmission_depth(SR_Greysphere_Calibration_transmission_depth) + + , SR_Greysphere_Calibration_transmission_scatter(SR_Greysphere_Calibration_transmission_scatter) + + , SR_Greysphere_Calibration_transmission_scatter_anisotropy(SR_Greysphere_Calibration_transmission_scatter_anisotropy) + + , SR_Greysphere_Calibration_transmission_dispersion(SR_Greysphere_Calibration_transmission_dispersion) + + , SR_Greysphere_Calibration_transmission_extra_roughness(SR_Greysphere_Calibration_transmission_extra_roughness) + + , SR_Greysphere_Calibration_subsurface(SR_Greysphere_Calibration_subsurface) + + , SR_Greysphere_Calibration_subsurface_color(SR_Greysphere_Calibration_subsurface_color) + + , SR_Greysphere_Calibration_subsurface_radius(SR_Greysphere_Calibration_subsurface_radius) + + , SR_Greysphere_Calibration_subsurface_scale(SR_Greysphere_Calibration_subsurface_scale) + + , SR_Greysphere_Calibration_subsurface_anisotropy(SR_Greysphere_Calibration_subsurface_anisotropy) + + , SR_Greysphere_Calibration_sheen(SR_Greysphere_Calibration_sheen) + + , SR_Greysphere_Calibration_sheen_color(SR_Greysphere_Calibration_sheen_color) + + , SR_Greysphere_Calibration_sheen_roughness(SR_Greysphere_Calibration_sheen_roughness) + + , SR_Greysphere_Calibration_coat(SR_Greysphere_Calibration_coat) + + , SR_Greysphere_Calibration_coat_color(SR_Greysphere_Calibration_coat_color) + + , SR_Greysphere_Calibration_coat_roughness(SR_Greysphere_Calibration_coat_roughness) + + , SR_Greysphere_Calibration_coat_anisotropy(SR_Greysphere_Calibration_coat_anisotropy) + + , SR_Greysphere_Calibration_coat_rotation(SR_Greysphere_Calibration_coat_rotation) + + , SR_Greysphere_Calibration_coat_IOR(SR_Greysphere_Calibration_coat_IOR) + + , SR_Greysphere_Calibration_coat_affect_color(SR_Greysphere_Calibration_coat_affect_color) + + , SR_Greysphere_Calibration_coat_affect_roughness(SR_Greysphere_Calibration_coat_affect_roughness) + + , SR_Greysphere_Calibration_thin_film_thickness(SR_Greysphere_Calibration_thin_film_thickness) + + , SR_Greysphere_Calibration_thin_film_IOR(SR_Greysphere_Calibration_thin_film_IOR) + + , SR_Greysphere_Calibration_emission(SR_Greysphere_Calibration_emission) + + , SR_Greysphere_Calibration_emission_color(SR_Greysphere_Calibration_emission_color) + + , SR_Greysphere_Calibration_opacity(SR_Greysphere_Calibration_opacity) + + , SR_Greysphere_Calibration_thin_walled(SR_Greysphere_Calibration_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int texcoord1_index; + + + vec2 place2d_pivot; + + + vec2 place2d_scale; + + + float place2d_rotate; + + + vec2 place2d_offset; + + + int place2d_operationorder; + + +MetalTexture image1_file; + int image1_layer; + + + vec3 image1_default; + + + int image1_uaddressmode; + + + int image1_vaddressmode; + + + int image1_filtertype; + + + int image1_framerange; + + + int image1_frameoffset; + + + int image1_frameendaction; + + + vec2 image1_uv_scale; + + + vec2 image1_uv_offset; + + + float SR_Greysphere_Calibration_base; + + + float SR_Greysphere_Calibration_diffuse_roughness; + + + float SR_Greysphere_Calibration_metalness; + + + float SR_Greysphere_Calibration_specular; + + + vec3 SR_Greysphere_Calibration_specular_color; + + + float SR_Greysphere_Calibration_specular_roughness; + + + float SR_Greysphere_Calibration_specular_IOR; + + + float SR_Greysphere_Calibration_specular_anisotropy; + + + float SR_Greysphere_Calibration_specular_rotation; + + + float SR_Greysphere_Calibration_transmission; + + + vec3 SR_Greysphere_Calibration_transmission_color; + + + float SR_Greysphere_Calibration_transmission_depth; + + + vec3 SR_Greysphere_Calibration_transmission_scatter; + + + float SR_Greysphere_Calibration_transmission_scatter_anisotropy; + + + float SR_Greysphere_Calibration_transmission_dispersion; + + + float SR_Greysphere_Calibration_transmission_extra_roughness; + + + float SR_Greysphere_Calibration_subsurface; + + + vec3 SR_Greysphere_Calibration_subsurface_color; + + + vec3 SR_Greysphere_Calibration_subsurface_radius; + + + float SR_Greysphere_Calibration_subsurface_scale; + + + float SR_Greysphere_Calibration_subsurface_anisotropy; + + + float SR_Greysphere_Calibration_sheen; + + + vec3 SR_Greysphere_Calibration_sheen_color; + + + float SR_Greysphere_Calibration_sheen_roughness; + + + float SR_Greysphere_Calibration_coat; + + + vec3 SR_Greysphere_Calibration_coat_color; + + + float SR_Greysphere_Calibration_coat_roughness; + + + float SR_Greysphere_Calibration_coat_anisotropy; + + + float SR_Greysphere_Calibration_coat_rotation; + + + float SR_Greysphere_Calibration_coat_IOR; + + + float SR_Greysphere_Calibration_coat_affect_color; + + + float SR_Greysphere_Calibration_coat_affect_roughness; + + + float SR_Greysphere_Calibration_thin_film_thickness; + + + float SR_Greysphere_Calibration_thin_film_IOR; + + + float SR_Greysphere_Calibration_emission; + + + vec3 SR_Greysphere_Calibration_emission_color; + + + vec3 SR_Greysphere_Calibration_opacity; + + + bool SR_Greysphere_Calibration_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_rotate_vector2(vec2 _in, float amount, thread vec2& result) + { + float rotationRadians = mx_radians(amount); + float sa = mx_sin(rotationRadians); + float ca = mx_cos(rotationRadians); + result = vec2(ca*_in.x + sa*_in.y, -sa*_in.x + ca*_in.y); + } + + void NG_switch_vector2I(vec2 in1, vec2 in2, vec2 in3, vec2 in4, vec2 in5, vec2 in6, vec2 in7, vec2 in8, vec2 in9, vec2 in10, int which, thread vec2& out1) + { + const int ifgreater_10_value1_tmp = 10; + const vec2 ifgreater_10_in2_tmp = vec2(0.000000, 0.000000); + vec2 ifgreater_10_out = (ifgreater_10_value1_tmp > which) ? in10 : ifgreater_10_in2_tmp; + const int ifgreater_9_value1_tmp = 9; + vec2 ifgreater_9_out = (ifgreater_9_value1_tmp > which) ? in9 : ifgreater_10_out; + const int ifgreater_8_value1_tmp = 8; + vec2 ifgreater_8_out = (ifgreater_8_value1_tmp > which) ? in8 : ifgreater_9_out; + const int ifgreater_7_value1_tmp = 7; + vec2 ifgreater_7_out = (ifgreater_7_value1_tmp > which) ? in7 : ifgreater_8_out; + const int ifgreater_6_value1_tmp = 6; + vec2 ifgreater_6_out = (ifgreater_6_value1_tmp > which) ? in6 : ifgreater_7_out; + const int ifgreater_5_value1_tmp = 5; + vec2 ifgreater_5_out = (ifgreater_5_value1_tmp > which) ? in5 : ifgreater_6_out; + const int ifgreater_4_value1_tmp = 4; + vec2 ifgreater_4_out = (ifgreater_4_value1_tmp > which) ? in4 : ifgreater_5_out; + const int ifgreater_3_value1_tmp = 3; + vec2 ifgreater_3_out = (ifgreater_3_value1_tmp > which) ? in3 : ifgreater_4_out; + const int ifgreater_2_value1_tmp = 2; + vec2 ifgreater_2_out = (ifgreater_2_value1_tmp > which) ? in2 : ifgreater_3_out; + const int ifgreater_1_value1_tmp = 1; + vec2 ifgreater_1_out = (ifgreater_1_value1_tmp > which) ? in1 : ifgreater_2_out; + out1 = ifgreater_1_out; + } + + void NG_place2d_vector2(vec2 texcoord1, vec2 pivot, vec2 scale, float rotate, vec2 offset, int operationorder, thread vec2& out1) + { + vec2 N_subpivot_out = texcoord1 - pivot; + vec2 N_applyscale_out = N_subpivot_out / scale; + vec2 N_applyoffset2_out = N_subpivot_out - offset; + vec2 N_applyrot_out = vec2(0.0); + mx_rotate_vector2(N_applyscale_out, rotate, N_applyrot_out); + vec2 N_applyrot2_out = vec2(0.0); + mx_rotate_vector2(N_applyoffset2_out, rotate, N_applyrot2_out); + vec2 N_applyoffset_out = N_applyrot_out - offset; + vec2 N_applyscale2_out = N_applyrot2_out / scale; + vec2 N_addpivot_out = N_applyoffset_out + pivot; + vec2 N_addpivot2_out = N_applyscale2_out + pivot; + vec2 N_switch_operationorder_out = vec2(0.0); + NG_switch_vector2I(N_addpivot_out, N_addpivot2_out, vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), vec2(0.000000, 0.000000), operationorder, N_switch_operationorder_out); + out1 = N_switch_operationorder_out; + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 texcoord1_out = vd.texcoord_0.xy; + vec2 place2d_out = vec2(0.0); + NG_place2d_vector2(texcoord1_out, place2d_pivot, place2d_scale, place2d_rotate, place2d_offset, place2d_operationorder, place2d_out); + vec3 image1_out = vec3(0.0); + mx_image_color3(image1_file, image1_layer, image1_default, place2d_out, image1_uaddressmode, image1_vaddressmode, image1_filtertype, image1_framerange, image1_frameoffset, image1_frameendaction, image1_uv_scale, image1_uv_offset, image1_out); + surfaceshader SR_Greysphere_Calibration_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_Greysphere_Calibration_base, image1_out, SR_Greysphere_Calibration_diffuse_roughness, SR_Greysphere_Calibration_metalness, SR_Greysphere_Calibration_specular, SR_Greysphere_Calibration_specular_color, SR_Greysphere_Calibration_specular_roughness, SR_Greysphere_Calibration_specular_IOR, SR_Greysphere_Calibration_specular_anisotropy, SR_Greysphere_Calibration_specular_rotation, SR_Greysphere_Calibration_transmission, SR_Greysphere_Calibration_transmission_color, SR_Greysphere_Calibration_transmission_depth, SR_Greysphere_Calibration_transmission_scatter, SR_Greysphere_Calibration_transmission_scatter_anisotropy, SR_Greysphere_Calibration_transmission_dispersion, SR_Greysphere_Calibration_transmission_extra_roughness, SR_Greysphere_Calibration_subsurface, SR_Greysphere_Calibration_subsurface_color, SR_Greysphere_Calibration_subsurface_radius, SR_Greysphere_Calibration_subsurface_scale, SR_Greysphere_Calibration_subsurface_anisotropy, SR_Greysphere_Calibration_sheen, SR_Greysphere_Calibration_sheen_color, SR_Greysphere_Calibration_sheen_roughness, SR_Greysphere_Calibration_coat, SR_Greysphere_Calibration_coat_color, SR_Greysphere_Calibration_coat_roughness, SR_Greysphere_Calibration_coat_anisotropy, SR_Greysphere_Calibration_coat_rotation, SR_Greysphere_Calibration_coat_IOR, geomprop_Nworld_out1, SR_Greysphere_Calibration_coat_affect_color, SR_Greysphere_Calibration_coat_affect_roughness, SR_Greysphere_Calibration_thin_film_thickness, SR_Greysphere_Calibration_thin_film_IOR, SR_Greysphere_Calibration_emission, SR_Greysphere_Calibration_emission_color, SR_Greysphere_Calibration_opacity, SR_Greysphere_Calibration_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_Greysphere_Calibration_out); + material Greysphere_Calibration_out = SR_Greysphere_Calibration_out; + out1 = float4(Greysphere_Calibration_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d image1_file_tex [[texture(0)]], sampler image1_file_sampler [[sampler(0)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(1)]], sampler u_envRadiance_sampler [[sampler(1)]] +, texture2d u_envIrradiance_tex [[texture(2)]], sampler u_envIrradiance_sampler [[sampler(2)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.texcoord1_index + , u_pub.place2d_pivot + , u_pub.place2d_scale + , u_pub.place2d_rotate + , u_pub.place2d_offset + , u_pub.place2d_operationorder +, MetalTexture { +image1_file_tex, image1_file_sampler } + , u_pub.image1_layer + , u_pub.image1_default + , u_pub.image1_uaddressmode + , u_pub.image1_vaddressmode + , u_pub.image1_filtertype + , u_pub.image1_framerange + , u_pub.image1_frameoffset + , u_pub.image1_frameendaction + , u_pub.image1_uv_scale + , u_pub.image1_uv_offset + , u_pub.SR_Greysphere_Calibration_base + , u_pub.SR_Greysphere_Calibration_diffuse_roughness + , u_pub.SR_Greysphere_Calibration_metalness + , u_pub.SR_Greysphere_Calibration_specular + , u_pub.SR_Greysphere_Calibration_specular_color + , u_pub.SR_Greysphere_Calibration_specular_roughness + , u_pub.SR_Greysphere_Calibration_specular_IOR + , u_pub.SR_Greysphere_Calibration_specular_anisotropy + , u_pub.SR_Greysphere_Calibration_specular_rotation + , u_pub.SR_Greysphere_Calibration_transmission + , u_pub.SR_Greysphere_Calibration_transmission_color + , u_pub.SR_Greysphere_Calibration_transmission_depth + , u_pub.SR_Greysphere_Calibration_transmission_scatter + , u_pub.SR_Greysphere_Calibration_transmission_scatter_anisotropy + , u_pub.SR_Greysphere_Calibration_transmission_dispersion + , u_pub.SR_Greysphere_Calibration_transmission_extra_roughness + , u_pub.SR_Greysphere_Calibration_subsurface + , u_pub.SR_Greysphere_Calibration_subsurface_color + , u_pub.SR_Greysphere_Calibration_subsurface_radius + , u_pub.SR_Greysphere_Calibration_subsurface_scale + , u_pub.SR_Greysphere_Calibration_subsurface_anisotropy + , u_pub.SR_Greysphere_Calibration_sheen + , u_pub.SR_Greysphere_Calibration_sheen_color + , u_pub.SR_Greysphere_Calibration_sheen_roughness + , u_pub.SR_Greysphere_Calibration_coat + , u_pub.SR_Greysphere_Calibration_coat_color + , u_pub.SR_Greysphere_Calibration_coat_roughness + , u_pub.SR_Greysphere_Calibration_coat_anisotropy + , u_pub.SR_Greysphere_Calibration_coat_rotation + , u_pub.SR_Greysphere_Calibration_coat_IOR + , u_pub.SR_Greysphere_Calibration_coat_affect_color + , u_pub.SR_Greysphere_Calibration_coat_affect_roughness + , u_pub.SR_Greysphere_Calibration_thin_film_thickness + , u_pub.SR_Greysphere_Calibration_thin_film_IOR + , u_pub.SR_Greysphere_Calibration_emission + , u_pub.SR_Greysphere_Calibration_emission_color + , u_pub.SR_Greysphere_Calibration_opacity + , u_pub.SR_Greysphere_Calibration_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Greysphere_Calibration.msl.vert b/Materials/Examples/StandardSurface/Greysphere_Calibration.msl.vert new file mode 100644 index 0000000000..a4f0144cec --- /dev/null +++ b/Materials/Examples/StandardSurface/Greysphere_Calibration.msl.vert @@ -0,0 +1,120 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'texcoord1'. Function already called in this scope. + // Omitted node 'place2d'. Function already called in this scope. + // Omitted node 'image1'. Function already called in this scope. + // Omitted node 'SR_Greysphere_Calibration'. Function already called in this scope. + // Omitted node 'Greysphere_Calibration'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Greysphere_Calibration.osl b/Materials/Examples/StandardSurface/Greysphere_Calibration.osl new file mode 100644 index 0000000000..23b9fb037a --- /dev/null +++ b/Materials/Examples/StandardSurface/Greysphere_Calibration.osl @@ -0,0 +1,568 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_rotate_vector2(vector2 _in, float amount, output vector2 result) +{ + float rotationRadians = radians(amount); + float sa = sin(rotationRadians); + float ca = cos(rotationRadians); + result = vector2(ca*_in.x + sa*_in.y, -sa*_in.x + ca*_in.y); +} + +void NG_switch_vector2I(vector2 in1, vector2 in2, vector2 in3, vector2 in4, vector2 in5, vector2 in6, vector2 in7, vector2 in8, vector2 in9, vector2 in10, int which, output vector2 out) +{ + int ifgreater_10_value1_tmp = 10; + vector2 ifgreater_10_in2_tmp = vector2(0.000000, 0.000000); + vector2 ifgreater_10_out = mx_ternary(ifgreater_10_value1_tmp > which, in10, ifgreater_10_in2_tmp); + int ifgreater_9_value1_tmp = 9; + vector2 ifgreater_9_out = mx_ternary(ifgreater_9_value1_tmp > which, in9, ifgreater_10_out); + int ifgreater_8_value1_tmp = 8; + vector2 ifgreater_8_out = mx_ternary(ifgreater_8_value1_tmp > which, in8, ifgreater_9_out); + int ifgreater_7_value1_tmp = 7; + vector2 ifgreater_7_out = mx_ternary(ifgreater_7_value1_tmp > which, in7, ifgreater_8_out); + int ifgreater_6_value1_tmp = 6; + vector2 ifgreater_6_out = mx_ternary(ifgreater_6_value1_tmp > which, in6, ifgreater_7_out); + int ifgreater_5_value1_tmp = 5; + vector2 ifgreater_5_out = mx_ternary(ifgreater_5_value1_tmp > which, in5, ifgreater_6_out); + int ifgreater_4_value1_tmp = 4; + vector2 ifgreater_4_out = mx_ternary(ifgreater_4_value1_tmp > which, in4, ifgreater_5_out); + int ifgreater_3_value1_tmp = 3; + vector2 ifgreater_3_out = mx_ternary(ifgreater_3_value1_tmp > which, in3, ifgreater_4_out); + int ifgreater_2_value1_tmp = 2; + vector2 ifgreater_2_out = mx_ternary(ifgreater_2_value1_tmp > which, in2, ifgreater_3_out); + int ifgreater_1_value1_tmp = 1; + vector2 ifgreater_1_out = mx_ternary(ifgreater_1_value1_tmp > which, in1, ifgreater_2_out); + out = ifgreater_1_out; +} + +void NG_place2d_vector2(vector2 texcoord, vector2 pivot, vector2 scale, float rotate1, vector2 offset, int operationorder, output vector2 out) +{ + vector2 N_subpivot_out = texcoord - pivot; + vector2 N_applyscale_out = N_subpivot_out / scale; + vector2 N_applyoffset2_out = N_subpivot_out - offset; + vector2 N_applyrot_out = vector2(0.0, 0.0); + mx_rotate_vector2(N_applyscale_out, rotate1, N_applyrot_out); + vector2 N_applyrot2_out = vector2(0.0, 0.0); + mx_rotate_vector2(N_applyoffset2_out, rotate1, N_applyrot2_out); + vector2 N_applyoffset_out = N_applyrot_out - offset; + vector2 N_applyscale2_out = N_applyrot2_out / scale; + vector2 N_addpivot_out = N_applyoffset_out + pivot; + vector2 N_addpivot2_out = N_applyscale2_out + pivot; + vector2 N_switch_operationorder_out = vector2(0.0, 0.0); + NG_switch_vector2I(N_addpivot_out, N_addpivot2_out, vector2(0.000000, 0.000000), vector2(0.000000, 0.000000), vector2(0.000000, 0.000000), vector2(0.000000, 0.000000), vector2(0.000000, 0.000000), vector2(0.000000, 0.000000), vector2(0.000000, 0.000000), vector2(0.000000, 0.000000), operationorder, N_switch_operationorder_out); + out = N_switch_operationorder_out; +} + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Greysphere_Calibration +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Greysphere_Calibration" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int texcoord1_index = 0 + [[ + string widget = "number" + ]], + vector2 place2d_pivot = {0.500000, 0.500000}, + vector2 place2d_scale = {0.210000, 0.210000}, + float place2d_rotate = 0.000000 + [[ + string widget = "number" + ]], + vector2 place2d_offset = {-1.660000, -0.490000}, + int place2d_operationorder = 0 + [[ + string widget = "number" + ]], + string image1_file = "../../../Images/greysphere_calibration.png" + [[ + string widget = "filename" + ]], + string image1_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string image1_layer = "", + color image1_default = color(0.000000, 0.000000, 0.000000), + string image1_uaddressmode = "clamp", + string image1_vaddressmode = "clamp", + string image1_filtertype = "linear", + string image1_framerange = "", + int image1_frameoffset = 0 + [[ + string widget = "number" + ]], + string image1_frameendaction = "constant", + float SR_Greysphere_Calibration_base = 1.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_metalness = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_specular = 1.000000 + [[ + string widget = "number" + ]], + color SR_Greysphere_Calibration_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_Greysphere_Calibration_specular_roughness = 0.700000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_Greysphere_Calibration_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_Greysphere_Calibration_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_Greysphere_Calibration_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_Greysphere_Calibration_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_Greysphere_Calibration_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_Greysphere_Calibration_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_Greysphere_Calibration_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_Greysphere_Calibration_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_Greysphere_Calibration_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_Greysphere_Calibration_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_Greysphere_Calibration_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_Greysphere_Calibration_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_Greysphere_Calibration_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_Greysphere_Calibration_opacity = color(1.000000, 1.000000, 1.000000), + int SR_Greysphere_Calibration_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource image1_file_ = {image1_file, image1_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 texcoord1_out = vector2(u,v); + vector2 place2d_out = vector2(0.0, 0.0); + NG_place2d_vector2(texcoord1_out, place2d_pivot, place2d_scale, place2d_rotate, place2d_offset, place2d_operationorder, place2d_out); + color image1_out = color(0.0); + mx_image_color3(image1_file_, image1_layer, image1_default, place2d_out, image1_uaddressmode, image1_vaddressmode, image1_filtertype, image1_framerange, image1_frameoffset, image1_frameendaction, image1_out); + surfaceshader SR_Greysphere_Calibration_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_Greysphere_Calibration_base, image1_out, SR_Greysphere_Calibration_diffuse_roughness, SR_Greysphere_Calibration_metalness, SR_Greysphere_Calibration_specular, SR_Greysphere_Calibration_specular_color, SR_Greysphere_Calibration_specular_roughness, SR_Greysphere_Calibration_specular_IOR, SR_Greysphere_Calibration_specular_anisotropy, SR_Greysphere_Calibration_specular_rotation, SR_Greysphere_Calibration_transmission, SR_Greysphere_Calibration_transmission_color, SR_Greysphere_Calibration_transmission_depth, SR_Greysphere_Calibration_transmission_scatter, SR_Greysphere_Calibration_transmission_scatter_anisotropy, SR_Greysphere_Calibration_transmission_dispersion, SR_Greysphere_Calibration_transmission_extra_roughness, SR_Greysphere_Calibration_subsurface, SR_Greysphere_Calibration_subsurface_color, SR_Greysphere_Calibration_subsurface_radius, SR_Greysphere_Calibration_subsurface_scale, SR_Greysphere_Calibration_subsurface_anisotropy, SR_Greysphere_Calibration_sheen, SR_Greysphere_Calibration_sheen_color, SR_Greysphere_Calibration_sheen_roughness, SR_Greysphere_Calibration_coat, SR_Greysphere_Calibration_coat_color, SR_Greysphere_Calibration_coat_roughness, SR_Greysphere_Calibration_coat_anisotropy, SR_Greysphere_Calibration_coat_rotation, SR_Greysphere_Calibration_coat_IOR, geomprop_Nworld_out1, SR_Greysphere_Calibration_coat_affect_color, SR_Greysphere_Calibration_coat_affect_roughness, SR_Greysphere_Calibration_thin_film_thickness, SR_Greysphere_Calibration_thin_film_IOR, SR_Greysphere_Calibration_emission, SR_Greysphere_Calibration_emission_color, SR_Greysphere_Calibration_opacity, SR_Greysphere_Calibration_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_Greysphere_Calibration_out); + MATERIAL Greysphere_Calibration_out = mx_surfacematerial(SR_Greysphere_Calibration_out, backsurfaceshader, displacementshader1); + out = Greysphere_Calibration_out; +} + diff --git a/Materials/Examples/StandardSurface/Jade.glsl.frag b/Materials/Examples/StandardSurface/Jade.glsl.frag new file mode 100644 index 0000000000..8fc37174d0 --- /dev/null +++ b/Materials/Examples/StandardSurface/Jade.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_jade_base = 0.500000; +uniform vec3 SR_jade_base_color = vec3(0.060300, 0.439800, 0.191600); +uniform float SR_jade_diffuse_roughness = 0.000000; +uniform float SR_jade_metalness = 0.000000; +uniform float SR_jade_specular = 1.000000; +uniform vec3 SR_jade_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_jade_specular_roughness = 0.250000; +uniform float SR_jade_specular_IOR = 2.418000; +uniform float SR_jade_specular_anisotropy = 0.500000; +uniform float SR_jade_specular_rotation = 0.000000; +uniform float SR_jade_transmission = 0.000000; +uniform vec3 SR_jade_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_jade_transmission_depth = 0.000000; +uniform vec3 SR_jade_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_jade_transmission_scatter_anisotropy = 0.000000; +uniform float SR_jade_transmission_dispersion = 0.000000; +uniform float SR_jade_transmission_extra_roughness = 0.000000; +uniform float SR_jade_subsurface = 0.400000; +uniform vec3 SR_jade_subsurface_color = vec3(0.060300, 0.439800, 0.191600); +uniform vec3 SR_jade_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_jade_subsurface_scale = 1.000000; +uniform float SR_jade_subsurface_anisotropy = 0.000000; +uniform float SR_jade_sheen = 0.000000; +uniform vec3 SR_jade_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_jade_sheen_roughness = 0.300000; +uniform float SR_jade_coat = 0.000000; +uniform vec3 SR_jade_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_jade_coat_roughness = 0.100000; +uniform float SR_jade_coat_anisotropy = 0.000000; +uniform float SR_jade_coat_rotation = 0.000000; +uniform float SR_jade_coat_IOR = 1.500000; +uniform float SR_jade_coat_affect_color = 0.000000; +uniform float SR_jade_coat_affect_roughness = 0.000000; +uniform float SR_jade_thin_film_thickness = 0.000000; +uniform float SR_jade_thin_film_IOR = 1.500000; +uniform float SR_jade_emission = 0.000000; +uniform vec3 SR_jade_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_jade_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_jade_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_jade_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_jade_base, SR_jade_base_color, SR_jade_diffuse_roughness, SR_jade_metalness, SR_jade_specular, SR_jade_specular_color, SR_jade_specular_roughness, SR_jade_specular_IOR, SR_jade_specular_anisotropy, SR_jade_specular_rotation, SR_jade_transmission, SR_jade_transmission_color, SR_jade_transmission_depth, SR_jade_transmission_scatter, SR_jade_transmission_scatter_anisotropy, SR_jade_transmission_dispersion, SR_jade_transmission_extra_roughness, SR_jade_subsurface, SR_jade_subsurface_color, SR_jade_subsurface_radius, SR_jade_subsurface_scale, SR_jade_subsurface_anisotropy, SR_jade_sheen, SR_jade_sheen_color, SR_jade_sheen_roughness, SR_jade_coat, SR_jade_coat_color, SR_jade_coat_roughness, SR_jade_coat_anisotropy, SR_jade_coat_rotation, SR_jade_coat_IOR, geomprop_Nworld_out1, SR_jade_coat_affect_color, SR_jade_coat_affect_roughness, SR_jade_thin_film_thickness, SR_jade_thin_film_IOR, SR_jade_emission, SR_jade_emission_color, SR_jade_opacity, SR_jade_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_jade_out); + material Jade_out = SR_jade_out; + out1 = vec4(Jade_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Jade.glsl.vert b/Materials/Examples/StandardSurface/Jade.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/Jade.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Jade.mdl b/Materials/Examples/StandardSurface/Jade.mdl new file mode 100644 index 0000000000..94e58326d9 --- /dev/null +++ b/Materials/Examples/StandardSurface/Jade.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Jade +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_jade_base = 0.500000 + [[ + materialx::core::origin("SR_jade/base") + ]], + color SR_jade_base_color = color(0.060300, 0.439800, 0.191600) + [[ + materialx::core::origin("SR_jade/base_color") + ]], + float SR_jade_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_jade/diffuse_roughness") + ]], + float SR_jade_metalness = 0.000000 + [[ + materialx::core::origin("SR_jade/metalness") + ]], + float SR_jade_specular = 1.000000 + [[ + materialx::core::origin("SR_jade/specular") + ]], + color SR_jade_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_jade/specular_color") + ]], + float SR_jade_specular_roughness = 0.250000 + [[ + materialx::core::origin("SR_jade/specular_roughness") + ]], + uniform float SR_jade_specular_IOR = 2.418000 + [[ + materialx::core::origin("SR_jade/specular_IOR") + ]], + float SR_jade_specular_anisotropy = 0.500000 + [[ + materialx::core::origin("SR_jade/specular_anisotropy") + ]], + float SR_jade_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_jade/specular_rotation") + ]], + float SR_jade_transmission = 0.000000 + [[ + materialx::core::origin("SR_jade/transmission") + ]], + color SR_jade_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_jade/transmission_color") + ]], + float SR_jade_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_jade/transmission_depth") + ]], + color SR_jade_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_jade/transmission_scatter") + ]], + float SR_jade_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_jade/transmission_scatter_anisotropy") + ]], + float SR_jade_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_jade/transmission_dispersion") + ]], + float SR_jade_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_jade/transmission_extra_roughness") + ]], + float SR_jade_subsurface = 0.400000 + [[ + materialx::core::origin("SR_jade/subsurface") + ]], + color SR_jade_subsurface_color = color(0.060300, 0.439800, 0.191600) + [[ + materialx::core::origin("SR_jade/subsurface_color") + ]], + color SR_jade_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_jade/subsurface_radius") + ]], + float SR_jade_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_jade/subsurface_scale") + ]], + float SR_jade_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_jade/subsurface_anisotropy") + ]], + float SR_jade_sheen = 0.000000 + [[ + materialx::core::origin("SR_jade/sheen") + ]], + color SR_jade_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_jade/sheen_color") + ]], + float SR_jade_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_jade/sheen_roughness") + ]], + float SR_jade_coat = 0.000000 + [[ + materialx::core::origin("SR_jade/coat") + ]], + color SR_jade_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_jade/coat_color") + ]], + float SR_jade_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_jade/coat_roughness") + ]], + float SR_jade_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_jade/coat_anisotropy") + ]], + float SR_jade_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_jade/coat_rotation") + ]], + uniform float SR_jade_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_jade/coat_IOR") + ]], + float SR_jade_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_jade/coat_affect_color") + ]], + float SR_jade_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_jade/coat_affect_roughness") + ]], + float SR_jade_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_jade/thin_film_thickness") + ]], + float SR_jade_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_jade/thin_film_IOR") + ]], + float SR_jade_emission = 0.000000 + [[ + materialx::core::origin("SR_jade/emission") + ]], + color SR_jade_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_jade/emission_color") + ]], + color SR_jade_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_jade/opacity") + ]], + bool SR_jade_thin_walled = false + [[ + materialx::core::origin("SR_jade/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_jade_out = NG_standard_surface_surfaceshader_100(SR_jade_base, SR_jade_base_color, SR_jade_diffuse_roughness, SR_jade_metalness, SR_jade_specular, SR_jade_specular_color, SR_jade_specular_roughness, SR_jade_specular_IOR, SR_jade_specular_anisotropy, SR_jade_specular_rotation, SR_jade_transmission, SR_jade_transmission_color, SR_jade_transmission_depth, SR_jade_transmission_scatter, SR_jade_transmission_scatter_anisotropy, SR_jade_transmission_dispersion, SR_jade_transmission_extra_roughness, SR_jade_subsurface, SR_jade_subsurface_color, SR_jade_subsurface_radius, SR_jade_subsurface_scale, SR_jade_subsurface_anisotropy, SR_jade_sheen, SR_jade_sheen_color, SR_jade_sheen_roughness, SR_jade_coat, SR_jade_coat_color, SR_jade_coat_roughness, SR_jade_coat_anisotropy, SR_jade_coat_rotation, SR_jade_coat_IOR, geomprop_Nworld_out1, SR_jade_coat_affect_color, SR_jade_coat_affect_roughness, SR_jade_thin_film_thickness, SR_jade_thin_film_IOR, SR_jade_emission, SR_jade_emission_color, SR_jade_opacity, SR_jade_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Jade_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_jade_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Jade_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Jade.msl.frag b/Materials/Examples/StandardSurface/Jade.msl.frag new file mode 100644 index 0000000000..c5d17969bd --- /dev/null +++ b/Materials/Examples/StandardSurface/Jade.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_jade_base; + vec3 SR_jade_base_color; + float SR_jade_diffuse_roughness; + float SR_jade_metalness; + float SR_jade_specular; + vec3 SR_jade_specular_color; + float SR_jade_specular_roughness; + float SR_jade_specular_IOR; + float SR_jade_specular_anisotropy; + float SR_jade_specular_rotation; + float SR_jade_transmission; + vec3 SR_jade_transmission_color; + float SR_jade_transmission_depth; + vec3 SR_jade_transmission_scatter; + float SR_jade_transmission_scatter_anisotropy; + float SR_jade_transmission_dispersion; + float SR_jade_transmission_extra_roughness; + float SR_jade_subsurface; + vec3 SR_jade_subsurface_color; + vec3 SR_jade_subsurface_radius; + float SR_jade_subsurface_scale; + float SR_jade_subsurface_anisotropy; + float SR_jade_sheen; + vec3 SR_jade_sheen_color; + float SR_jade_sheen_roughness; + float SR_jade_coat; + vec3 SR_jade_coat_color; + float SR_jade_coat_roughness; + float SR_jade_coat_anisotropy; + float SR_jade_coat_rotation; + float SR_jade_coat_IOR; + float SR_jade_coat_affect_color; + float SR_jade_coat_affect_roughness; + float SR_jade_thin_film_thickness; + float SR_jade_thin_film_IOR; + float SR_jade_emission; + vec3 SR_jade_emission_color; + vec3 SR_jade_opacity; + bool SR_jade_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_jade_base + + , vec3 SR_jade_base_color + + , float SR_jade_diffuse_roughness + + , float SR_jade_metalness + + , float SR_jade_specular + + , vec3 SR_jade_specular_color + + , float SR_jade_specular_roughness + + , float SR_jade_specular_IOR + + , float SR_jade_specular_anisotropy + + , float SR_jade_specular_rotation + + , float SR_jade_transmission + + , vec3 SR_jade_transmission_color + + , float SR_jade_transmission_depth + + , vec3 SR_jade_transmission_scatter + + , float SR_jade_transmission_scatter_anisotropy + + , float SR_jade_transmission_dispersion + + , float SR_jade_transmission_extra_roughness + + , float SR_jade_subsurface + + , vec3 SR_jade_subsurface_color + + , vec3 SR_jade_subsurface_radius + + , float SR_jade_subsurface_scale + + , float SR_jade_subsurface_anisotropy + + , float SR_jade_sheen + + , vec3 SR_jade_sheen_color + + , float SR_jade_sheen_roughness + + , float SR_jade_coat + + , vec3 SR_jade_coat_color + + , float SR_jade_coat_roughness + + , float SR_jade_coat_anisotropy + + , float SR_jade_coat_rotation + + , float SR_jade_coat_IOR + + , float SR_jade_coat_affect_color + + , float SR_jade_coat_affect_roughness + + , float SR_jade_thin_film_thickness + + , float SR_jade_thin_film_IOR + + , float SR_jade_emission + + , vec3 SR_jade_emission_color + + , vec3 SR_jade_opacity + + , bool SR_jade_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_jade_base(SR_jade_base) + + , SR_jade_base_color(SR_jade_base_color) + + , SR_jade_diffuse_roughness(SR_jade_diffuse_roughness) + + , SR_jade_metalness(SR_jade_metalness) + + , SR_jade_specular(SR_jade_specular) + + , SR_jade_specular_color(SR_jade_specular_color) + + , SR_jade_specular_roughness(SR_jade_specular_roughness) + + , SR_jade_specular_IOR(SR_jade_specular_IOR) + + , SR_jade_specular_anisotropy(SR_jade_specular_anisotropy) + + , SR_jade_specular_rotation(SR_jade_specular_rotation) + + , SR_jade_transmission(SR_jade_transmission) + + , SR_jade_transmission_color(SR_jade_transmission_color) + + , SR_jade_transmission_depth(SR_jade_transmission_depth) + + , SR_jade_transmission_scatter(SR_jade_transmission_scatter) + + , SR_jade_transmission_scatter_anisotropy(SR_jade_transmission_scatter_anisotropy) + + , SR_jade_transmission_dispersion(SR_jade_transmission_dispersion) + + , SR_jade_transmission_extra_roughness(SR_jade_transmission_extra_roughness) + + , SR_jade_subsurface(SR_jade_subsurface) + + , SR_jade_subsurface_color(SR_jade_subsurface_color) + + , SR_jade_subsurface_radius(SR_jade_subsurface_radius) + + , SR_jade_subsurface_scale(SR_jade_subsurface_scale) + + , SR_jade_subsurface_anisotropy(SR_jade_subsurface_anisotropy) + + , SR_jade_sheen(SR_jade_sheen) + + , SR_jade_sheen_color(SR_jade_sheen_color) + + , SR_jade_sheen_roughness(SR_jade_sheen_roughness) + + , SR_jade_coat(SR_jade_coat) + + , SR_jade_coat_color(SR_jade_coat_color) + + , SR_jade_coat_roughness(SR_jade_coat_roughness) + + , SR_jade_coat_anisotropy(SR_jade_coat_anisotropy) + + , SR_jade_coat_rotation(SR_jade_coat_rotation) + + , SR_jade_coat_IOR(SR_jade_coat_IOR) + + , SR_jade_coat_affect_color(SR_jade_coat_affect_color) + + , SR_jade_coat_affect_roughness(SR_jade_coat_affect_roughness) + + , SR_jade_thin_film_thickness(SR_jade_thin_film_thickness) + + , SR_jade_thin_film_IOR(SR_jade_thin_film_IOR) + + , SR_jade_emission(SR_jade_emission) + + , SR_jade_emission_color(SR_jade_emission_color) + + , SR_jade_opacity(SR_jade_opacity) + + , SR_jade_thin_walled(SR_jade_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_jade_base; + + + vec3 SR_jade_base_color; + + + float SR_jade_diffuse_roughness; + + + float SR_jade_metalness; + + + float SR_jade_specular; + + + vec3 SR_jade_specular_color; + + + float SR_jade_specular_roughness; + + + float SR_jade_specular_IOR; + + + float SR_jade_specular_anisotropy; + + + float SR_jade_specular_rotation; + + + float SR_jade_transmission; + + + vec3 SR_jade_transmission_color; + + + float SR_jade_transmission_depth; + + + vec3 SR_jade_transmission_scatter; + + + float SR_jade_transmission_scatter_anisotropy; + + + float SR_jade_transmission_dispersion; + + + float SR_jade_transmission_extra_roughness; + + + float SR_jade_subsurface; + + + vec3 SR_jade_subsurface_color; + + + vec3 SR_jade_subsurface_radius; + + + float SR_jade_subsurface_scale; + + + float SR_jade_subsurface_anisotropy; + + + float SR_jade_sheen; + + + vec3 SR_jade_sheen_color; + + + float SR_jade_sheen_roughness; + + + float SR_jade_coat; + + + vec3 SR_jade_coat_color; + + + float SR_jade_coat_roughness; + + + float SR_jade_coat_anisotropy; + + + float SR_jade_coat_rotation; + + + float SR_jade_coat_IOR; + + + float SR_jade_coat_affect_color; + + + float SR_jade_coat_affect_roughness; + + + float SR_jade_thin_film_thickness; + + + float SR_jade_thin_film_IOR; + + + float SR_jade_emission; + + + vec3 SR_jade_emission_color; + + + vec3 SR_jade_opacity; + + + bool SR_jade_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_jade_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_jade_base, SR_jade_base_color, SR_jade_diffuse_roughness, SR_jade_metalness, SR_jade_specular, SR_jade_specular_color, SR_jade_specular_roughness, SR_jade_specular_IOR, SR_jade_specular_anisotropy, SR_jade_specular_rotation, SR_jade_transmission, SR_jade_transmission_color, SR_jade_transmission_depth, SR_jade_transmission_scatter, SR_jade_transmission_scatter_anisotropy, SR_jade_transmission_dispersion, SR_jade_transmission_extra_roughness, SR_jade_subsurface, SR_jade_subsurface_color, SR_jade_subsurface_radius, SR_jade_subsurface_scale, SR_jade_subsurface_anisotropy, SR_jade_sheen, SR_jade_sheen_color, SR_jade_sheen_roughness, SR_jade_coat, SR_jade_coat_color, SR_jade_coat_roughness, SR_jade_coat_anisotropy, SR_jade_coat_rotation, SR_jade_coat_IOR, geomprop_Nworld_out1, SR_jade_coat_affect_color, SR_jade_coat_affect_roughness, SR_jade_thin_film_thickness, SR_jade_thin_film_IOR, SR_jade_emission, SR_jade_emission_color, SR_jade_opacity, SR_jade_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_jade_out); + material Jade_out = SR_jade_out; + out1 = float4(Jade_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_jade_base + , u_pub.SR_jade_base_color + , u_pub.SR_jade_diffuse_roughness + , u_pub.SR_jade_metalness + , u_pub.SR_jade_specular + , u_pub.SR_jade_specular_color + , u_pub.SR_jade_specular_roughness + , u_pub.SR_jade_specular_IOR + , u_pub.SR_jade_specular_anisotropy + , u_pub.SR_jade_specular_rotation + , u_pub.SR_jade_transmission + , u_pub.SR_jade_transmission_color + , u_pub.SR_jade_transmission_depth + , u_pub.SR_jade_transmission_scatter + , u_pub.SR_jade_transmission_scatter_anisotropy + , u_pub.SR_jade_transmission_dispersion + , u_pub.SR_jade_transmission_extra_roughness + , u_pub.SR_jade_subsurface + , u_pub.SR_jade_subsurface_color + , u_pub.SR_jade_subsurface_radius + , u_pub.SR_jade_subsurface_scale + , u_pub.SR_jade_subsurface_anisotropy + , u_pub.SR_jade_sheen + , u_pub.SR_jade_sheen_color + , u_pub.SR_jade_sheen_roughness + , u_pub.SR_jade_coat + , u_pub.SR_jade_coat_color + , u_pub.SR_jade_coat_roughness + , u_pub.SR_jade_coat_anisotropy + , u_pub.SR_jade_coat_rotation + , u_pub.SR_jade_coat_IOR + , u_pub.SR_jade_coat_affect_color + , u_pub.SR_jade_coat_affect_roughness + , u_pub.SR_jade_thin_film_thickness + , u_pub.SR_jade_thin_film_IOR + , u_pub.SR_jade_emission + , u_pub.SR_jade_emission_color + , u_pub.SR_jade_opacity + , u_pub.SR_jade_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Jade.msl.vert b/Materials/Examples/StandardSurface/Jade.msl.vert new file mode 100644 index 0000000000..02a761f4c7 --- /dev/null +++ b/Materials/Examples/StandardSurface/Jade.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_jade'. Function already called in this scope. + // Omitted node 'Jade'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Jade.osl b/Materials/Examples/StandardSurface/Jade.osl new file mode 100644 index 0000000000..c3c82e0506 --- /dev/null +++ b/Materials/Examples/StandardSurface/Jade.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Jade +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Jade" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_jade_base = 0.500000 + [[ + string widget = "number" + ]], + color SR_jade_base_color = color(0.060300, 0.439800, 0.191600), + float SR_jade_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_jade_metalness = 0.000000 + [[ + string widget = "number" + ]], + float SR_jade_specular = 1.000000 + [[ + string widget = "number" + ]], + color SR_jade_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_jade_specular_roughness = 0.250000 + [[ + string widget = "number" + ]], + float SR_jade_specular_IOR = 2.418000 + [[ + string widget = "number" + ]], + float SR_jade_specular_anisotropy = 0.500000 + [[ + string widget = "number" + ]], + float SR_jade_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_jade_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_jade_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_jade_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_jade_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_jade_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_jade_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_jade_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_jade_subsurface = 0.400000 + [[ + string widget = "number" + ]], + color SR_jade_subsurface_color = color(0.060300, 0.439800, 0.191600), + color SR_jade_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_jade_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_jade_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_jade_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_jade_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_jade_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_jade_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_jade_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_jade_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_jade_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_jade_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_jade_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_jade_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_jade_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_jade_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_jade_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_jade_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_jade_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_jade_opacity = color(1.000000, 1.000000, 1.000000), + int SR_jade_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_jade_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_jade_base, SR_jade_base_color, SR_jade_diffuse_roughness, SR_jade_metalness, SR_jade_specular, SR_jade_specular_color, SR_jade_specular_roughness, SR_jade_specular_IOR, SR_jade_specular_anisotropy, SR_jade_specular_rotation, SR_jade_transmission, SR_jade_transmission_color, SR_jade_transmission_depth, SR_jade_transmission_scatter, SR_jade_transmission_scatter_anisotropy, SR_jade_transmission_dispersion, SR_jade_transmission_extra_roughness, SR_jade_subsurface, SR_jade_subsurface_color, SR_jade_subsurface_radius, SR_jade_subsurface_scale, SR_jade_subsurface_anisotropy, SR_jade_sheen, SR_jade_sheen_color, SR_jade_sheen_roughness, SR_jade_coat, SR_jade_coat_color, SR_jade_coat_roughness, SR_jade_coat_anisotropy, SR_jade_coat_rotation, SR_jade_coat_IOR, geomprop_Nworld_out1, SR_jade_coat_affect_color, SR_jade_coat_affect_roughness, SR_jade_thin_film_thickness, SR_jade_thin_film_IOR, SR_jade_emission, SR_jade_emission_color, SR_jade_opacity, SR_jade_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_jade_out); + MATERIAL Jade_out = mx_surfacematerial(SR_jade_out, backsurfaceshader, displacementshader1); + out = Jade_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Bishop_B.glsl.frag b/Materials/Examples/StandardSurface/M_Bishop_B.glsl.frag new file mode 100644 index 0000000000..ea43002656 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Bishop_B.glsl.frag @@ -0,0 +1,2013 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D diffuse2_file; +uniform int diffuse2_layer = 0; +uniform vec3 diffuse2_default = vec3(0.000000, 0.000000, 0.000000); +uniform int diffuse2_uaddressmode = 2; +uniform int diffuse2_vaddressmode = 2; +uniform int diffuse2_filtertype = 1; +uniform int diffuse2_framerange = 0; +uniform int diffuse2_frameoffset = 0; +uniform int diffuse2_frameendaction = 0; +uniform vec2 diffuse2_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 diffuse2_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D metallic2_file; +uniform int metallic2_layer = 0; +uniform float metallic2_default = 0.000000; +uniform int metallic2_uaddressmode = 2; +uniform int metallic2_vaddressmode = 2; +uniform int metallic2_filtertype = 1; +uniform int metallic2_framerange = 0; +uniform int metallic2_frameoffset = 0; +uniform int metallic2_frameendaction = 0; +uniform vec2 metallic2_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 metallic2_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D roughness2_file; +uniform int roughness2_layer = 0; +uniform float roughness2_default = 0.000000; +uniform int roughness2_uaddressmode = 2; +uniform int roughness2_vaddressmode = 2; +uniform int roughness2_filtertype = 1; +uniform int roughness2_framerange = 0; +uniform int roughness2_frameoffset = 0; +uniform int roughness2_frameendaction = 0; +uniform vec2 roughness2_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 roughness2_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D normal2_file; +uniform int normal2_layer = 0; +uniform vec3 normal2_default = vec3(0.000000, 0.000000, 0.000000); +uniform int normal2_uaddressmode = 2; +uniform int normal2_vaddressmode = 2; +uniform int normal2_filtertype = 1; +uniform int normal2_framerange = 0; +uniform int normal2_frameoffset = 0; +uniform int normal2_frameendaction = 0; +uniform vec2 normal2_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 normal2_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap4_scale = 1.000000; +uniform float Bishop_B_base = 1.000000; +uniform float Bishop_B_diffuse_roughness = 0.000000; +uniform float Bishop_B_specular = 1.000000; +uniform vec3 Bishop_B_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Bishop_B_specular_IOR = 1.500000; +uniform float Bishop_B_specular_anisotropy = 0.000000; +uniform float Bishop_B_specular_rotation = 0.000000; +uniform float Bishop_B_transmission = 0.000000; +uniform vec3 Bishop_B_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Bishop_B_transmission_depth = 0.000000; +uniform vec3 Bishop_B_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Bishop_B_transmission_scatter_anisotropy = 0.000000; +uniform float Bishop_B_transmission_dispersion = 0.000000; +uniform float Bishop_B_transmission_extra_roughness = 0.000000; +uniform float Bishop_B_subsurface = 0.000000; +uniform float Bishop_B_subsurface_scale = 0.003000; +uniform float Bishop_B_subsurface_anisotropy = 0.000000; +uniform float Bishop_B_sheen = 0.000000; +uniform vec3 Bishop_B_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Bishop_B_sheen_roughness = 0.300000; +uniform float Bishop_B_coat = 0.000000; +uniform vec3 Bishop_B_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Bishop_B_coat_roughness = 0.100000; +uniform float Bishop_B_coat_anisotropy = 0.000000; +uniform float Bishop_B_coat_rotation = 0.000000; +uniform float Bishop_B_coat_IOR = 1.500000; +uniform float Bishop_B_coat_affect_color = 0.000000; +uniform float Bishop_B_coat_affect_roughness = 0.000000; +uniform float Bishop_B_thin_film_thickness = 0.000000; +uniform float Bishop_B_thin_film_IOR = 1.500000; +uniform float Bishop_B_emission = 0.000000; +uniform vec3 Bishop_B_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Bishop_B_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Bishop_B_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse2_out = vec3(0.0); + mx_image_color3(diffuse2_file, diffuse2_layer, diffuse2_default, geomprop_UV0_out1, diffuse2_uaddressmode, diffuse2_vaddressmode, diffuse2_filtertype, diffuse2_framerange, diffuse2_frameoffset, diffuse2_frameendaction, diffuse2_uv_scale, diffuse2_uv_offset, diffuse2_out); + float metallic2_out = 0.0; + mx_image_float(metallic2_file, metallic2_layer, metallic2_default, geomprop_UV0_out1, metallic2_uaddressmode, metallic2_vaddressmode, metallic2_filtertype, metallic2_framerange, metallic2_frameoffset, metallic2_frameendaction, metallic2_uv_scale, metallic2_uv_offset, metallic2_out); + float roughness2_out = 0.0; + mx_image_float(roughness2_file, roughness2_layer, roughness2_default, geomprop_UV0_out1, roughness2_uaddressmode, roughness2_vaddressmode, roughness2_filtertype, roughness2_framerange, roughness2_frameoffset, roughness2_frameendaction, roughness2_uv_scale, roughness2_uv_offset, roughness2_out); + vec3 normal2_out = vec3(0.0); + mx_image_vector3(normal2_file, normal2_layer, normal2_default, geomprop_UV0_out1, normal2_uaddressmode, normal2_vaddressmode, normal2_filtertype, normal2_framerange, normal2_frameoffset, normal2_frameendaction, normal2_uv_scale, normal2_uv_offset, normal2_out); + vec3 diffuse2_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse2_out, diffuse2_out_cm_out); + vec3 mtlxnormalmap4_out = vec3(0.0); + mx_normalmap_float(normal2_out, mtlxnormalmap4_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap4_out); + surfaceshader Bishop_B_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Bishop_B_base, diffuse2_out_cm_out, Bishop_B_diffuse_roughness, metallic2_out, Bishop_B_specular, Bishop_B_specular_color, roughness2_out, Bishop_B_specular_IOR, Bishop_B_specular_anisotropy, Bishop_B_specular_rotation, Bishop_B_transmission, Bishop_B_transmission_color, Bishop_B_transmission_depth, Bishop_B_transmission_scatter, Bishop_B_transmission_scatter_anisotropy, Bishop_B_transmission_dispersion, Bishop_B_transmission_extra_roughness, Bishop_B_subsurface, diffuse2_out_cm_out, diffuse2_out_cm_out, Bishop_B_subsurface_scale, Bishop_B_subsurface_anisotropy, Bishop_B_sheen, Bishop_B_sheen_color, Bishop_B_sheen_roughness, Bishop_B_coat, Bishop_B_coat_color, Bishop_B_coat_roughness, Bishop_B_coat_anisotropy, Bishop_B_coat_rotation, Bishop_B_coat_IOR, geomprop_Nworld_out1, Bishop_B_coat_affect_color, Bishop_B_coat_affect_roughness, Bishop_B_thin_film_thickness, Bishop_B_thin_film_IOR, Bishop_B_emission, Bishop_B_emission_color, Bishop_B_opacity, Bishop_B_thin_walled, mtlxnormalmap4_out, geomprop_Tworld_out1, Bishop_B_out); + material M_Bishop_B_out = Bishop_B_out; + out1 = vec4(M_Bishop_B_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Bishop_B.glsl.vert b/Materials/Examples/StandardSurface/M_Bishop_B.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Bishop_B.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Bishop_B.mdl b/Materials/Examples/StandardSurface/M_Bishop_B.mdl new file mode 100644 index 0000000000..518f797ebb --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Bishop_B.mdl @@ -0,0 +1,506 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Bishop_B +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d diffuse2_file = texture_2d("/chess_set/bishop_black_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BishopBlack/diffuse2/file") + ]], + uniform string diffuse2_layer = "" + [[ + materialx::core::origin("NG_BishopBlack/diffuse2/layer") + ]], + color diffuse2_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_BishopBlack/diffuse2/default") + ]], + uniform mx_addressmode_type diffuse2_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopBlack/diffuse2/uaddressmode") + ]], + uniform mx_addressmode_type diffuse2_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopBlack/diffuse2/vaddressmode") + ]], + uniform mx_filterlookup_type diffuse2_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BishopBlack/diffuse2/filtertype") + ]], + uniform string diffuse2_framerange = "" + [[ + materialx::core::origin("NG_BishopBlack/diffuse2/framerange") + ]], + uniform int diffuse2_frameoffset = 0 + [[ + materialx::core::origin("NG_BishopBlack/diffuse2/frameoffset") + ]], + uniform mx_addressmode_type diffuse2_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BishopBlack/diffuse2/frameendaction") + ]], + uniform texture_2d metallic2_file = texture_2d("/chess_set/bishop_shared_metallic.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BishopBlack/metallic2/file") + ]], + uniform string metallic2_layer = "" + [[ + materialx::core::origin("NG_BishopBlack/metallic2/layer") + ]], + float metallic2_default = 0.000000 + [[ + materialx::core::origin("NG_BishopBlack/metallic2/default") + ]], + uniform mx_addressmode_type metallic2_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopBlack/metallic2/uaddressmode") + ]], + uniform mx_addressmode_type metallic2_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopBlack/metallic2/vaddressmode") + ]], + uniform mx_filterlookup_type metallic2_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BishopBlack/metallic2/filtertype") + ]], + uniform string metallic2_framerange = "" + [[ + materialx::core::origin("NG_BishopBlack/metallic2/framerange") + ]], + uniform int metallic2_frameoffset = 0 + [[ + materialx::core::origin("NG_BishopBlack/metallic2/frameoffset") + ]], + uniform mx_addressmode_type metallic2_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BishopBlack/metallic2/frameendaction") + ]], + uniform texture_2d roughness2_file = texture_2d("/chess_set/bishop_black_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BishopBlack/roughness2/file") + ]], + uniform string roughness2_layer = "" + [[ + materialx::core::origin("NG_BishopBlack/roughness2/layer") + ]], + float roughness2_default = 0.000000 + [[ + materialx::core::origin("NG_BishopBlack/roughness2/default") + ]], + uniform mx_addressmode_type roughness2_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopBlack/roughness2/uaddressmode") + ]], + uniform mx_addressmode_type roughness2_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopBlack/roughness2/vaddressmode") + ]], + uniform mx_filterlookup_type roughness2_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BishopBlack/roughness2/filtertype") + ]], + uniform string roughness2_framerange = "" + [[ + materialx::core::origin("NG_BishopBlack/roughness2/framerange") + ]], + uniform int roughness2_frameoffset = 0 + [[ + materialx::core::origin("NG_BishopBlack/roughness2/frameoffset") + ]], + uniform mx_addressmode_type roughness2_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BishopBlack/roughness2/frameendaction") + ]], + uniform texture_2d normal2_file = texture_2d("/chess_set/bishop_black_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BishopBlack/normal2/file") + ]], + uniform string normal2_layer = "" + [[ + materialx::core::origin("NG_BishopBlack/normal2/layer") + ]], + float3 normal2_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_BishopBlack/normal2/default") + ]], + uniform mx_addressmode_type normal2_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopBlack/normal2/uaddressmode") + ]], + uniform mx_addressmode_type normal2_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopBlack/normal2/vaddressmode") + ]], + uniform mx_filterlookup_type normal2_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BishopBlack/normal2/filtertype") + ]], + uniform string normal2_framerange = "" + [[ + materialx::core::origin("NG_BishopBlack/normal2/framerange") + ]], + uniform int normal2_frameoffset = 0 + [[ + materialx::core::origin("NG_BishopBlack/normal2/frameoffset") + ]], + uniform mx_addressmode_type normal2_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BishopBlack/normal2/frameendaction") + ]], + float mtlxnormalmap4_scale = 1.000000 + [[ + materialx::core::origin("NG_BishopBlack/mtlxnormalmap4/scale") + ]], + float Bishop_B_base = 1.000000 + [[ + materialx::core::origin("Bishop_B/base") + ]], + float Bishop_B_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Bishop_B/diffuse_roughness") + ]], + float Bishop_B_specular = 1.000000 + [[ + materialx::core::origin("Bishop_B/specular") + ]], + color Bishop_B_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Bishop_B/specular_color") + ]], + uniform float Bishop_B_specular_IOR = 1.500000 + [[ + materialx::core::origin("Bishop_B/specular_IOR") + ]], + float Bishop_B_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Bishop_B/specular_anisotropy") + ]], + float Bishop_B_specular_rotation = 0.000000 + [[ + materialx::core::origin("Bishop_B/specular_rotation") + ]], + float Bishop_B_transmission = 0.000000 + [[ + materialx::core::origin("Bishop_B/transmission") + ]], + color Bishop_B_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Bishop_B/transmission_color") + ]], + float Bishop_B_transmission_depth = 0.000000 + [[ + materialx::core::origin("Bishop_B/transmission_depth") + ]], + color Bishop_B_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Bishop_B/transmission_scatter") + ]], + float Bishop_B_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Bishop_B/transmission_scatter_anisotropy") + ]], + float Bishop_B_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Bishop_B/transmission_dispersion") + ]], + float Bishop_B_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Bishop_B/transmission_extra_roughness") + ]], + float Bishop_B_subsurface = 0.000000 + [[ + materialx::core::origin("Bishop_B/subsurface") + ]], + float Bishop_B_subsurface_scale = 0.003000 + [[ + materialx::core::origin("Bishop_B/subsurface_scale") + ]], + float Bishop_B_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Bishop_B/subsurface_anisotropy") + ]], + float Bishop_B_sheen = 0.000000 + [[ + materialx::core::origin("Bishop_B/sheen") + ]], + color Bishop_B_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Bishop_B/sheen_color") + ]], + float Bishop_B_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Bishop_B/sheen_roughness") + ]], + float Bishop_B_coat = 0.000000 + [[ + materialx::core::origin("Bishop_B/coat") + ]], + color Bishop_B_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Bishop_B/coat_color") + ]], + float Bishop_B_coat_roughness = 0.100000 + [[ + materialx::core::origin("Bishop_B/coat_roughness") + ]], + float Bishop_B_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Bishop_B/coat_anisotropy") + ]], + float Bishop_B_coat_rotation = 0.000000 + [[ + materialx::core::origin("Bishop_B/coat_rotation") + ]], + uniform float Bishop_B_coat_IOR = 1.500000 + [[ + materialx::core::origin("Bishop_B/coat_IOR") + ]], + float Bishop_B_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Bishop_B/coat_affect_color") + ]], + float Bishop_B_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Bishop_B/coat_affect_roughness") + ]], + float Bishop_B_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Bishop_B/thin_film_thickness") + ]], + float Bishop_B_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Bishop_B/thin_film_IOR") + ]], + float Bishop_B_emission = 0.000000 + [[ + materialx::core::origin("Bishop_B/emission") + ]], + color Bishop_B_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Bishop_B/emission_color") + ]], + color Bishop_B_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Bishop_B/opacity") + ]], + bool Bishop_B_thin_walled = false + [[ + materialx::core::origin("Bishop_B/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color diffuse2_out = materialx::stdlib_1_8::mx_image_color3(diffuse2_file, diffuse2_layer, diffuse2_default, geomprop_UV0_out1, diffuse2_uaddressmode, diffuse2_vaddressmode, diffuse2_filtertype, diffuse2_framerange, diffuse2_frameoffset, diffuse2_frameendaction, mxp_flip_v:false); + float metallic2_out = materialx::stdlib_1_8::mx_image_float(metallic2_file, metallic2_layer, metallic2_default, geomprop_UV0_out1, metallic2_uaddressmode, metallic2_vaddressmode, metallic2_filtertype, metallic2_framerange, metallic2_frameoffset, metallic2_frameendaction, mxp_flip_v:false); + float roughness2_out = materialx::stdlib_1_8::mx_image_float(roughness2_file, roughness2_layer, roughness2_default, geomprop_UV0_out1, roughness2_uaddressmode, roughness2_vaddressmode, roughness2_filtertype, roughness2_framerange, roughness2_frameoffset, roughness2_frameendaction, mxp_flip_v:false); + float3 normal2_out = materialx::stdlib_1_8::mx_image_vector3(normal2_file, normal2_layer, normal2_default, geomprop_UV0_out1, normal2_uaddressmode, normal2_vaddressmode, normal2_filtertype, normal2_framerange, normal2_frameoffset, normal2_frameendaction, mxp_flip_v:false); + color diffuse2_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(diffuse2_out); + float3 mtlxnormalmap4_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:normal2_out, mxp_scale:mtlxnormalmap4_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Bishop_B_out = NG_standard_surface_surfaceshader_100(Bishop_B_base, diffuse2_out_cm_out, Bishop_B_diffuse_roughness, metallic2_out, Bishop_B_specular, Bishop_B_specular_color, roughness2_out, Bishop_B_specular_IOR, Bishop_B_specular_anisotropy, Bishop_B_specular_rotation, Bishop_B_transmission, Bishop_B_transmission_color, Bishop_B_transmission_depth, Bishop_B_transmission_scatter, Bishop_B_transmission_scatter_anisotropy, Bishop_B_transmission_dispersion, Bishop_B_transmission_extra_roughness, Bishop_B_subsurface, diffuse2_out_cm_out, diffuse2_out_cm_out, Bishop_B_subsurface_scale, Bishop_B_subsurface_anisotropy, Bishop_B_sheen, Bishop_B_sheen_color, Bishop_B_sheen_roughness, Bishop_B_coat, Bishop_B_coat_color, Bishop_B_coat_roughness, Bishop_B_coat_anisotropy, Bishop_B_coat_rotation, Bishop_B_coat_IOR, geomprop_Nworld_out1, Bishop_B_coat_affect_color, Bishop_B_coat_affect_roughness, Bishop_B_thin_film_thickness, Bishop_B_thin_film_IOR, Bishop_B_emission, Bishop_B_emission_color, Bishop_B_opacity, Bishop_B_thin_walled, mtlxnormalmap4_out, geomprop_Tworld_out1); + material M_Bishop_B_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Bishop_B_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Bishop_B_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Bishop_B.msl.frag b/Materials/Examples/StandardSurface/M_Bishop_B.msl.frag new file mode 100644 index 0000000000..091069b3c4 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Bishop_B.msl.frag @@ -0,0 +1,2961 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int diffuse2_layer; + vec3 diffuse2_default; + int diffuse2_uaddressmode; + int diffuse2_vaddressmode; + int diffuse2_filtertype; + int diffuse2_framerange; + int diffuse2_frameoffset; + int diffuse2_frameendaction; + vec2 diffuse2_uv_scale; + vec2 diffuse2_uv_offset; + int metallic2_layer; + float metallic2_default; + int metallic2_uaddressmode; + int metallic2_vaddressmode; + int metallic2_filtertype; + int metallic2_framerange; + int metallic2_frameoffset; + int metallic2_frameendaction; + vec2 metallic2_uv_scale; + vec2 metallic2_uv_offset; + int roughness2_layer; + float roughness2_default; + int roughness2_uaddressmode; + int roughness2_vaddressmode; + int roughness2_filtertype; + int roughness2_framerange; + int roughness2_frameoffset; + int roughness2_frameendaction; + vec2 roughness2_uv_scale; + vec2 roughness2_uv_offset; + int normal2_layer; + vec3 normal2_default; + int normal2_uaddressmode; + int normal2_vaddressmode; + int normal2_filtertype; + int normal2_framerange; + int normal2_frameoffset; + int normal2_frameendaction; + vec2 normal2_uv_scale; + vec2 normal2_uv_offset; + float mtlxnormalmap4_scale; + float Bishop_B_base; + float Bishop_B_diffuse_roughness; + float Bishop_B_specular; + vec3 Bishop_B_specular_color; + float Bishop_B_specular_IOR; + float Bishop_B_specular_anisotropy; + float Bishop_B_specular_rotation; + float Bishop_B_transmission; + vec3 Bishop_B_transmission_color; + float Bishop_B_transmission_depth; + vec3 Bishop_B_transmission_scatter; + float Bishop_B_transmission_scatter_anisotropy; + float Bishop_B_transmission_dispersion; + float Bishop_B_transmission_extra_roughness; + float Bishop_B_subsurface; + float Bishop_B_subsurface_scale; + float Bishop_B_subsurface_anisotropy; + float Bishop_B_sheen; + vec3 Bishop_B_sheen_color; + float Bishop_B_sheen_roughness; + float Bishop_B_coat; + vec3 Bishop_B_coat_color; + float Bishop_B_coat_roughness; + float Bishop_B_coat_anisotropy; + float Bishop_B_coat_rotation; + float Bishop_B_coat_IOR; + float Bishop_B_coat_affect_color; + float Bishop_B_coat_affect_roughness; + float Bishop_B_thin_film_thickness; + float Bishop_B_thin_film_IOR; + float Bishop_B_emission; + vec3 Bishop_B_emission_color; + vec3 Bishop_B_opacity; + bool Bishop_B_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture diffuse2_file , int diffuse2_layer + + , vec3 diffuse2_default + + , int diffuse2_uaddressmode + + , int diffuse2_vaddressmode + + , int diffuse2_filtertype + + , int diffuse2_framerange + + , int diffuse2_frameoffset + + , int diffuse2_frameendaction + + , vec2 diffuse2_uv_scale + + , vec2 diffuse2_uv_offset + +, MetalTexture metallic2_file , int metallic2_layer + + , float metallic2_default + + , int metallic2_uaddressmode + + , int metallic2_vaddressmode + + , int metallic2_filtertype + + , int metallic2_framerange + + , int metallic2_frameoffset + + , int metallic2_frameendaction + + , vec2 metallic2_uv_scale + + , vec2 metallic2_uv_offset + +, MetalTexture roughness2_file , int roughness2_layer + + , float roughness2_default + + , int roughness2_uaddressmode + + , int roughness2_vaddressmode + + , int roughness2_filtertype + + , int roughness2_framerange + + , int roughness2_frameoffset + + , int roughness2_frameendaction + + , vec2 roughness2_uv_scale + + , vec2 roughness2_uv_offset + +, MetalTexture normal2_file , int normal2_layer + + , vec3 normal2_default + + , int normal2_uaddressmode + + , int normal2_vaddressmode + + , int normal2_filtertype + + , int normal2_framerange + + , int normal2_frameoffset + + , int normal2_frameendaction + + , vec2 normal2_uv_scale + + , vec2 normal2_uv_offset + + , float mtlxnormalmap4_scale + + , float Bishop_B_base + + , float Bishop_B_diffuse_roughness + + , float Bishop_B_specular + + , vec3 Bishop_B_specular_color + + , float Bishop_B_specular_IOR + + , float Bishop_B_specular_anisotropy + + , float Bishop_B_specular_rotation + + , float Bishop_B_transmission + + , vec3 Bishop_B_transmission_color + + , float Bishop_B_transmission_depth + + , vec3 Bishop_B_transmission_scatter + + , float Bishop_B_transmission_scatter_anisotropy + + , float Bishop_B_transmission_dispersion + + , float Bishop_B_transmission_extra_roughness + + , float Bishop_B_subsurface + + , float Bishop_B_subsurface_scale + + , float Bishop_B_subsurface_anisotropy + + , float Bishop_B_sheen + + , vec3 Bishop_B_sheen_color + + , float Bishop_B_sheen_roughness + + , float Bishop_B_coat + + , vec3 Bishop_B_coat_color + + , float Bishop_B_coat_roughness + + , float Bishop_B_coat_anisotropy + + , float Bishop_B_coat_rotation + + , float Bishop_B_coat_IOR + + , float Bishop_B_coat_affect_color + + , float Bishop_B_coat_affect_roughness + + , float Bishop_B_thin_film_thickness + + , float Bishop_B_thin_film_IOR + + , float Bishop_B_emission + + , vec3 Bishop_B_emission_color + + , vec3 Bishop_B_opacity + + , bool Bishop_B_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, diffuse2_file(diffuse2_file) + , diffuse2_layer(diffuse2_layer) + + , diffuse2_default(diffuse2_default) + + , diffuse2_uaddressmode(diffuse2_uaddressmode) + + , diffuse2_vaddressmode(diffuse2_vaddressmode) + + , diffuse2_filtertype(diffuse2_filtertype) + + , diffuse2_framerange(diffuse2_framerange) + + , diffuse2_frameoffset(diffuse2_frameoffset) + + , diffuse2_frameendaction(diffuse2_frameendaction) + + , diffuse2_uv_scale(diffuse2_uv_scale) + + , diffuse2_uv_offset(diffuse2_uv_offset) + +, metallic2_file(metallic2_file) + , metallic2_layer(metallic2_layer) + + , metallic2_default(metallic2_default) + + , metallic2_uaddressmode(metallic2_uaddressmode) + + , metallic2_vaddressmode(metallic2_vaddressmode) + + , metallic2_filtertype(metallic2_filtertype) + + , metallic2_framerange(metallic2_framerange) + + , metallic2_frameoffset(metallic2_frameoffset) + + , metallic2_frameendaction(metallic2_frameendaction) + + , metallic2_uv_scale(metallic2_uv_scale) + + , metallic2_uv_offset(metallic2_uv_offset) + +, roughness2_file(roughness2_file) + , roughness2_layer(roughness2_layer) + + , roughness2_default(roughness2_default) + + , roughness2_uaddressmode(roughness2_uaddressmode) + + , roughness2_vaddressmode(roughness2_vaddressmode) + + , roughness2_filtertype(roughness2_filtertype) + + , roughness2_framerange(roughness2_framerange) + + , roughness2_frameoffset(roughness2_frameoffset) + + , roughness2_frameendaction(roughness2_frameendaction) + + , roughness2_uv_scale(roughness2_uv_scale) + + , roughness2_uv_offset(roughness2_uv_offset) + +, normal2_file(normal2_file) + , normal2_layer(normal2_layer) + + , normal2_default(normal2_default) + + , normal2_uaddressmode(normal2_uaddressmode) + + , normal2_vaddressmode(normal2_vaddressmode) + + , normal2_filtertype(normal2_filtertype) + + , normal2_framerange(normal2_framerange) + + , normal2_frameoffset(normal2_frameoffset) + + , normal2_frameendaction(normal2_frameendaction) + + , normal2_uv_scale(normal2_uv_scale) + + , normal2_uv_offset(normal2_uv_offset) + + , mtlxnormalmap4_scale(mtlxnormalmap4_scale) + + , Bishop_B_base(Bishop_B_base) + + , Bishop_B_diffuse_roughness(Bishop_B_diffuse_roughness) + + , Bishop_B_specular(Bishop_B_specular) + + , Bishop_B_specular_color(Bishop_B_specular_color) + + , Bishop_B_specular_IOR(Bishop_B_specular_IOR) + + , Bishop_B_specular_anisotropy(Bishop_B_specular_anisotropy) + + , Bishop_B_specular_rotation(Bishop_B_specular_rotation) + + , Bishop_B_transmission(Bishop_B_transmission) + + , Bishop_B_transmission_color(Bishop_B_transmission_color) + + , Bishop_B_transmission_depth(Bishop_B_transmission_depth) + + , Bishop_B_transmission_scatter(Bishop_B_transmission_scatter) + + , Bishop_B_transmission_scatter_anisotropy(Bishop_B_transmission_scatter_anisotropy) + + , Bishop_B_transmission_dispersion(Bishop_B_transmission_dispersion) + + , Bishop_B_transmission_extra_roughness(Bishop_B_transmission_extra_roughness) + + , Bishop_B_subsurface(Bishop_B_subsurface) + + , Bishop_B_subsurface_scale(Bishop_B_subsurface_scale) + + , Bishop_B_subsurface_anisotropy(Bishop_B_subsurface_anisotropy) + + , Bishop_B_sheen(Bishop_B_sheen) + + , Bishop_B_sheen_color(Bishop_B_sheen_color) + + , Bishop_B_sheen_roughness(Bishop_B_sheen_roughness) + + , Bishop_B_coat(Bishop_B_coat) + + , Bishop_B_coat_color(Bishop_B_coat_color) + + , Bishop_B_coat_roughness(Bishop_B_coat_roughness) + + , Bishop_B_coat_anisotropy(Bishop_B_coat_anisotropy) + + , Bishop_B_coat_rotation(Bishop_B_coat_rotation) + + , Bishop_B_coat_IOR(Bishop_B_coat_IOR) + + , Bishop_B_coat_affect_color(Bishop_B_coat_affect_color) + + , Bishop_B_coat_affect_roughness(Bishop_B_coat_affect_roughness) + + , Bishop_B_thin_film_thickness(Bishop_B_thin_film_thickness) + + , Bishop_B_thin_film_IOR(Bishop_B_thin_film_IOR) + + , Bishop_B_emission(Bishop_B_emission) + + , Bishop_B_emission_color(Bishop_B_emission_color) + + , Bishop_B_opacity(Bishop_B_opacity) + + , Bishop_B_thin_walled(Bishop_B_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture diffuse2_file; + int diffuse2_layer; + + + vec3 diffuse2_default; + + + int diffuse2_uaddressmode; + + + int diffuse2_vaddressmode; + + + int diffuse2_filtertype; + + + int diffuse2_framerange; + + + int diffuse2_frameoffset; + + + int diffuse2_frameendaction; + + + vec2 diffuse2_uv_scale; + + + vec2 diffuse2_uv_offset; + + +MetalTexture metallic2_file; + int metallic2_layer; + + + float metallic2_default; + + + int metallic2_uaddressmode; + + + int metallic2_vaddressmode; + + + int metallic2_filtertype; + + + int metallic2_framerange; + + + int metallic2_frameoffset; + + + int metallic2_frameendaction; + + + vec2 metallic2_uv_scale; + + + vec2 metallic2_uv_offset; + + +MetalTexture roughness2_file; + int roughness2_layer; + + + float roughness2_default; + + + int roughness2_uaddressmode; + + + int roughness2_vaddressmode; + + + int roughness2_filtertype; + + + int roughness2_framerange; + + + int roughness2_frameoffset; + + + int roughness2_frameendaction; + + + vec2 roughness2_uv_scale; + + + vec2 roughness2_uv_offset; + + +MetalTexture normal2_file; + int normal2_layer; + + + vec3 normal2_default; + + + int normal2_uaddressmode; + + + int normal2_vaddressmode; + + + int normal2_filtertype; + + + int normal2_framerange; + + + int normal2_frameoffset; + + + int normal2_frameendaction; + + + vec2 normal2_uv_scale; + + + vec2 normal2_uv_offset; + + + float mtlxnormalmap4_scale; + + + float Bishop_B_base; + + + float Bishop_B_diffuse_roughness; + + + float Bishop_B_specular; + + + vec3 Bishop_B_specular_color; + + + float Bishop_B_specular_IOR; + + + float Bishop_B_specular_anisotropy; + + + float Bishop_B_specular_rotation; + + + float Bishop_B_transmission; + + + vec3 Bishop_B_transmission_color; + + + float Bishop_B_transmission_depth; + + + vec3 Bishop_B_transmission_scatter; + + + float Bishop_B_transmission_scatter_anisotropy; + + + float Bishop_B_transmission_dispersion; + + + float Bishop_B_transmission_extra_roughness; + + + float Bishop_B_subsurface; + + + float Bishop_B_subsurface_scale; + + + float Bishop_B_subsurface_anisotropy; + + + float Bishop_B_sheen; + + + vec3 Bishop_B_sheen_color; + + + float Bishop_B_sheen_roughness; + + + float Bishop_B_coat; + + + vec3 Bishop_B_coat_color; + + + float Bishop_B_coat_roughness; + + + float Bishop_B_coat_anisotropy; + + + float Bishop_B_coat_rotation; + + + float Bishop_B_coat_IOR; + + + float Bishop_B_coat_affect_color; + + + float Bishop_B_coat_affect_roughness; + + + float Bishop_B_thin_film_thickness; + + + float Bishop_B_thin_film_IOR; + + + float Bishop_B_emission; + + + vec3 Bishop_B_emission_color; + + + vec3 Bishop_B_opacity; + + + bool Bishop_B_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse2_out = vec3(0.0); + mx_image_color3(diffuse2_file, diffuse2_layer, diffuse2_default, geomprop_UV0_out1, diffuse2_uaddressmode, diffuse2_vaddressmode, diffuse2_filtertype, diffuse2_framerange, diffuse2_frameoffset, diffuse2_frameendaction, diffuse2_uv_scale, diffuse2_uv_offset, diffuse2_out); + float metallic2_out = 0.0; + mx_image_float(metallic2_file, metallic2_layer, metallic2_default, geomprop_UV0_out1, metallic2_uaddressmode, metallic2_vaddressmode, metallic2_filtertype, metallic2_framerange, metallic2_frameoffset, metallic2_frameendaction, metallic2_uv_scale, metallic2_uv_offset, metallic2_out); + float roughness2_out = 0.0; + mx_image_float(roughness2_file, roughness2_layer, roughness2_default, geomprop_UV0_out1, roughness2_uaddressmode, roughness2_vaddressmode, roughness2_filtertype, roughness2_framerange, roughness2_frameoffset, roughness2_frameendaction, roughness2_uv_scale, roughness2_uv_offset, roughness2_out); + vec3 normal2_out = vec3(0.0); + mx_image_vector3(normal2_file, normal2_layer, normal2_default, geomprop_UV0_out1, normal2_uaddressmode, normal2_vaddressmode, normal2_filtertype, normal2_framerange, normal2_frameoffset, normal2_frameendaction, normal2_uv_scale, normal2_uv_offset, normal2_out); + vec3 diffuse2_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse2_out, diffuse2_out_cm_out); + vec3 mtlxnormalmap4_out = vec3(0.0); + mx_normalmap_float(normal2_out, mtlxnormalmap4_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap4_out); + surfaceshader Bishop_B_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Bishop_B_base, diffuse2_out_cm_out, Bishop_B_diffuse_roughness, metallic2_out, Bishop_B_specular, Bishop_B_specular_color, roughness2_out, Bishop_B_specular_IOR, Bishop_B_specular_anisotropy, Bishop_B_specular_rotation, Bishop_B_transmission, Bishop_B_transmission_color, Bishop_B_transmission_depth, Bishop_B_transmission_scatter, Bishop_B_transmission_scatter_anisotropy, Bishop_B_transmission_dispersion, Bishop_B_transmission_extra_roughness, Bishop_B_subsurface, diffuse2_out_cm_out, diffuse2_out_cm_out, Bishop_B_subsurface_scale, Bishop_B_subsurface_anisotropy, Bishop_B_sheen, Bishop_B_sheen_color, Bishop_B_sheen_roughness, Bishop_B_coat, Bishop_B_coat_color, Bishop_B_coat_roughness, Bishop_B_coat_anisotropy, Bishop_B_coat_rotation, Bishop_B_coat_IOR, geomprop_Nworld_out1, Bishop_B_coat_affect_color, Bishop_B_coat_affect_roughness, Bishop_B_thin_film_thickness, Bishop_B_thin_film_IOR, Bishop_B_emission, Bishop_B_emission_color, Bishop_B_opacity, Bishop_B_thin_walled, mtlxnormalmap4_out, geomprop_Tworld_out1, Bishop_B_out); + material M_Bishop_B_out = Bishop_B_out; + out1 = float4(M_Bishop_B_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d diffuse2_file_tex [[texture(0)]], sampler diffuse2_file_sampler [[sampler(0)]] +, texture2d metallic2_file_tex [[texture(1)]], sampler metallic2_file_sampler [[sampler(1)]] +, texture2d roughness2_file_tex [[texture(2)]], sampler roughness2_file_sampler [[sampler(2)]] +, texture2d normal2_file_tex [[texture(3)]], sampler normal2_file_sampler [[sampler(3)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(4)]], sampler u_envRadiance_sampler [[sampler(4)]] +, texture2d u_envIrradiance_tex [[texture(5)]], sampler u_envIrradiance_sampler [[sampler(5)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +diffuse2_file_tex, diffuse2_file_sampler } + , u_pub.diffuse2_layer + , u_pub.diffuse2_default + , u_pub.diffuse2_uaddressmode + , u_pub.diffuse2_vaddressmode + , u_pub.diffuse2_filtertype + , u_pub.diffuse2_framerange + , u_pub.diffuse2_frameoffset + , u_pub.diffuse2_frameendaction + , u_pub.diffuse2_uv_scale + , u_pub.diffuse2_uv_offset +, MetalTexture { +metallic2_file_tex, metallic2_file_sampler } + , u_pub.metallic2_layer + , u_pub.metallic2_default + , u_pub.metallic2_uaddressmode + , u_pub.metallic2_vaddressmode + , u_pub.metallic2_filtertype + , u_pub.metallic2_framerange + , u_pub.metallic2_frameoffset + , u_pub.metallic2_frameendaction + , u_pub.metallic2_uv_scale + , u_pub.metallic2_uv_offset +, MetalTexture { +roughness2_file_tex, roughness2_file_sampler } + , u_pub.roughness2_layer + , u_pub.roughness2_default + , u_pub.roughness2_uaddressmode + , u_pub.roughness2_vaddressmode + , u_pub.roughness2_filtertype + , u_pub.roughness2_framerange + , u_pub.roughness2_frameoffset + , u_pub.roughness2_frameendaction + , u_pub.roughness2_uv_scale + , u_pub.roughness2_uv_offset +, MetalTexture { +normal2_file_tex, normal2_file_sampler } + , u_pub.normal2_layer + , u_pub.normal2_default + , u_pub.normal2_uaddressmode + , u_pub.normal2_vaddressmode + , u_pub.normal2_filtertype + , u_pub.normal2_framerange + , u_pub.normal2_frameoffset + , u_pub.normal2_frameendaction + , u_pub.normal2_uv_scale + , u_pub.normal2_uv_offset + , u_pub.mtlxnormalmap4_scale + , u_pub.Bishop_B_base + , u_pub.Bishop_B_diffuse_roughness + , u_pub.Bishop_B_specular + , u_pub.Bishop_B_specular_color + , u_pub.Bishop_B_specular_IOR + , u_pub.Bishop_B_specular_anisotropy + , u_pub.Bishop_B_specular_rotation + , u_pub.Bishop_B_transmission + , u_pub.Bishop_B_transmission_color + , u_pub.Bishop_B_transmission_depth + , u_pub.Bishop_B_transmission_scatter + , u_pub.Bishop_B_transmission_scatter_anisotropy + , u_pub.Bishop_B_transmission_dispersion + , u_pub.Bishop_B_transmission_extra_roughness + , u_pub.Bishop_B_subsurface + , u_pub.Bishop_B_subsurface_scale + , u_pub.Bishop_B_subsurface_anisotropy + , u_pub.Bishop_B_sheen + , u_pub.Bishop_B_sheen_color + , u_pub.Bishop_B_sheen_roughness + , u_pub.Bishop_B_coat + , u_pub.Bishop_B_coat_color + , u_pub.Bishop_B_coat_roughness + , u_pub.Bishop_B_coat_anisotropy + , u_pub.Bishop_B_coat_rotation + , u_pub.Bishop_B_coat_IOR + , u_pub.Bishop_B_coat_affect_color + , u_pub.Bishop_B_coat_affect_roughness + , u_pub.Bishop_B_thin_film_thickness + , u_pub.Bishop_B_thin_film_IOR + , u_pub.Bishop_B_emission + , u_pub.Bishop_B_emission_color + , u_pub.Bishop_B_opacity + , u_pub.Bishop_B_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Bishop_B.msl.vert b/Materials/Examples/StandardSurface/M_Bishop_B.msl.vert new file mode 100644 index 0000000000..bb42f84dd2 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Bishop_B.msl.vert @@ -0,0 +1,127 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'diffuse2'. Function already called in this scope. + // Omitted node 'metallic2'. Function already called in this scope. + // Omitted node 'roughness2'. Function already called in this scope. + // Omitted node 'normal2'. Function already called in this scope. + // Omitted node 'diffuse2_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap4'. Function already called in this scope. + // Omitted node 'Bishop_B'. Function already called in this scope. + // Omitted node 'M_Bishop_B'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Bishop_B.osl b/Materials/Examples/StandardSurface/M_Bishop_B.osl new file mode 100644 index 0000000000..efa18fe6c5 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Bishop_B.osl @@ -0,0 +1,678 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Bishop_B +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Bishop_B" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string diffuse2_file = "chess_set/bishop_black_base_color.jpg" + [[ + string widget = "filename" + ]], + string diffuse2_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string diffuse2_layer = "", + color diffuse2_default = color(0.000000, 0.000000, 0.000000), + string diffuse2_uaddressmode = "periodic", + string diffuse2_vaddressmode = "periodic", + string diffuse2_filtertype = "linear", + string diffuse2_framerange = "", + int diffuse2_frameoffset = 0 + [[ + string widget = "number" + ]], + string diffuse2_frameendaction = "constant", + string metallic2_file = "chess_set/bishop_shared_metallic.jpg" + [[ + string widget = "filename" + ]], + string metallic2_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string metallic2_layer = "", + float metallic2_default = 0.000000 + [[ + string widget = "number" + ]], + string metallic2_uaddressmode = "periodic", + string metallic2_vaddressmode = "periodic", + string metallic2_filtertype = "linear", + string metallic2_framerange = "", + int metallic2_frameoffset = 0 + [[ + string widget = "number" + ]], + string metallic2_frameendaction = "constant", + string roughness2_file = "chess_set/bishop_black_roughness.jpg" + [[ + string widget = "filename" + ]], + string roughness2_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string roughness2_layer = "", + float roughness2_default = 0.000000 + [[ + string widget = "number" + ]], + string roughness2_uaddressmode = "periodic", + string roughness2_vaddressmode = "periodic", + string roughness2_filtertype = "linear", + string roughness2_framerange = "", + int roughness2_frameoffset = 0 + [[ + string widget = "number" + ]], + string roughness2_frameendaction = "constant", + string normal2_file = "chess_set/bishop_black_normal.jpg" + [[ + string widget = "filename" + ]], + string normal2_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string normal2_layer = "", + vector normal2_default = vector(0.000000, 0.000000, 0.000000), + string normal2_uaddressmode = "periodic", + string normal2_vaddressmode = "periodic", + string normal2_filtertype = "linear", + string normal2_framerange = "", + int normal2_frameoffset = 0 + [[ + string widget = "number" + ]], + string normal2_frameendaction = "constant", + float mtlxnormalmap4_scale = 1.000000 + [[ + string widget = "number" + ]], + float Bishop_B_base = 1.000000 + [[ + string widget = "number" + ]], + float Bishop_B_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_specular = 1.000000 + [[ + string widget = "number" + ]], + color Bishop_B_specular_color = color(1.000000, 1.000000, 1.000000), + float Bishop_B_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Bishop_B_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_transmission = 0.000000 + [[ + string widget = "number" + ]], + color Bishop_B_transmission_color = color(1.000000, 1.000000, 1.000000), + float Bishop_B_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Bishop_B_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Bishop_B_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_subsurface = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float Bishop_B_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Bishop_B_sheen_color = color(1.000000, 1.000000, 1.000000), + float Bishop_B_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Bishop_B_coat = 0.000000 + [[ + string widget = "number" + ]], + color Bishop_B_coat_color = color(1.000000, 1.000000, 1.000000), + float Bishop_B_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Bishop_B_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Bishop_B_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_B_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Bishop_B_emission = 0.000000 + [[ + string widget = "number" + ]], + color Bishop_B_emission_color = color(1.000000, 1.000000, 1.000000), + color Bishop_B_opacity = color(1.000000, 1.000000, 1.000000), + int Bishop_B_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource diffuse2_file_ = {diffuse2_file, diffuse2_file_colorspace}; + textureresource metallic2_file_ = {metallic2_file, metallic2_file_colorspace}; + textureresource roughness2_file_ = {roughness2_file, roughness2_file_colorspace}; + textureresource normal2_file_ = {normal2_file, normal2_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color diffuse2_out = color(0.0); + mx_image_color3(diffuse2_file_, diffuse2_layer, diffuse2_default, geomprop_UV0_out1, diffuse2_uaddressmode, diffuse2_vaddressmode, diffuse2_filtertype, diffuse2_framerange, diffuse2_frameoffset, diffuse2_frameendaction, diffuse2_out); + float metallic2_out = 0.0; + mx_image_float(metallic2_file_, metallic2_layer, metallic2_default, geomprop_UV0_out1, metallic2_uaddressmode, metallic2_vaddressmode, metallic2_filtertype, metallic2_framerange, metallic2_frameoffset, metallic2_frameendaction, metallic2_out); + float roughness2_out = 0.0; + mx_image_float(roughness2_file_, roughness2_layer, roughness2_default, geomprop_UV0_out1, roughness2_uaddressmode, roughness2_vaddressmode, roughness2_filtertype, roughness2_framerange, roughness2_frameoffset, roughness2_frameendaction, roughness2_out); + vector normal2_out = vector(0.0); + mx_image_vector3(normal2_file_, normal2_layer, normal2_default, geomprop_UV0_out1, normal2_uaddressmode, normal2_vaddressmode, normal2_filtertype, normal2_framerange, normal2_frameoffset, normal2_frameendaction, normal2_out); + color diffuse2_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse2_out, diffuse2_out_cm_out); + vector mtlxnormalmap4_out = vector(0.0); + mx_normalmap_float(normal2_out, mtlxnormalmap4_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap4_out); + surfaceshader Bishop_B_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Bishop_B_base, diffuse2_out_cm_out, Bishop_B_diffuse_roughness, metallic2_out, Bishop_B_specular, Bishop_B_specular_color, roughness2_out, Bishop_B_specular_IOR, Bishop_B_specular_anisotropy, Bishop_B_specular_rotation, Bishop_B_transmission, Bishop_B_transmission_color, Bishop_B_transmission_depth, Bishop_B_transmission_scatter, Bishop_B_transmission_scatter_anisotropy, Bishop_B_transmission_dispersion, Bishop_B_transmission_extra_roughness, Bishop_B_subsurface, diffuse2_out_cm_out, diffuse2_out_cm_out, Bishop_B_subsurface_scale, Bishop_B_subsurface_anisotropy, Bishop_B_sheen, Bishop_B_sheen_color, Bishop_B_sheen_roughness, Bishop_B_coat, Bishop_B_coat_color, Bishop_B_coat_roughness, Bishop_B_coat_anisotropy, Bishop_B_coat_rotation, Bishop_B_coat_IOR, geomprop_Nworld_out1, Bishop_B_coat_affect_color, Bishop_B_coat_affect_roughness, Bishop_B_thin_film_thickness, Bishop_B_thin_film_IOR, Bishop_B_emission, Bishop_B_emission_color, Bishop_B_opacity, Bishop_B_thin_walled, mtlxnormalmap4_out, geomprop_Tworld_out1, Bishop_B_out); + MATERIAL M_Bishop_B_out = mx_surfacematerial(Bishop_B_out, backsurfaceshader, displacementshader1); + out = M_Bishop_B_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Bishop_W.glsl.frag b/Materials/Examples/StandardSurface/M_Bishop_W.glsl.frag new file mode 100644 index 0000000000..dca03d8d57 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Bishop_W.glsl.frag @@ -0,0 +1,2013 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D diffuse3_file; +uniform int diffuse3_layer = 0; +uniform vec3 diffuse3_default = vec3(0.000000, 0.000000, 0.000000); +uniform int diffuse3_uaddressmode = 2; +uniform int diffuse3_vaddressmode = 2; +uniform int diffuse3_filtertype = 1; +uniform int diffuse3_framerange = 0; +uniform int diffuse3_frameoffset = 0; +uniform int diffuse3_frameendaction = 0; +uniform vec2 diffuse3_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 diffuse3_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D metallic3_file; +uniform int metallic3_layer = 0; +uniform float metallic3_default = 0.000000; +uniform int metallic3_uaddressmode = 2; +uniform int metallic3_vaddressmode = 2; +uniform int metallic3_filtertype = 1; +uniform int metallic3_framerange = 0; +uniform int metallic3_frameoffset = 0; +uniform int metallic3_frameendaction = 0; +uniform vec2 metallic3_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 metallic3_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D roughness3_file; +uniform int roughness3_layer = 0; +uniform float roughness3_default = 0.000000; +uniform int roughness3_uaddressmode = 2; +uniform int roughness3_vaddressmode = 2; +uniform int roughness3_filtertype = 1; +uniform int roughness3_framerange = 0; +uniform int roughness3_frameoffset = 0; +uniform int roughness3_frameendaction = 0; +uniform vec2 roughness3_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 roughness3_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D normal3_file; +uniform int normal3_layer = 0; +uniform vec3 normal3_default = vec3(0.000000, 0.000000, 0.000000); +uniform int normal3_uaddressmode = 2; +uniform int normal3_vaddressmode = 2; +uniform int normal3_filtertype = 1; +uniform int normal3_framerange = 0; +uniform int normal3_frameoffset = 0; +uniform int normal3_frameendaction = 0; +uniform vec2 normal3_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 normal3_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap5_scale = 1.000000; +uniform float Bishop_W_base = 1.000000; +uniform float Bishop_W_diffuse_roughness = 0.000000; +uniform float Bishop_W_specular = 1.000000; +uniform vec3 Bishop_W_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Bishop_W_specular_IOR = 1.500000; +uniform float Bishop_W_specular_anisotropy = 0.000000; +uniform float Bishop_W_specular_rotation = 0.000000; +uniform float Bishop_W_transmission = 0.000000; +uniform vec3 Bishop_W_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Bishop_W_transmission_depth = 0.000000; +uniform vec3 Bishop_W_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Bishop_W_transmission_scatter_anisotropy = 0.000000; +uniform float Bishop_W_transmission_dispersion = 0.000000; +uniform float Bishop_W_transmission_extra_roughness = 0.000000; +uniform float Bishop_W_subsurface = 0.000000; +uniform float Bishop_W_subsurface_scale = 0.003000; +uniform float Bishop_W_subsurface_anisotropy = 0.000000; +uniform float Bishop_W_sheen = 0.000000; +uniform vec3 Bishop_W_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Bishop_W_sheen_roughness = 0.300000; +uniform float Bishop_W_coat = 0.000000; +uniform vec3 Bishop_W_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Bishop_W_coat_roughness = 0.100000; +uniform float Bishop_W_coat_anisotropy = 0.000000; +uniform float Bishop_W_coat_rotation = 0.000000; +uniform float Bishop_W_coat_IOR = 1.500000; +uniform float Bishop_W_coat_affect_color = 0.000000; +uniform float Bishop_W_coat_affect_roughness = 0.000000; +uniform float Bishop_W_thin_film_thickness = 0.000000; +uniform float Bishop_W_thin_film_IOR = 1.500000; +uniform float Bishop_W_emission = 0.000000; +uniform vec3 Bishop_W_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Bishop_W_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Bishop_W_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse3_out = vec3(0.0); + mx_image_color3(diffuse3_file, diffuse3_layer, diffuse3_default, geomprop_UV0_out1, diffuse3_uaddressmode, diffuse3_vaddressmode, diffuse3_filtertype, diffuse3_framerange, diffuse3_frameoffset, diffuse3_frameendaction, diffuse3_uv_scale, diffuse3_uv_offset, diffuse3_out); + float metallic3_out = 0.0; + mx_image_float(metallic3_file, metallic3_layer, metallic3_default, geomprop_UV0_out1, metallic3_uaddressmode, metallic3_vaddressmode, metallic3_filtertype, metallic3_framerange, metallic3_frameoffset, metallic3_frameendaction, metallic3_uv_scale, metallic3_uv_offset, metallic3_out); + float roughness3_out = 0.0; + mx_image_float(roughness3_file, roughness3_layer, roughness3_default, geomprop_UV0_out1, roughness3_uaddressmode, roughness3_vaddressmode, roughness3_filtertype, roughness3_framerange, roughness3_frameoffset, roughness3_frameendaction, roughness3_uv_scale, roughness3_uv_offset, roughness3_out); + vec3 normal3_out = vec3(0.0); + mx_image_vector3(normal3_file, normal3_layer, normal3_default, geomprop_UV0_out1, normal3_uaddressmode, normal3_vaddressmode, normal3_filtertype, normal3_framerange, normal3_frameoffset, normal3_frameendaction, normal3_uv_scale, normal3_uv_offset, normal3_out); + vec3 diffuse3_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse3_out, diffuse3_out_cm_out); + vec3 mtlxnormalmap5_out = vec3(0.0); + mx_normalmap_float(normal3_out, mtlxnormalmap5_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap5_out); + surfaceshader Bishop_W_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Bishop_W_base, diffuse3_out_cm_out, Bishop_W_diffuse_roughness, metallic3_out, Bishop_W_specular, Bishop_W_specular_color, roughness3_out, Bishop_W_specular_IOR, Bishop_W_specular_anisotropy, Bishop_W_specular_rotation, Bishop_W_transmission, Bishop_W_transmission_color, Bishop_W_transmission_depth, Bishop_W_transmission_scatter, Bishop_W_transmission_scatter_anisotropy, Bishop_W_transmission_dispersion, Bishop_W_transmission_extra_roughness, Bishop_W_subsurface, diffuse3_out_cm_out, diffuse3_out_cm_out, Bishop_W_subsurface_scale, Bishop_W_subsurface_anisotropy, Bishop_W_sheen, Bishop_W_sheen_color, Bishop_W_sheen_roughness, Bishop_W_coat, Bishop_W_coat_color, Bishop_W_coat_roughness, Bishop_W_coat_anisotropy, Bishop_W_coat_rotation, Bishop_W_coat_IOR, geomprop_Nworld_out1, Bishop_W_coat_affect_color, Bishop_W_coat_affect_roughness, Bishop_W_thin_film_thickness, Bishop_W_thin_film_IOR, Bishop_W_emission, Bishop_W_emission_color, Bishop_W_opacity, Bishop_W_thin_walled, mtlxnormalmap5_out, geomprop_Tworld_out1, Bishop_W_out); + material M_Bishop_W_out = Bishop_W_out; + out1 = vec4(M_Bishop_W_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Bishop_W.glsl.vert b/Materials/Examples/StandardSurface/M_Bishop_W.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Bishop_W.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Bishop_W.mdl b/Materials/Examples/StandardSurface/M_Bishop_W.mdl new file mode 100644 index 0000000000..1bde479183 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Bishop_W.mdl @@ -0,0 +1,506 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Bishop_W +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d diffuse3_file = texture_2d("/chess_set/bishop_white_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BishopWhite/diffuse3/file") + ]], + uniform string diffuse3_layer = "" + [[ + materialx::core::origin("NG_BishopWhite/diffuse3/layer") + ]], + color diffuse3_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_BishopWhite/diffuse3/default") + ]], + uniform mx_addressmode_type diffuse3_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopWhite/diffuse3/uaddressmode") + ]], + uniform mx_addressmode_type diffuse3_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopWhite/diffuse3/vaddressmode") + ]], + uniform mx_filterlookup_type diffuse3_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BishopWhite/diffuse3/filtertype") + ]], + uniform string diffuse3_framerange = "" + [[ + materialx::core::origin("NG_BishopWhite/diffuse3/framerange") + ]], + uniform int diffuse3_frameoffset = 0 + [[ + materialx::core::origin("NG_BishopWhite/diffuse3/frameoffset") + ]], + uniform mx_addressmode_type diffuse3_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BishopWhite/diffuse3/frameendaction") + ]], + uniform texture_2d metallic3_file = texture_2d("/chess_set/bishop_shared_metallic.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BishopWhite/metallic3/file") + ]], + uniform string metallic3_layer = "" + [[ + materialx::core::origin("NG_BishopWhite/metallic3/layer") + ]], + float metallic3_default = 0.000000 + [[ + materialx::core::origin("NG_BishopWhite/metallic3/default") + ]], + uniform mx_addressmode_type metallic3_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopWhite/metallic3/uaddressmode") + ]], + uniform mx_addressmode_type metallic3_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopWhite/metallic3/vaddressmode") + ]], + uniform mx_filterlookup_type metallic3_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BishopWhite/metallic3/filtertype") + ]], + uniform string metallic3_framerange = "" + [[ + materialx::core::origin("NG_BishopWhite/metallic3/framerange") + ]], + uniform int metallic3_frameoffset = 0 + [[ + materialx::core::origin("NG_BishopWhite/metallic3/frameoffset") + ]], + uniform mx_addressmode_type metallic3_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BishopWhite/metallic3/frameendaction") + ]], + uniform texture_2d roughness3_file = texture_2d("/chess_set/bishop_white_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BishopWhite/roughness3/file") + ]], + uniform string roughness3_layer = "" + [[ + materialx::core::origin("NG_BishopWhite/roughness3/layer") + ]], + float roughness3_default = 0.000000 + [[ + materialx::core::origin("NG_BishopWhite/roughness3/default") + ]], + uniform mx_addressmode_type roughness3_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopWhite/roughness3/uaddressmode") + ]], + uniform mx_addressmode_type roughness3_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopWhite/roughness3/vaddressmode") + ]], + uniform mx_filterlookup_type roughness3_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BishopWhite/roughness3/filtertype") + ]], + uniform string roughness3_framerange = "" + [[ + materialx::core::origin("NG_BishopWhite/roughness3/framerange") + ]], + uniform int roughness3_frameoffset = 0 + [[ + materialx::core::origin("NG_BishopWhite/roughness3/frameoffset") + ]], + uniform mx_addressmode_type roughness3_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BishopWhite/roughness3/frameendaction") + ]], + uniform texture_2d normal3_file = texture_2d("/chess_set/bishop_white_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BishopWhite/normal3/file") + ]], + uniform string normal3_layer = "" + [[ + materialx::core::origin("NG_BishopWhite/normal3/layer") + ]], + float3 normal3_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_BishopWhite/normal3/default") + ]], + uniform mx_addressmode_type normal3_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopWhite/normal3/uaddressmode") + ]], + uniform mx_addressmode_type normal3_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_BishopWhite/normal3/vaddressmode") + ]], + uniform mx_filterlookup_type normal3_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BishopWhite/normal3/filtertype") + ]], + uniform string normal3_framerange = "" + [[ + materialx::core::origin("NG_BishopWhite/normal3/framerange") + ]], + uniform int normal3_frameoffset = 0 + [[ + materialx::core::origin("NG_BishopWhite/normal3/frameoffset") + ]], + uniform mx_addressmode_type normal3_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BishopWhite/normal3/frameendaction") + ]], + float mtlxnormalmap5_scale = 1.000000 + [[ + materialx::core::origin("NG_BishopWhite/mtlxnormalmap5/scale") + ]], + float Bishop_W_base = 1.000000 + [[ + materialx::core::origin("Bishop_W/base") + ]], + float Bishop_W_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Bishop_W/diffuse_roughness") + ]], + float Bishop_W_specular = 1.000000 + [[ + materialx::core::origin("Bishop_W/specular") + ]], + color Bishop_W_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Bishop_W/specular_color") + ]], + uniform float Bishop_W_specular_IOR = 1.500000 + [[ + materialx::core::origin("Bishop_W/specular_IOR") + ]], + float Bishop_W_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Bishop_W/specular_anisotropy") + ]], + float Bishop_W_specular_rotation = 0.000000 + [[ + materialx::core::origin("Bishop_W/specular_rotation") + ]], + float Bishop_W_transmission = 0.000000 + [[ + materialx::core::origin("Bishop_W/transmission") + ]], + color Bishop_W_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Bishop_W/transmission_color") + ]], + float Bishop_W_transmission_depth = 0.000000 + [[ + materialx::core::origin("Bishop_W/transmission_depth") + ]], + color Bishop_W_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Bishop_W/transmission_scatter") + ]], + float Bishop_W_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Bishop_W/transmission_scatter_anisotropy") + ]], + float Bishop_W_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Bishop_W/transmission_dispersion") + ]], + float Bishop_W_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Bishop_W/transmission_extra_roughness") + ]], + float Bishop_W_subsurface = 0.000000 + [[ + materialx::core::origin("Bishop_W/subsurface") + ]], + float Bishop_W_subsurface_scale = 0.003000 + [[ + materialx::core::origin("Bishop_W/subsurface_scale") + ]], + float Bishop_W_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Bishop_W/subsurface_anisotropy") + ]], + float Bishop_W_sheen = 0.000000 + [[ + materialx::core::origin("Bishop_W/sheen") + ]], + color Bishop_W_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Bishop_W/sheen_color") + ]], + float Bishop_W_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Bishop_W/sheen_roughness") + ]], + float Bishop_W_coat = 0.000000 + [[ + materialx::core::origin("Bishop_W/coat") + ]], + color Bishop_W_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Bishop_W/coat_color") + ]], + float Bishop_W_coat_roughness = 0.100000 + [[ + materialx::core::origin("Bishop_W/coat_roughness") + ]], + float Bishop_W_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Bishop_W/coat_anisotropy") + ]], + float Bishop_W_coat_rotation = 0.000000 + [[ + materialx::core::origin("Bishop_W/coat_rotation") + ]], + uniform float Bishop_W_coat_IOR = 1.500000 + [[ + materialx::core::origin("Bishop_W/coat_IOR") + ]], + float Bishop_W_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Bishop_W/coat_affect_color") + ]], + float Bishop_W_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Bishop_W/coat_affect_roughness") + ]], + float Bishop_W_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Bishop_W/thin_film_thickness") + ]], + float Bishop_W_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Bishop_W/thin_film_IOR") + ]], + float Bishop_W_emission = 0.000000 + [[ + materialx::core::origin("Bishop_W/emission") + ]], + color Bishop_W_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Bishop_W/emission_color") + ]], + color Bishop_W_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Bishop_W/opacity") + ]], + bool Bishop_W_thin_walled = false + [[ + materialx::core::origin("Bishop_W/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color diffuse3_out = materialx::stdlib_1_8::mx_image_color3(diffuse3_file, diffuse3_layer, diffuse3_default, geomprop_UV0_out1, diffuse3_uaddressmode, diffuse3_vaddressmode, diffuse3_filtertype, diffuse3_framerange, diffuse3_frameoffset, diffuse3_frameendaction, mxp_flip_v:false); + float metallic3_out = materialx::stdlib_1_8::mx_image_float(metallic3_file, metallic3_layer, metallic3_default, geomprop_UV0_out1, metallic3_uaddressmode, metallic3_vaddressmode, metallic3_filtertype, metallic3_framerange, metallic3_frameoffset, metallic3_frameendaction, mxp_flip_v:false); + float roughness3_out = materialx::stdlib_1_8::mx_image_float(roughness3_file, roughness3_layer, roughness3_default, geomprop_UV0_out1, roughness3_uaddressmode, roughness3_vaddressmode, roughness3_filtertype, roughness3_framerange, roughness3_frameoffset, roughness3_frameendaction, mxp_flip_v:false); + float3 normal3_out = materialx::stdlib_1_8::mx_image_vector3(normal3_file, normal3_layer, normal3_default, geomprop_UV0_out1, normal3_uaddressmode, normal3_vaddressmode, normal3_filtertype, normal3_framerange, normal3_frameoffset, normal3_frameendaction, mxp_flip_v:false); + color diffuse3_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(diffuse3_out); + float3 mtlxnormalmap5_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:normal3_out, mxp_scale:mtlxnormalmap5_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Bishop_W_out = NG_standard_surface_surfaceshader_100(Bishop_W_base, diffuse3_out_cm_out, Bishop_W_diffuse_roughness, metallic3_out, Bishop_W_specular, Bishop_W_specular_color, roughness3_out, Bishop_W_specular_IOR, Bishop_W_specular_anisotropy, Bishop_W_specular_rotation, Bishop_W_transmission, Bishop_W_transmission_color, Bishop_W_transmission_depth, Bishop_W_transmission_scatter, Bishop_W_transmission_scatter_anisotropy, Bishop_W_transmission_dispersion, Bishop_W_transmission_extra_roughness, Bishop_W_subsurface, diffuse3_out_cm_out, diffuse3_out_cm_out, Bishop_W_subsurface_scale, Bishop_W_subsurface_anisotropy, Bishop_W_sheen, Bishop_W_sheen_color, Bishop_W_sheen_roughness, Bishop_W_coat, Bishop_W_coat_color, Bishop_W_coat_roughness, Bishop_W_coat_anisotropy, Bishop_W_coat_rotation, Bishop_W_coat_IOR, geomprop_Nworld_out1, Bishop_W_coat_affect_color, Bishop_W_coat_affect_roughness, Bishop_W_thin_film_thickness, Bishop_W_thin_film_IOR, Bishop_W_emission, Bishop_W_emission_color, Bishop_W_opacity, Bishop_W_thin_walled, mtlxnormalmap5_out, geomprop_Tworld_out1); + material M_Bishop_W_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Bishop_W_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Bishop_W_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Bishop_W.msl.frag b/Materials/Examples/StandardSurface/M_Bishop_W.msl.frag new file mode 100644 index 0000000000..6ec295521c --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Bishop_W.msl.frag @@ -0,0 +1,2961 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int diffuse3_layer; + vec3 diffuse3_default; + int diffuse3_uaddressmode; + int diffuse3_vaddressmode; + int diffuse3_filtertype; + int diffuse3_framerange; + int diffuse3_frameoffset; + int diffuse3_frameendaction; + vec2 diffuse3_uv_scale; + vec2 diffuse3_uv_offset; + int metallic3_layer; + float metallic3_default; + int metallic3_uaddressmode; + int metallic3_vaddressmode; + int metallic3_filtertype; + int metallic3_framerange; + int metallic3_frameoffset; + int metallic3_frameendaction; + vec2 metallic3_uv_scale; + vec2 metallic3_uv_offset; + int roughness3_layer; + float roughness3_default; + int roughness3_uaddressmode; + int roughness3_vaddressmode; + int roughness3_filtertype; + int roughness3_framerange; + int roughness3_frameoffset; + int roughness3_frameendaction; + vec2 roughness3_uv_scale; + vec2 roughness3_uv_offset; + int normal3_layer; + vec3 normal3_default; + int normal3_uaddressmode; + int normal3_vaddressmode; + int normal3_filtertype; + int normal3_framerange; + int normal3_frameoffset; + int normal3_frameendaction; + vec2 normal3_uv_scale; + vec2 normal3_uv_offset; + float mtlxnormalmap5_scale; + float Bishop_W_base; + float Bishop_W_diffuse_roughness; + float Bishop_W_specular; + vec3 Bishop_W_specular_color; + float Bishop_W_specular_IOR; + float Bishop_W_specular_anisotropy; + float Bishop_W_specular_rotation; + float Bishop_W_transmission; + vec3 Bishop_W_transmission_color; + float Bishop_W_transmission_depth; + vec3 Bishop_W_transmission_scatter; + float Bishop_W_transmission_scatter_anisotropy; + float Bishop_W_transmission_dispersion; + float Bishop_W_transmission_extra_roughness; + float Bishop_W_subsurface; + float Bishop_W_subsurface_scale; + float Bishop_W_subsurface_anisotropy; + float Bishop_W_sheen; + vec3 Bishop_W_sheen_color; + float Bishop_W_sheen_roughness; + float Bishop_W_coat; + vec3 Bishop_W_coat_color; + float Bishop_W_coat_roughness; + float Bishop_W_coat_anisotropy; + float Bishop_W_coat_rotation; + float Bishop_W_coat_IOR; + float Bishop_W_coat_affect_color; + float Bishop_W_coat_affect_roughness; + float Bishop_W_thin_film_thickness; + float Bishop_W_thin_film_IOR; + float Bishop_W_emission; + vec3 Bishop_W_emission_color; + vec3 Bishop_W_opacity; + bool Bishop_W_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture diffuse3_file , int diffuse3_layer + + , vec3 diffuse3_default + + , int diffuse3_uaddressmode + + , int diffuse3_vaddressmode + + , int diffuse3_filtertype + + , int diffuse3_framerange + + , int diffuse3_frameoffset + + , int diffuse3_frameendaction + + , vec2 diffuse3_uv_scale + + , vec2 diffuse3_uv_offset + +, MetalTexture metallic3_file , int metallic3_layer + + , float metallic3_default + + , int metallic3_uaddressmode + + , int metallic3_vaddressmode + + , int metallic3_filtertype + + , int metallic3_framerange + + , int metallic3_frameoffset + + , int metallic3_frameendaction + + , vec2 metallic3_uv_scale + + , vec2 metallic3_uv_offset + +, MetalTexture roughness3_file , int roughness3_layer + + , float roughness3_default + + , int roughness3_uaddressmode + + , int roughness3_vaddressmode + + , int roughness3_filtertype + + , int roughness3_framerange + + , int roughness3_frameoffset + + , int roughness3_frameendaction + + , vec2 roughness3_uv_scale + + , vec2 roughness3_uv_offset + +, MetalTexture normal3_file , int normal3_layer + + , vec3 normal3_default + + , int normal3_uaddressmode + + , int normal3_vaddressmode + + , int normal3_filtertype + + , int normal3_framerange + + , int normal3_frameoffset + + , int normal3_frameendaction + + , vec2 normal3_uv_scale + + , vec2 normal3_uv_offset + + , float mtlxnormalmap5_scale + + , float Bishop_W_base + + , float Bishop_W_diffuse_roughness + + , float Bishop_W_specular + + , vec3 Bishop_W_specular_color + + , float Bishop_W_specular_IOR + + , float Bishop_W_specular_anisotropy + + , float Bishop_W_specular_rotation + + , float Bishop_W_transmission + + , vec3 Bishop_W_transmission_color + + , float Bishop_W_transmission_depth + + , vec3 Bishop_W_transmission_scatter + + , float Bishop_W_transmission_scatter_anisotropy + + , float Bishop_W_transmission_dispersion + + , float Bishop_W_transmission_extra_roughness + + , float Bishop_W_subsurface + + , float Bishop_W_subsurface_scale + + , float Bishop_W_subsurface_anisotropy + + , float Bishop_W_sheen + + , vec3 Bishop_W_sheen_color + + , float Bishop_W_sheen_roughness + + , float Bishop_W_coat + + , vec3 Bishop_W_coat_color + + , float Bishop_W_coat_roughness + + , float Bishop_W_coat_anisotropy + + , float Bishop_W_coat_rotation + + , float Bishop_W_coat_IOR + + , float Bishop_W_coat_affect_color + + , float Bishop_W_coat_affect_roughness + + , float Bishop_W_thin_film_thickness + + , float Bishop_W_thin_film_IOR + + , float Bishop_W_emission + + , vec3 Bishop_W_emission_color + + , vec3 Bishop_W_opacity + + , bool Bishop_W_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, diffuse3_file(diffuse3_file) + , diffuse3_layer(diffuse3_layer) + + , diffuse3_default(diffuse3_default) + + , diffuse3_uaddressmode(diffuse3_uaddressmode) + + , diffuse3_vaddressmode(diffuse3_vaddressmode) + + , diffuse3_filtertype(diffuse3_filtertype) + + , diffuse3_framerange(diffuse3_framerange) + + , diffuse3_frameoffset(diffuse3_frameoffset) + + , diffuse3_frameendaction(diffuse3_frameendaction) + + , diffuse3_uv_scale(diffuse3_uv_scale) + + , diffuse3_uv_offset(diffuse3_uv_offset) + +, metallic3_file(metallic3_file) + , metallic3_layer(metallic3_layer) + + , metallic3_default(metallic3_default) + + , metallic3_uaddressmode(metallic3_uaddressmode) + + , metallic3_vaddressmode(metallic3_vaddressmode) + + , metallic3_filtertype(metallic3_filtertype) + + , metallic3_framerange(metallic3_framerange) + + , metallic3_frameoffset(metallic3_frameoffset) + + , metallic3_frameendaction(metallic3_frameendaction) + + , metallic3_uv_scale(metallic3_uv_scale) + + , metallic3_uv_offset(metallic3_uv_offset) + +, roughness3_file(roughness3_file) + , roughness3_layer(roughness3_layer) + + , roughness3_default(roughness3_default) + + , roughness3_uaddressmode(roughness3_uaddressmode) + + , roughness3_vaddressmode(roughness3_vaddressmode) + + , roughness3_filtertype(roughness3_filtertype) + + , roughness3_framerange(roughness3_framerange) + + , roughness3_frameoffset(roughness3_frameoffset) + + , roughness3_frameendaction(roughness3_frameendaction) + + , roughness3_uv_scale(roughness3_uv_scale) + + , roughness3_uv_offset(roughness3_uv_offset) + +, normal3_file(normal3_file) + , normal3_layer(normal3_layer) + + , normal3_default(normal3_default) + + , normal3_uaddressmode(normal3_uaddressmode) + + , normal3_vaddressmode(normal3_vaddressmode) + + , normal3_filtertype(normal3_filtertype) + + , normal3_framerange(normal3_framerange) + + , normal3_frameoffset(normal3_frameoffset) + + , normal3_frameendaction(normal3_frameendaction) + + , normal3_uv_scale(normal3_uv_scale) + + , normal3_uv_offset(normal3_uv_offset) + + , mtlxnormalmap5_scale(mtlxnormalmap5_scale) + + , Bishop_W_base(Bishop_W_base) + + , Bishop_W_diffuse_roughness(Bishop_W_diffuse_roughness) + + , Bishop_W_specular(Bishop_W_specular) + + , Bishop_W_specular_color(Bishop_W_specular_color) + + , Bishop_W_specular_IOR(Bishop_W_specular_IOR) + + , Bishop_W_specular_anisotropy(Bishop_W_specular_anisotropy) + + , Bishop_W_specular_rotation(Bishop_W_specular_rotation) + + , Bishop_W_transmission(Bishop_W_transmission) + + , Bishop_W_transmission_color(Bishop_W_transmission_color) + + , Bishop_W_transmission_depth(Bishop_W_transmission_depth) + + , Bishop_W_transmission_scatter(Bishop_W_transmission_scatter) + + , Bishop_W_transmission_scatter_anisotropy(Bishop_W_transmission_scatter_anisotropy) + + , Bishop_W_transmission_dispersion(Bishop_W_transmission_dispersion) + + , Bishop_W_transmission_extra_roughness(Bishop_W_transmission_extra_roughness) + + , Bishop_W_subsurface(Bishop_W_subsurface) + + , Bishop_W_subsurface_scale(Bishop_W_subsurface_scale) + + , Bishop_W_subsurface_anisotropy(Bishop_W_subsurface_anisotropy) + + , Bishop_W_sheen(Bishop_W_sheen) + + , Bishop_W_sheen_color(Bishop_W_sheen_color) + + , Bishop_W_sheen_roughness(Bishop_W_sheen_roughness) + + , Bishop_W_coat(Bishop_W_coat) + + , Bishop_W_coat_color(Bishop_W_coat_color) + + , Bishop_W_coat_roughness(Bishop_W_coat_roughness) + + , Bishop_W_coat_anisotropy(Bishop_W_coat_anisotropy) + + , Bishop_W_coat_rotation(Bishop_W_coat_rotation) + + , Bishop_W_coat_IOR(Bishop_W_coat_IOR) + + , Bishop_W_coat_affect_color(Bishop_W_coat_affect_color) + + , Bishop_W_coat_affect_roughness(Bishop_W_coat_affect_roughness) + + , Bishop_W_thin_film_thickness(Bishop_W_thin_film_thickness) + + , Bishop_W_thin_film_IOR(Bishop_W_thin_film_IOR) + + , Bishop_W_emission(Bishop_W_emission) + + , Bishop_W_emission_color(Bishop_W_emission_color) + + , Bishop_W_opacity(Bishop_W_opacity) + + , Bishop_W_thin_walled(Bishop_W_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture diffuse3_file; + int diffuse3_layer; + + + vec3 diffuse3_default; + + + int diffuse3_uaddressmode; + + + int diffuse3_vaddressmode; + + + int diffuse3_filtertype; + + + int diffuse3_framerange; + + + int diffuse3_frameoffset; + + + int diffuse3_frameendaction; + + + vec2 diffuse3_uv_scale; + + + vec2 diffuse3_uv_offset; + + +MetalTexture metallic3_file; + int metallic3_layer; + + + float metallic3_default; + + + int metallic3_uaddressmode; + + + int metallic3_vaddressmode; + + + int metallic3_filtertype; + + + int metallic3_framerange; + + + int metallic3_frameoffset; + + + int metallic3_frameendaction; + + + vec2 metallic3_uv_scale; + + + vec2 metallic3_uv_offset; + + +MetalTexture roughness3_file; + int roughness3_layer; + + + float roughness3_default; + + + int roughness3_uaddressmode; + + + int roughness3_vaddressmode; + + + int roughness3_filtertype; + + + int roughness3_framerange; + + + int roughness3_frameoffset; + + + int roughness3_frameendaction; + + + vec2 roughness3_uv_scale; + + + vec2 roughness3_uv_offset; + + +MetalTexture normal3_file; + int normal3_layer; + + + vec3 normal3_default; + + + int normal3_uaddressmode; + + + int normal3_vaddressmode; + + + int normal3_filtertype; + + + int normal3_framerange; + + + int normal3_frameoffset; + + + int normal3_frameendaction; + + + vec2 normal3_uv_scale; + + + vec2 normal3_uv_offset; + + + float mtlxnormalmap5_scale; + + + float Bishop_W_base; + + + float Bishop_W_diffuse_roughness; + + + float Bishop_W_specular; + + + vec3 Bishop_W_specular_color; + + + float Bishop_W_specular_IOR; + + + float Bishop_W_specular_anisotropy; + + + float Bishop_W_specular_rotation; + + + float Bishop_W_transmission; + + + vec3 Bishop_W_transmission_color; + + + float Bishop_W_transmission_depth; + + + vec3 Bishop_W_transmission_scatter; + + + float Bishop_W_transmission_scatter_anisotropy; + + + float Bishop_W_transmission_dispersion; + + + float Bishop_W_transmission_extra_roughness; + + + float Bishop_W_subsurface; + + + float Bishop_W_subsurface_scale; + + + float Bishop_W_subsurface_anisotropy; + + + float Bishop_W_sheen; + + + vec3 Bishop_W_sheen_color; + + + float Bishop_W_sheen_roughness; + + + float Bishop_W_coat; + + + vec3 Bishop_W_coat_color; + + + float Bishop_W_coat_roughness; + + + float Bishop_W_coat_anisotropy; + + + float Bishop_W_coat_rotation; + + + float Bishop_W_coat_IOR; + + + float Bishop_W_coat_affect_color; + + + float Bishop_W_coat_affect_roughness; + + + float Bishop_W_thin_film_thickness; + + + float Bishop_W_thin_film_IOR; + + + float Bishop_W_emission; + + + vec3 Bishop_W_emission_color; + + + vec3 Bishop_W_opacity; + + + bool Bishop_W_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse3_out = vec3(0.0); + mx_image_color3(diffuse3_file, diffuse3_layer, diffuse3_default, geomprop_UV0_out1, diffuse3_uaddressmode, diffuse3_vaddressmode, diffuse3_filtertype, diffuse3_framerange, diffuse3_frameoffset, diffuse3_frameendaction, diffuse3_uv_scale, diffuse3_uv_offset, diffuse3_out); + float metallic3_out = 0.0; + mx_image_float(metallic3_file, metallic3_layer, metallic3_default, geomprop_UV0_out1, metallic3_uaddressmode, metallic3_vaddressmode, metallic3_filtertype, metallic3_framerange, metallic3_frameoffset, metallic3_frameendaction, metallic3_uv_scale, metallic3_uv_offset, metallic3_out); + float roughness3_out = 0.0; + mx_image_float(roughness3_file, roughness3_layer, roughness3_default, geomprop_UV0_out1, roughness3_uaddressmode, roughness3_vaddressmode, roughness3_filtertype, roughness3_framerange, roughness3_frameoffset, roughness3_frameendaction, roughness3_uv_scale, roughness3_uv_offset, roughness3_out); + vec3 normal3_out = vec3(0.0); + mx_image_vector3(normal3_file, normal3_layer, normal3_default, geomprop_UV0_out1, normal3_uaddressmode, normal3_vaddressmode, normal3_filtertype, normal3_framerange, normal3_frameoffset, normal3_frameendaction, normal3_uv_scale, normal3_uv_offset, normal3_out); + vec3 diffuse3_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse3_out, diffuse3_out_cm_out); + vec3 mtlxnormalmap5_out = vec3(0.0); + mx_normalmap_float(normal3_out, mtlxnormalmap5_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap5_out); + surfaceshader Bishop_W_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Bishop_W_base, diffuse3_out_cm_out, Bishop_W_diffuse_roughness, metallic3_out, Bishop_W_specular, Bishop_W_specular_color, roughness3_out, Bishop_W_specular_IOR, Bishop_W_specular_anisotropy, Bishop_W_specular_rotation, Bishop_W_transmission, Bishop_W_transmission_color, Bishop_W_transmission_depth, Bishop_W_transmission_scatter, Bishop_W_transmission_scatter_anisotropy, Bishop_W_transmission_dispersion, Bishop_W_transmission_extra_roughness, Bishop_W_subsurface, diffuse3_out_cm_out, diffuse3_out_cm_out, Bishop_W_subsurface_scale, Bishop_W_subsurface_anisotropy, Bishop_W_sheen, Bishop_W_sheen_color, Bishop_W_sheen_roughness, Bishop_W_coat, Bishop_W_coat_color, Bishop_W_coat_roughness, Bishop_W_coat_anisotropy, Bishop_W_coat_rotation, Bishop_W_coat_IOR, geomprop_Nworld_out1, Bishop_W_coat_affect_color, Bishop_W_coat_affect_roughness, Bishop_W_thin_film_thickness, Bishop_W_thin_film_IOR, Bishop_W_emission, Bishop_W_emission_color, Bishop_W_opacity, Bishop_W_thin_walled, mtlxnormalmap5_out, geomprop_Tworld_out1, Bishop_W_out); + material M_Bishop_W_out = Bishop_W_out; + out1 = float4(M_Bishop_W_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d diffuse3_file_tex [[texture(0)]], sampler diffuse3_file_sampler [[sampler(0)]] +, texture2d metallic3_file_tex [[texture(1)]], sampler metallic3_file_sampler [[sampler(1)]] +, texture2d roughness3_file_tex [[texture(2)]], sampler roughness3_file_sampler [[sampler(2)]] +, texture2d normal3_file_tex [[texture(3)]], sampler normal3_file_sampler [[sampler(3)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(4)]], sampler u_envRadiance_sampler [[sampler(4)]] +, texture2d u_envIrradiance_tex [[texture(5)]], sampler u_envIrradiance_sampler [[sampler(5)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +diffuse3_file_tex, diffuse3_file_sampler } + , u_pub.diffuse3_layer + , u_pub.diffuse3_default + , u_pub.diffuse3_uaddressmode + , u_pub.diffuse3_vaddressmode + , u_pub.diffuse3_filtertype + , u_pub.diffuse3_framerange + , u_pub.diffuse3_frameoffset + , u_pub.diffuse3_frameendaction + , u_pub.diffuse3_uv_scale + , u_pub.diffuse3_uv_offset +, MetalTexture { +metallic3_file_tex, metallic3_file_sampler } + , u_pub.metallic3_layer + , u_pub.metallic3_default + , u_pub.metallic3_uaddressmode + , u_pub.metallic3_vaddressmode + , u_pub.metallic3_filtertype + , u_pub.metallic3_framerange + , u_pub.metallic3_frameoffset + , u_pub.metallic3_frameendaction + , u_pub.metallic3_uv_scale + , u_pub.metallic3_uv_offset +, MetalTexture { +roughness3_file_tex, roughness3_file_sampler } + , u_pub.roughness3_layer + , u_pub.roughness3_default + , u_pub.roughness3_uaddressmode + , u_pub.roughness3_vaddressmode + , u_pub.roughness3_filtertype + , u_pub.roughness3_framerange + , u_pub.roughness3_frameoffset + , u_pub.roughness3_frameendaction + , u_pub.roughness3_uv_scale + , u_pub.roughness3_uv_offset +, MetalTexture { +normal3_file_tex, normal3_file_sampler } + , u_pub.normal3_layer + , u_pub.normal3_default + , u_pub.normal3_uaddressmode + , u_pub.normal3_vaddressmode + , u_pub.normal3_filtertype + , u_pub.normal3_framerange + , u_pub.normal3_frameoffset + , u_pub.normal3_frameendaction + , u_pub.normal3_uv_scale + , u_pub.normal3_uv_offset + , u_pub.mtlxnormalmap5_scale + , u_pub.Bishop_W_base + , u_pub.Bishop_W_diffuse_roughness + , u_pub.Bishop_W_specular + , u_pub.Bishop_W_specular_color + , u_pub.Bishop_W_specular_IOR + , u_pub.Bishop_W_specular_anisotropy + , u_pub.Bishop_W_specular_rotation + , u_pub.Bishop_W_transmission + , u_pub.Bishop_W_transmission_color + , u_pub.Bishop_W_transmission_depth + , u_pub.Bishop_W_transmission_scatter + , u_pub.Bishop_W_transmission_scatter_anisotropy + , u_pub.Bishop_W_transmission_dispersion + , u_pub.Bishop_W_transmission_extra_roughness + , u_pub.Bishop_W_subsurface + , u_pub.Bishop_W_subsurface_scale + , u_pub.Bishop_W_subsurface_anisotropy + , u_pub.Bishop_W_sheen + , u_pub.Bishop_W_sheen_color + , u_pub.Bishop_W_sheen_roughness + , u_pub.Bishop_W_coat + , u_pub.Bishop_W_coat_color + , u_pub.Bishop_W_coat_roughness + , u_pub.Bishop_W_coat_anisotropy + , u_pub.Bishop_W_coat_rotation + , u_pub.Bishop_W_coat_IOR + , u_pub.Bishop_W_coat_affect_color + , u_pub.Bishop_W_coat_affect_roughness + , u_pub.Bishop_W_thin_film_thickness + , u_pub.Bishop_W_thin_film_IOR + , u_pub.Bishop_W_emission + , u_pub.Bishop_W_emission_color + , u_pub.Bishop_W_opacity + , u_pub.Bishop_W_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Bishop_W.msl.vert b/Materials/Examples/StandardSurface/M_Bishop_W.msl.vert new file mode 100644 index 0000000000..ac6006185b --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Bishop_W.msl.vert @@ -0,0 +1,127 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'diffuse3'. Function already called in this scope. + // Omitted node 'metallic3'. Function already called in this scope. + // Omitted node 'roughness3'. Function already called in this scope. + // Omitted node 'normal3'. Function already called in this scope. + // Omitted node 'diffuse3_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap5'. Function already called in this scope. + // Omitted node 'Bishop_W'. Function already called in this scope. + // Omitted node 'M_Bishop_W'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Bishop_W.osl b/Materials/Examples/StandardSurface/M_Bishop_W.osl new file mode 100644 index 0000000000..c312c1c00d --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Bishop_W.osl @@ -0,0 +1,678 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Bishop_W +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Bishop_W" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string diffuse3_file = "chess_set/bishop_white_base_color.jpg" + [[ + string widget = "filename" + ]], + string diffuse3_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string diffuse3_layer = "", + color diffuse3_default = color(0.000000, 0.000000, 0.000000), + string diffuse3_uaddressmode = "periodic", + string diffuse3_vaddressmode = "periodic", + string diffuse3_filtertype = "linear", + string diffuse3_framerange = "", + int diffuse3_frameoffset = 0 + [[ + string widget = "number" + ]], + string diffuse3_frameendaction = "constant", + string metallic3_file = "chess_set/bishop_shared_metallic.jpg" + [[ + string widget = "filename" + ]], + string metallic3_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string metallic3_layer = "", + float metallic3_default = 0.000000 + [[ + string widget = "number" + ]], + string metallic3_uaddressmode = "periodic", + string metallic3_vaddressmode = "periodic", + string metallic3_filtertype = "linear", + string metallic3_framerange = "", + int metallic3_frameoffset = 0 + [[ + string widget = "number" + ]], + string metallic3_frameendaction = "constant", + string roughness3_file = "chess_set/bishop_white_roughness.jpg" + [[ + string widget = "filename" + ]], + string roughness3_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string roughness3_layer = "", + float roughness3_default = 0.000000 + [[ + string widget = "number" + ]], + string roughness3_uaddressmode = "periodic", + string roughness3_vaddressmode = "periodic", + string roughness3_filtertype = "linear", + string roughness3_framerange = "", + int roughness3_frameoffset = 0 + [[ + string widget = "number" + ]], + string roughness3_frameendaction = "constant", + string normal3_file = "chess_set/bishop_white_normal.jpg" + [[ + string widget = "filename" + ]], + string normal3_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string normal3_layer = "", + vector normal3_default = vector(0.000000, 0.000000, 0.000000), + string normal3_uaddressmode = "periodic", + string normal3_vaddressmode = "periodic", + string normal3_filtertype = "linear", + string normal3_framerange = "", + int normal3_frameoffset = 0 + [[ + string widget = "number" + ]], + string normal3_frameendaction = "constant", + float mtlxnormalmap5_scale = 1.000000 + [[ + string widget = "number" + ]], + float Bishop_W_base = 1.000000 + [[ + string widget = "number" + ]], + float Bishop_W_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_specular = 1.000000 + [[ + string widget = "number" + ]], + color Bishop_W_specular_color = color(1.000000, 1.000000, 1.000000), + float Bishop_W_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Bishop_W_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_transmission = 0.000000 + [[ + string widget = "number" + ]], + color Bishop_W_transmission_color = color(1.000000, 1.000000, 1.000000), + float Bishop_W_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Bishop_W_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Bishop_W_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_subsurface = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float Bishop_W_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Bishop_W_sheen_color = color(1.000000, 1.000000, 1.000000), + float Bishop_W_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Bishop_W_coat = 0.000000 + [[ + string widget = "number" + ]], + color Bishop_W_coat_color = color(1.000000, 1.000000, 1.000000), + float Bishop_W_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Bishop_W_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Bishop_W_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Bishop_W_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Bishop_W_emission = 0.000000 + [[ + string widget = "number" + ]], + color Bishop_W_emission_color = color(1.000000, 1.000000, 1.000000), + color Bishop_W_opacity = color(1.000000, 1.000000, 1.000000), + int Bishop_W_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource diffuse3_file_ = {diffuse3_file, diffuse3_file_colorspace}; + textureresource metallic3_file_ = {metallic3_file, metallic3_file_colorspace}; + textureresource roughness3_file_ = {roughness3_file, roughness3_file_colorspace}; + textureresource normal3_file_ = {normal3_file, normal3_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color diffuse3_out = color(0.0); + mx_image_color3(diffuse3_file_, diffuse3_layer, diffuse3_default, geomprop_UV0_out1, diffuse3_uaddressmode, diffuse3_vaddressmode, diffuse3_filtertype, diffuse3_framerange, diffuse3_frameoffset, diffuse3_frameendaction, diffuse3_out); + float metallic3_out = 0.0; + mx_image_float(metallic3_file_, metallic3_layer, metallic3_default, geomprop_UV0_out1, metallic3_uaddressmode, metallic3_vaddressmode, metallic3_filtertype, metallic3_framerange, metallic3_frameoffset, metallic3_frameendaction, metallic3_out); + float roughness3_out = 0.0; + mx_image_float(roughness3_file_, roughness3_layer, roughness3_default, geomprop_UV0_out1, roughness3_uaddressmode, roughness3_vaddressmode, roughness3_filtertype, roughness3_framerange, roughness3_frameoffset, roughness3_frameendaction, roughness3_out); + vector normal3_out = vector(0.0); + mx_image_vector3(normal3_file_, normal3_layer, normal3_default, geomprop_UV0_out1, normal3_uaddressmode, normal3_vaddressmode, normal3_filtertype, normal3_framerange, normal3_frameoffset, normal3_frameendaction, normal3_out); + color diffuse3_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse3_out, diffuse3_out_cm_out); + vector mtlxnormalmap5_out = vector(0.0); + mx_normalmap_float(normal3_out, mtlxnormalmap5_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap5_out); + surfaceshader Bishop_W_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Bishop_W_base, diffuse3_out_cm_out, Bishop_W_diffuse_roughness, metallic3_out, Bishop_W_specular, Bishop_W_specular_color, roughness3_out, Bishop_W_specular_IOR, Bishop_W_specular_anisotropy, Bishop_W_specular_rotation, Bishop_W_transmission, Bishop_W_transmission_color, Bishop_W_transmission_depth, Bishop_W_transmission_scatter, Bishop_W_transmission_scatter_anisotropy, Bishop_W_transmission_dispersion, Bishop_W_transmission_extra_roughness, Bishop_W_subsurface, diffuse3_out_cm_out, diffuse3_out_cm_out, Bishop_W_subsurface_scale, Bishop_W_subsurface_anisotropy, Bishop_W_sheen, Bishop_W_sheen_color, Bishop_W_sheen_roughness, Bishop_W_coat, Bishop_W_coat_color, Bishop_W_coat_roughness, Bishop_W_coat_anisotropy, Bishop_W_coat_rotation, Bishop_W_coat_IOR, geomprop_Nworld_out1, Bishop_W_coat_affect_color, Bishop_W_coat_affect_roughness, Bishop_W_thin_film_thickness, Bishop_W_thin_film_IOR, Bishop_W_emission, Bishop_W_emission_color, Bishop_W_opacity, Bishop_W_thin_walled, mtlxnormalmap5_out, geomprop_Tworld_out1, Bishop_W_out); + MATERIAL M_Bishop_W_out = mx_surfacematerial(Bishop_W_out, backsurfaceshader, displacementshader1); + out = M_Bishop_W_out; +} + diff --git a/Materials/Examples/StandardSurface/M_BrickPattern.glsl.frag b/Materials/Examples/StandardSurface/M_BrickPattern.glsl.frag new file mode 100644 index 0000000000..2097cb452c --- /dev/null +++ b/Materials/Examples/StandardSurface/M_BrickPattern.glsl.frag @@ -0,0 +1,2143 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform float node_convert_1_in = 3.000000; +uniform vec3 node_rgbtohsv_12_in = vec3(0.661876, 0.190880, 0.000000); +uniform sampler2D node_tiledimage_float_26_file; +uniform float node_tiledimage_float_26_default = 0.000000; +uniform vec2 node_tiledimage_float_26_uvoffset = vec2(0.000000, 0.000000); +uniform vec2 node_tiledimage_float_26_realworldimagesize = vec2(1.000000, 1.000000); +uniform vec2 node_tiledimage_float_26_realworldtilesize = vec2(1.000000, 1.000000); +uniform int node_tiledimage_float_26_filtertype = 1; +uniform int node_tiledimage_float_26_framerange = 0; +uniform int node_tiledimage_float_26_frameoffset = 0; +uniform int node_tiledimage_float_26_frameendaction = 0; +uniform sampler2D node_tiledimage_float_7_file; +uniform float node_tiledimage_float_7_default = 0.000000; +uniform vec2 node_tiledimage_float_7_uvoffset = vec2(0.000000, 0.000000); +uniform vec2 node_tiledimage_float_7_realworldimagesize = vec2(1.000000, 1.000000); +uniform vec2 node_tiledimage_float_7_realworldtilesize = vec2(1.000000, 1.000000); +uniform int node_tiledimage_float_7_filtertype = 1; +uniform int node_tiledimage_float_7_framerange = 0; +uniform int node_tiledimage_float_7_frameoffset = 0; +uniform int node_tiledimage_float_7_frameendaction = 0; +uniform sampler2D node_tiledimage_float_24_file; +uniform float node_tiledimage_float_24_default = 0.000000; +uniform vec2 node_tiledimage_float_24_uvoffset = vec2(0.000000, 0.000000); +uniform vec2 node_tiledimage_float_24_realworldimagesize = vec2(1.000000, 1.000000); +uniform vec2 node_tiledimage_float_24_realworldtilesize = vec2(1.000000, 1.000000); +uniform int node_tiledimage_float_24_filtertype = 1; +uniform int node_tiledimage_float_24_framerange = 0; +uniform int node_tiledimage_float_24_frameoffset = 0; +uniform int node_tiledimage_float_24_frameendaction = 0; +uniform sampler2D node_tiledimage_float_10_file; +uniform float node_tiledimage_float_10_default = 0.000000; +uniform vec2 node_tiledimage_float_10_uvoffset = vec2(0.000000, 0.000000); +uniform vec2 node_tiledimage_float_10_realworldimagesize = vec2(1.000000, 1.000000); +uniform vec2 node_tiledimage_float_10_realworldtilesize = vec2(1.000000, 1.000000); +uniform int node_tiledimage_float_10_filtertype = 1; +uniform int node_tiledimage_float_10_framerange = 0; +uniform int node_tiledimage_float_10_frameoffset = 0; +uniform int node_tiledimage_float_10_frameendaction = 0; +uniform sampler2D node_tiledimage_float_22_file; +uniform float node_tiledimage_float_22_default = 0.000000; +uniform vec2 node_tiledimage_float_22_uvoffset = vec2(0.000000, 0.000000); +uniform vec2 node_tiledimage_float_22_realworldimagesize = vec2(1.000000, 1.000000); +uniform vec2 node_tiledimage_float_22_realworldtilesize = vec2(1.000000, 1.000000); +uniform int node_tiledimage_float_22_filtertype = 1; +uniform int node_tiledimage_float_22_framerange = 0; +uniform int node_tiledimage_float_22_frameoffset = 0; +uniform int node_tiledimage_float_22_frameendaction = 0; +uniform sampler2D node_tiledimage_vector3_27_file; +uniform vec3 node_tiledimage_vector3_27_default = vec3(0.000000, 0.000000, 0.000000); +uniform vec2 node_tiledimage_vector3_27_uvoffset = vec2(0.000000, 0.000000); +uniform vec2 node_tiledimage_vector3_27_realworldimagesize = vec2(1.000000, 1.000000); +uniform vec2 node_tiledimage_vector3_27_realworldtilesize = vec2(1.000000, 1.000000); +uniform int node_tiledimage_vector3_27_filtertype = 1; +uniform int node_tiledimage_vector3_27_framerange = 0; +uniform int node_tiledimage_vector3_27_frameoffset = 0; +uniform int node_tiledimage_vector3_27_frameendaction = 0; +uniform float node_multiply_25_in1 = 0.083000; +uniform float node_multiply_20_in1 = 0.787000; +uniform vec3 node_multiply_9_in1 = vec3(0.263273, 0.263273, 0.263273); +uniform float node_multiply_23_in1 = 0.248000; +uniform float node_max_1_in2 = 0.000010; +uniform float node_normalmap_3_scale = 1.000000; +uniform float node_divide_21_in1 = 0.853000; +uniform float node_subtract_18_in2 = 0.350000; +uniform float node_multiply_14_in2 = 0.083000; +uniform float node_combine3_color3_13_in2 = 0.000000; +uniform vec3 node_mix_6_fg = vec3(0.563720, 0.563720, 0.563720); +uniform vec3 node_clamp_0_low = vec3(0.000000, 0.000000, 0.000000); +uniform vec3 node_clamp_0_high = vec3(1.000000, 1.000000, 1.000000); +uniform float N_StandardSurface_base = 1.000000; +uniform float N_StandardSurface_diffuse_roughness = 0.000000; +uniform float N_StandardSurface_metalness = 0.000000; +uniform float N_StandardSurface_specular = 1.000000; +uniform vec3 N_StandardSurface_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float N_StandardSurface_specular_IOR = 1.500000; +uniform float N_StandardSurface_specular_anisotropy = 0.000000; +uniform float N_StandardSurface_specular_rotation = 0.000000; +uniform float N_StandardSurface_transmission = 0.000000; +uniform vec3 N_StandardSurface_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float N_StandardSurface_transmission_depth = 0.000000; +uniform vec3 N_StandardSurface_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float N_StandardSurface_transmission_scatter_anisotropy = 0.000000; +uniform float N_StandardSurface_transmission_dispersion = 0.000000; +uniform float N_StandardSurface_transmission_extra_roughness = 0.000000; +uniform float N_StandardSurface_subsurface = 0.000000; +uniform vec3 N_StandardSurface_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 N_StandardSurface_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float N_StandardSurface_subsurface_scale = 1.000000; +uniform float N_StandardSurface_subsurface_anisotropy = 0.000000; +uniform float N_StandardSurface_sheen = 0.000000; +uniform vec3 N_StandardSurface_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float N_StandardSurface_sheen_roughness = 0.300000; +uniform float N_StandardSurface_coat = 0.000000; +uniform vec3 N_StandardSurface_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float N_StandardSurface_coat_roughness = 0.100000; +uniform float N_StandardSurface_coat_anisotropy = 0.000000; +uniform float N_StandardSurface_coat_rotation = 0.000000; +uniform float N_StandardSurface_coat_IOR = 1.500000; +uniform float N_StandardSurface_coat_affect_color = 0.000000; +uniform float N_StandardSurface_coat_affect_roughness = 0.000000; +uniform float N_StandardSurface_thin_film_thickness = 0.000000; +uniform float N_StandardSurface_thin_film_IOR = 1.500000; +uniform float N_StandardSurface_emission = 0.000000; +uniform vec3 N_StandardSurface_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 N_StandardSurface_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool N_StandardSurface_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec2 texcoord_0; + vec3 normalWorld; + vec3 tangentWorld; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void NG_convert_float_vector2(float in1, out vec2 out1) +{ + vec2 combine_out = vec2(in1,in1); + out1 = combine_out; +} + +/* +Color transform functions. + +These funcions are modified versions of the color operators found in Open Shading Language: +github.com/imageworks/OpenShadingLanguage/blob/master/src/liboslexec/opcolor.cpp + +It contains the subset of color operators needed to implement the MaterialX +standard library. The modifications are for conversions from C++ to GLSL. + +Original copyright notice: +------------------------------------------------------------------------ +Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of Sony Pictures Imageworks nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +------------------------------------------------------------------------ +*/ + +vec3 mx_hsvtorgb(vec3 hsv) +{ + // Reference for this technique: Foley & van Dam + float h = hsv.x; float s = hsv.y; float v = hsv.z; + if (s < 0.0001f) { + return vec3 (v, v, v); + } else { + h = 6.0f * (h - floor(h)); // expand to [0..6) + int hi = int(trunc(h)); + float f = h - float(hi); + float p = v * (1.0f-s); + float q = v * (1.0f-s*f); + float t = v * (1.0f-s*(1.0f-f)); + if (hi == 0) + return vec3 (v, t, p); + else if (hi == 1) + return vec3 (q, v, p); + else if (hi == 2) + return vec3 (p, v, t); + else if (hi == 3) + return vec3 (p, q, v); + else if (hi == 4) + return vec3 (t, p, v); + return vec3 (v, p, q); + } +} + + +vec3 mx_rgbtohsv(vec3 c) +{ + // See Foley & van Dam + float r = c.x; float g = c.y; float b = c.z; + float mincomp = min (r, min(g, b)); + float maxcomp = max (r, max(g, b)); + float delta = maxcomp - mincomp; // chroma + float h, s, v; + v = maxcomp; + if (maxcomp > 0.0f) + s = delta / maxcomp; + else s = 0.0f; + if (s <= 0.0f) + h = 0.0f; + else { + if (r >= maxcomp) h = (g-b) / delta; + else if (g >= maxcomp) h = 2.0f + (b-r) / delta; + else h = 4.0f + (r-g) / delta; + h *= (1.0f/6.0f); + if (h < 0.0f) + h += 1.0f; + } + return vec3(h, s, v); +} + +void mx_rgbtohsv_color3(vec3 _in, out vec3 result) +{ + result = mx_rgbtohsv(_in); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + +void NG_tiledimage_float(sampler2D file, float default1, vec2 texcoord1, vec2 uvtiling, vec2 uvoffset, vec2 realworldimagesize, vec2 realworldtilesize, int filtertype, int framerange, int frameoffset, int frameendaction, out float out1) +{ + vec2 N_mult_float_out = texcoord1 * uvtiling; + vec2 N_sub_float_out = N_mult_float_out - uvoffset; + vec2 N_divtilesize_float_out = N_sub_float_out / realworldimagesize; + vec2 N_multtilesize_float_out = N_divtilesize_float_out * realworldtilesize; + float N_img_float_out = 0.0; + mx_image_float(file, 0, default1, N_multtilesize_float_out, 2, 2, filtertype, framerange, frameoffset, frameendaction, vec2(1.000000, 1.000000), vec2(0.000000, 0.000000), N_img_float_out); + out1 = N_img_float_out; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_tiledimage_vector3(sampler2D file, vec3 default1, vec2 texcoord1, vec2 uvtiling, vec2 uvoffset, vec2 realworldimagesize, vec2 realworldtilesize, int filtertype, int framerange, int frameoffset, int frameendaction, out vec3 out1) +{ + vec2 N_mult_vector3_out = texcoord1 * uvtiling; + vec2 N_sub_vector3_out = N_mult_vector3_out - uvoffset; + vec2 N_divtilesize_vector3_out = N_sub_vector3_out / realworldimagesize; + vec2 N_multtilesize_vector3_out = N_divtilesize_vector3_out * realworldtilesize; + vec3 N_img_vector3_out = vec3(0.0); + mx_image_vector3(file, 0, default1, N_multtilesize_vector3_out, 2, 2, filtertype, framerange, frameoffset, frameendaction, vec2(1.000000, 1.000000), vec2(0.000000, 0.000000), N_img_vector3_out); + out1 = N_img_vector3_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + + +void mx_hsvtorgb_color3(vec3 _in, out vec3 result) +{ + result = mx_hsvtorgb(_in); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec2 node_convert_1_out = vec2(0.0); + NG_convert_float_vector2(node_convert_1_in, node_convert_1_out); + vec3 node_rgbtohsv_12_out = vec3(0.0); + mx_rgbtohsv_color3(node_rgbtohsv_12_in, node_rgbtohsv_12_out); + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + float node_tiledimage_float_26_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_26_file, node_tiledimage_float_26_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_26_uvoffset, node_tiledimage_float_26_realworldimagesize, node_tiledimage_float_26_realworldtilesize, node_tiledimage_float_26_filtertype, node_tiledimage_float_26_framerange, node_tiledimage_float_26_frameoffset, node_tiledimage_float_26_frameendaction, node_tiledimage_float_26_out); + float node_tiledimage_float_7_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_7_file, node_tiledimage_float_7_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_7_uvoffset, node_tiledimage_float_7_realworldimagesize, node_tiledimage_float_7_realworldtilesize, node_tiledimage_float_7_filtertype, node_tiledimage_float_7_framerange, node_tiledimage_float_7_frameoffset, node_tiledimage_float_7_frameendaction, node_tiledimage_float_7_out); + float node_tiledimage_float_24_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_24_file, node_tiledimage_float_24_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_24_uvoffset, node_tiledimage_float_24_realworldimagesize, node_tiledimage_float_24_realworldtilesize, node_tiledimage_float_24_filtertype, node_tiledimage_float_24_framerange, node_tiledimage_float_24_frameoffset, node_tiledimage_float_24_frameendaction, node_tiledimage_float_24_out); + float node_tiledimage_float_10_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_10_file, node_tiledimage_float_10_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_10_uvoffset, node_tiledimage_float_10_realworldimagesize, node_tiledimage_float_10_realworldtilesize, node_tiledimage_float_10_filtertype, node_tiledimage_float_10_framerange, node_tiledimage_float_10_frameoffset, node_tiledimage_float_10_frameendaction, node_tiledimage_float_10_out); + float node_tiledimage_float_22_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_22_file, node_tiledimage_float_22_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_22_uvoffset, node_tiledimage_float_22_realworldimagesize, node_tiledimage_float_22_realworldtilesize, node_tiledimage_float_22_filtertype, node_tiledimage_float_22_framerange, node_tiledimage_float_22_frameoffset, node_tiledimage_float_22_frameendaction, node_tiledimage_float_22_out); + vec3 node_tiledimage_vector3_27_out = vec3(0.0); + NG_tiledimage_vector3(node_tiledimage_vector3_27_file, node_tiledimage_vector3_27_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_vector3_27_uvoffset, node_tiledimage_vector3_27_realworldimagesize, node_tiledimage_vector3_27_realworldtilesize, node_tiledimage_vector3_27_filtertype, node_tiledimage_vector3_27_framerange, node_tiledimage_vector3_27_frameoffset, node_tiledimage_vector3_27_frameendaction, node_tiledimage_vector3_27_out); + float node_multiply_25_out = node_multiply_25_in1 * node_tiledimage_float_26_out; + float node_multiply_20_out = node_multiply_20_in1 * node_tiledimage_float_26_out; + vec3 node_multiply_9_out = node_multiply_9_in1 * node_tiledimage_float_7_out; + float node_multiply_23_out = node_multiply_23_in1 * node_tiledimage_float_24_out; + float node_max_1_out = max(node_tiledimage_float_10_out, node_max_1_in2); + vec3 node_normalmap_3_out = vec3(0.0); + mx_normalmap_float(node_tiledimage_vector3_27_out, node_normalmap_3_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, node_normalmap_3_out); + float node_add_19_out = node_multiply_25_out + node_tiledimage_float_7_out; + float node_divide_21_out = node_divide_21_in1 / node_max_1_out; + float node_subtract_18_out = node_add_19_out - node_subtract_18_in2; + float node_multiply_15_out = node_add_19_out * node_multiply_20_out; + float node_multiply_1_out = node_divide_21_out * node_tiledimage_float_22_out; + float node_multiply_14_out = node_subtract_18_out * node_multiply_14_in2; + vec3 node_combine3_color3_13_out = vec3(node_multiply_14_out,node_combine3_color3_13_in2,node_multiply_15_out); + vec3 node_add_16_out = node_combine3_color3_13_out + node_rgbtohsv_12_out; + vec3 node_hsvtorgb_17_out = vec3(0.0); + mx_hsvtorgb_color3(node_add_16_out, node_hsvtorgb_17_out); + vec3 node_mix_6_out = mix(node_hsvtorgb_17_out, node_mix_6_fg, node_multiply_23_out); + vec3 node_multiply_5_out = node_mix_6_out * node_tiledimage_float_7_out; + vec3 node_mix_8_out = mix(node_multiply_9_out, node_multiply_5_out, node_tiledimage_float_10_out); + vec3 node_clamp_0_out = clamp(node_mix_8_out, node_clamp_0_low, node_clamp_0_high); + surfaceshader N_StandardSurface_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(N_StandardSurface_base, node_clamp_0_out, N_StandardSurface_diffuse_roughness, N_StandardSurface_metalness, N_StandardSurface_specular, N_StandardSurface_specular_color, node_multiply_1_out, N_StandardSurface_specular_IOR, N_StandardSurface_specular_anisotropy, N_StandardSurface_specular_rotation, N_StandardSurface_transmission, N_StandardSurface_transmission_color, N_StandardSurface_transmission_depth, N_StandardSurface_transmission_scatter, N_StandardSurface_transmission_scatter_anisotropy, N_StandardSurface_transmission_dispersion, N_StandardSurface_transmission_extra_roughness, N_StandardSurface_subsurface, N_StandardSurface_subsurface_color, N_StandardSurface_subsurface_radius, N_StandardSurface_subsurface_scale, N_StandardSurface_subsurface_anisotropy, N_StandardSurface_sheen, N_StandardSurface_sheen_color, N_StandardSurface_sheen_roughness, N_StandardSurface_coat, N_StandardSurface_coat_color, N_StandardSurface_coat_roughness, N_StandardSurface_coat_anisotropy, N_StandardSurface_coat_rotation, N_StandardSurface_coat_IOR, geomprop_Nworld_out1, N_StandardSurface_coat_affect_color, N_StandardSurface_coat_affect_roughness, N_StandardSurface_thin_film_thickness, N_StandardSurface_thin_film_IOR, N_StandardSurface_emission, N_StandardSurface_emission_color, N_StandardSurface_opacity, N_StandardSurface_thin_walled, node_normalmap_3_out, geomprop_Tworld_out1, N_StandardSurface_out); + material M_BrickPattern_out = N_StandardSurface_out; + out1 = vec4(M_BrickPattern_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_BrickPattern.glsl.vert b/Materials/Examples/StandardSurface/M_BrickPattern.glsl.vert new file mode 100644 index 0000000000..246b16ef39 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_BrickPattern.glsl.vert @@ -0,0 +1,53 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec2 i_texcoord_0; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec2 texcoord_0; + vec3 normalWorld; + vec3 tangentWorld; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.texcoord_0 = i_texcoord_0; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + // Omitted node 'N_mult_float'. Function already called in this scope. + // Omitted node 'N_sub_float'. Function already called in this scope. + // Omitted node 'N_divtilesize_float'. Function already called in this scope. + // Omitted node 'N_multtilesize_float'. Function already called in this scope. + // Omitted node 'N_img_float'. Function already called in this scope. + // Omitted node 'N_mult_float'. Function already called in this scope. + // Omitted node 'N_sub_float'. Function already called in this scope. + // Omitted node 'N_divtilesize_float'. Function already called in this scope. + // Omitted node 'N_multtilesize_float'. Function already called in this scope. + // Omitted node 'N_img_float'. Function already called in this scope. + // Omitted node 'N_mult_float'. Function already called in this scope. + // Omitted node 'N_sub_float'. Function already called in this scope. + // Omitted node 'N_divtilesize_float'. Function already called in this scope. + // Omitted node 'N_multtilesize_float'. Function already called in this scope. + // Omitted node 'N_img_float'. Function already called in this scope. + // Omitted node 'N_mult_float'. Function already called in this scope. + // Omitted node 'N_sub_float'. Function already called in this scope. + // Omitted node 'N_divtilesize_float'. Function already called in this scope. + // Omitted node 'N_multtilesize_float'. Function already called in this scope. + // Omitted node 'N_img_float'. Function already called in this scope. + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_BrickPattern.mdl b/Materials/Examples/StandardSurface/M_BrickPattern.mdl new file mode 100644 index 0000000000..0b09b51406 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_BrickPattern.mdl @@ -0,0 +1,681 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +float2 NG_convert_float_vector2 +( + float in1 = 0.000000 +) +{ + float2 combine_out = float2( in1,in1 ); + return combine_out; +} + +float NG_tiledimage_float +( + uniform texture_2d file = texture_2d(), + float default1 = 0.000000, + float2 texcoord = float2(state::texture_coordinate(0).x, state::texture_coordinate(0).y), + float2 uvtiling = float2(1.000000, 1.000000), + float2 uvoffset = float2(0.000000, 0.000000), + float2 realworldimagesize = float2(1.000000, 1.000000), + float2 realworldtilesize = float2(1.000000, 1.000000), + uniform mx_filterlookup_type filtertype = mx_filterlookup_type_linear, + uniform string framerange = "", + uniform int frameoffset = 0, + uniform mx_addressmode_type frameendaction = mx_addressmode_type_constant +) +{ + float2 N_mult_float_out = texcoord * uvtiling; + float2 N_sub_float_out = N_mult_float_out - uvoffset; + float2 N_divtilesize_float_out = N_sub_float_out / realworldimagesize; + float2 N_multtilesize_float_out = N_divtilesize_float_out * realworldtilesize; + float N_img_float_out = materialx::stdlib_1_8::mx_image_float(file, "", default1, N_multtilesize_float_out, mx_addressmode_type_periodic, mx_addressmode_type_periodic, filtertype, framerange, frameoffset, frameendaction, mxp_flip_v:false); + return N_img_float_out; +} + +float3 NG_tiledimage_vector3 +( + uniform texture_2d file = texture_2d(), + float3 default1 = float3(0.000000, 0.000000, 0.000000), + float2 texcoord = float2(state::texture_coordinate(0).x, state::texture_coordinate(0).y), + float2 uvtiling = float2(1.000000, 1.000000), + float2 uvoffset = float2(0.000000, 0.000000), + float2 realworldimagesize = float2(1.000000, 1.000000), + float2 realworldtilesize = float2(1.000000, 1.000000), + uniform mx_filterlookup_type filtertype = mx_filterlookup_type_linear, + uniform string framerange = "", + uniform int frameoffset = 0, + uniform mx_addressmode_type frameendaction = mx_addressmode_type_constant +) +{ + float2 N_mult_vector3_out = texcoord * uvtiling; + float2 N_sub_vector3_out = N_mult_vector3_out - uvoffset; + float2 N_divtilesize_vector3_out = N_sub_vector3_out / realworldimagesize; + float2 N_multtilesize_vector3_out = N_divtilesize_vector3_out * realworldtilesize; + float3 N_img_vector3_out = materialx::stdlib_1_8::mx_image_vector3(file, "", default1, N_multtilesize_vector3_out, mx_addressmode_type_periodic, mx_addressmode_type_periodic, filtertype, framerange, frameoffset, frameendaction, mxp_flip_v:false); + return N_img_vector3_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_BrickPattern +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + float node_convert_1_in = 3.000000 + [[ + materialx::core::origin("NG_BrickPattern/uvtiling") + ]], + color node_rgbtohsv_12_in = color(0.661876, 0.190880, 0.000000) + [[ + materialx::core::origin("NG_BrickPattern/brick_color") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d node_tiledimage_float_26_file = texture_2d("../../../Images/brick_variation_mask.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_26/file") + ]], + float node_tiledimage_float_26_default = 0.000000 + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_26/default") + ]], + float2 node_tiledimage_float_26_uvoffset = float2(0.000000, 0.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_26/uvoffset") + ]], + float2 node_tiledimage_float_26_realworldimagesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_26/realworldimagesize") + ]], + float2 node_tiledimage_float_26_realworldtilesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_26/realworldtilesize") + ]], + uniform mx_filterlookup_type node_tiledimage_float_26_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_26/filtertype") + ]], + uniform string node_tiledimage_float_26_framerange = "" + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_26/framerange") + ]], + uniform int node_tiledimage_float_26_frameoffset = 0 + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_26/frameoffset") + ]], + uniform mx_addressmode_type node_tiledimage_float_26_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_26/frameendaction") + ]], + uniform texture_2d node_tiledimage_float_7_file = texture_2d("../../../Images/brick_base_gray.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_7/file") + ]], + float node_tiledimage_float_7_default = 0.000000 + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_7/default") + ]], + float2 node_tiledimage_float_7_uvoffset = float2(0.000000, 0.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_7/uvoffset") + ]], + float2 node_tiledimage_float_7_realworldimagesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_7/realworldimagesize") + ]], + float2 node_tiledimage_float_7_realworldtilesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_7/realworldtilesize") + ]], + uniform mx_filterlookup_type node_tiledimage_float_7_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_7/filtertype") + ]], + uniform string node_tiledimage_float_7_framerange = "" + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_7/framerange") + ]], + uniform int node_tiledimage_float_7_frameoffset = 0 + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_7/frameoffset") + ]], + uniform mx_addressmode_type node_tiledimage_float_7_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_7/frameendaction") + ]], + uniform texture_2d node_tiledimage_float_24_file = texture_2d("../../../Images/brick_dirt_mask.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_24/file") + ]], + float node_tiledimage_float_24_default = 0.000000 + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_24/default") + ]], + float2 node_tiledimage_float_24_uvoffset = float2(0.000000, 0.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_24/uvoffset") + ]], + float2 node_tiledimage_float_24_realworldimagesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_24/realworldimagesize") + ]], + float2 node_tiledimage_float_24_realworldtilesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_24/realworldtilesize") + ]], + uniform mx_filterlookup_type node_tiledimage_float_24_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_24/filtertype") + ]], + uniform string node_tiledimage_float_24_framerange = "" + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_24/framerange") + ]], + uniform int node_tiledimage_float_24_frameoffset = 0 + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_24/frameoffset") + ]], + uniform mx_addressmode_type node_tiledimage_float_24_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_24/frameendaction") + ]], + uniform texture_2d node_tiledimage_float_10_file = texture_2d("../../../Images/brick_mask.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_10/file") + ]], + float node_tiledimage_float_10_default = 0.000000 + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_10/default") + ]], + float2 node_tiledimage_float_10_uvoffset = float2(0.000000, 0.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_10/uvoffset") + ]], + float2 node_tiledimage_float_10_realworldimagesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_10/realworldimagesize") + ]], + float2 node_tiledimage_float_10_realworldtilesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_10/realworldtilesize") + ]], + uniform mx_filterlookup_type node_tiledimage_float_10_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_10/filtertype") + ]], + uniform string node_tiledimage_float_10_framerange = "" + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_10/framerange") + ]], + uniform int node_tiledimage_float_10_frameoffset = 0 + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_10/frameoffset") + ]], + uniform mx_addressmode_type node_tiledimage_float_10_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_10/frameendaction") + ]], + uniform texture_2d node_tiledimage_float_22_file = texture_2d("../../../Images/brick_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_22/file") + ]], + float node_tiledimage_float_22_default = 0.000000 + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_22/default") + ]], + float2 node_tiledimage_float_22_uvoffset = float2(0.000000, 0.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_22/uvoffset") + ]], + float2 node_tiledimage_float_22_realworldimagesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_22/realworldimagesize") + ]], + float2 node_tiledimage_float_22_realworldtilesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_22/realworldtilesize") + ]], + uniform mx_filterlookup_type node_tiledimage_float_22_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_22/filtertype") + ]], + uniform string node_tiledimage_float_22_framerange = "" + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_22/framerange") + ]], + uniform int node_tiledimage_float_22_frameoffset = 0 + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_22/frameoffset") + ]], + uniform mx_addressmode_type node_tiledimage_float_22_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_float_22/frameendaction") + ]], + uniform texture_2d node_tiledimage_vector3_27_file = texture_2d("../../../Images/brick_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_vector3_27/file") + ]], + float3 node_tiledimage_vector3_27_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_vector3_27/default") + ]], + float2 node_tiledimage_vector3_27_uvoffset = float2(0.000000, 0.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_vector3_27/uvoffset") + ]], + float2 node_tiledimage_vector3_27_realworldimagesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_vector3_27/realworldimagesize") + ]], + float2 node_tiledimage_vector3_27_realworldtilesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_vector3_27/realworldtilesize") + ]], + uniform mx_filterlookup_type node_tiledimage_vector3_27_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_vector3_27/filtertype") + ]], + uniform string node_tiledimage_vector3_27_framerange = "" + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_vector3_27/framerange") + ]], + uniform int node_tiledimage_vector3_27_frameoffset = 0 + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_vector3_27/frameoffset") + ]], + uniform mx_addressmode_type node_tiledimage_vector3_27_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_BrickPattern/node_tiledimage_vector3_27/frameendaction") + ]], + float node_multiply_25_in1 = 0.083000 + [[ + materialx::core::origin("NG_BrickPattern/hue_variation") + ]], + float node_multiply_20_in1 = 0.787000 + [[ + materialx::core::origin("NG_BrickPattern/value_variation") + ]], + color node_multiply_9_in1 = color(0.263273, 0.263273, 0.263273) + [[ + materialx::core::origin("NG_BrickPattern/node_color_11/value") + ]], + float node_multiply_23_in1 = 0.248000 + [[ + materialx::core::origin("NG_BrickPattern/dirt_amount") + ]], + float node_max_1_in2 = 0.000010 + [[ + materialx::core::origin("NG_BrickPattern/node_max_1/in2") + ]], + float node_normalmap_3_scale = 1.000000 + [[ + materialx::core::origin("NG_BrickPattern/node_normalmap_3/scale") + ]], + float node_divide_21_in1 = 0.853000 + [[ + materialx::core::origin("NG_BrickPattern/roughness_amount") + ]], + float node_subtract_18_in2 = 0.350000 + [[ + materialx::core::origin("NG_BrickPattern/node_subtract_18/in2") + ]], + float node_multiply_14_in2 = 0.083000 + [[ + materialx::core::origin("NG_BrickPattern/hue_variation") + ]], + float node_combine3_color3_13_in2 = 0.000000 + [[ + materialx::core::origin("NG_BrickPattern/node_combine3_color3_13/in2") + ]], + color node_mix_6_fg = color(0.563720, 0.563720, 0.563720) + [[ + materialx::core::origin("NG_BrickPattern/dirt_color") + ]], + color node_clamp_0_low = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_clamp_0/low") + ]], + color node_clamp_0_high = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("NG_BrickPattern/node_clamp_0/high") + ]], + float N_StandardSurface_base = 1.000000 + [[ + materialx::core::origin("N_StandardSurface/base") + ]], + float N_StandardSurface_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/diffuse_roughness") + ]], + float N_StandardSurface_metalness = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/metalness") + ]], + float N_StandardSurface_specular = 1.000000 + [[ + materialx::core::origin("N_StandardSurface/specular") + ]], + color N_StandardSurface_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("N_StandardSurface/specular_color") + ]], + uniform float N_StandardSurface_specular_IOR = 1.500000 + [[ + materialx::core::origin("N_StandardSurface/specular_IOR") + ]], + float N_StandardSurface_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/specular_anisotropy") + ]], + float N_StandardSurface_specular_rotation = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/specular_rotation") + ]], + float N_StandardSurface_transmission = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/transmission") + ]], + color N_StandardSurface_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("N_StandardSurface/transmission_color") + ]], + float N_StandardSurface_transmission_depth = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/transmission_depth") + ]], + color N_StandardSurface_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("N_StandardSurface/transmission_scatter") + ]], + float N_StandardSurface_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/transmission_scatter_anisotropy") + ]], + float N_StandardSurface_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/transmission_dispersion") + ]], + float N_StandardSurface_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/transmission_extra_roughness") + ]], + float N_StandardSurface_subsurface = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/subsurface") + ]], + color N_StandardSurface_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("N_StandardSurface/subsurface_color") + ]], + color N_StandardSurface_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("N_StandardSurface/subsurface_radius") + ]], + float N_StandardSurface_subsurface_scale = 1.000000 + [[ + materialx::core::origin("N_StandardSurface/subsurface_scale") + ]], + float N_StandardSurface_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/subsurface_anisotropy") + ]], + float N_StandardSurface_sheen = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/sheen") + ]], + color N_StandardSurface_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("N_StandardSurface/sheen_color") + ]], + float N_StandardSurface_sheen_roughness = 0.300000 + [[ + materialx::core::origin("N_StandardSurface/sheen_roughness") + ]], + float N_StandardSurface_coat = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/coat") + ]], + color N_StandardSurface_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("N_StandardSurface/coat_color") + ]], + float N_StandardSurface_coat_roughness = 0.100000 + [[ + materialx::core::origin("N_StandardSurface/coat_roughness") + ]], + float N_StandardSurface_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/coat_anisotropy") + ]], + float N_StandardSurface_coat_rotation = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/coat_rotation") + ]], + uniform float N_StandardSurface_coat_IOR = 1.500000 + [[ + materialx::core::origin("N_StandardSurface/coat_IOR") + ]], + float N_StandardSurface_coat_affect_color = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/coat_affect_color") + ]], + float N_StandardSurface_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/coat_affect_roughness") + ]], + float N_StandardSurface_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/thin_film_thickness") + ]], + float N_StandardSurface_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("N_StandardSurface/thin_film_IOR") + ]], + float N_StandardSurface_emission = 0.000000 + [[ + materialx::core::origin("N_StandardSurface/emission") + ]], + color N_StandardSurface_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("N_StandardSurface/emission_color") + ]], + color N_StandardSurface_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("N_StandardSurface/opacity") + ]], + bool N_StandardSurface_thin_walled = false + [[ + materialx::core::origin("N_StandardSurface/thin_walled") + ]] +) += let +{ + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float2 node_convert_1_out = NG_convert_float_vector2(node_convert_1_in); + color node_rgbtohsv_12_out = materialx::stdlib_1_8::mx_rgbtohsv_color3(node_rgbtohsv_12_in); + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + float node_tiledimage_float_26_out = NG_tiledimage_float(node_tiledimage_float_26_file, node_tiledimage_float_26_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_26_uvoffset, node_tiledimage_float_26_realworldimagesize, node_tiledimage_float_26_realworldtilesize, node_tiledimage_float_26_filtertype, node_tiledimage_float_26_framerange, node_tiledimage_float_26_frameoffset, node_tiledimage_float_26_frameendaction); + float node_tiledimage_float_7_out = NG_tiledimage_float(node_tiledimage_float_7_file, node_tiledimage_float_7_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_7_uvoffset, node_tiledimage_float_7_realworldimagesize, node_tiledimage_float_7_realworldtilesize, node_tiledimage_float_7_filtertype, node_tiledimage_float_7_framerange, node_tiledimage_float_7_frameoffset, node_tiledimage_float_7_frameendaction); + float node_tiledimage_float_24_out = NG_tiledimage_float(node_tiledimage_float_24_file, node_tiledimage_float_24_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_24_uvoffset, node_tiledimage_float_24_realworldimagesize, node_tiledimage_float_24_realworldtilesize, node_tiledimage_float_24_filtertype, node_tiledimage_float_24_framerange, node_tiledimage_float_24_frameoffset, node_tiledimage_float_24_frameendaction); + float node_tiledimage_float_10_out = NG_tiledimage_float(node_tiledimage_float_10_file, node_tiledimage_float_10_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_10_uvoffset, node_tiledimage_float_10_realworldimagesize, node_tiledimage_float_10_realworldtilesize, node_tiledimage_float_10_filtertype, node_tiledimage_float_10_framerange, node_tiledimage_float_10_frameoffset, node_tiledimage_float_10_frameendaction); + float node_tiledimage_float_22_out = NG_tiledimage_float(node_tiledimage_float_22_file, node_tiledimage_float_22_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_22_uvoffset, node_tiledimage_float_22_realworldimagesize, node_tiledimage_float_22_realworldtilesize, node_tiledimage_float_22_filtertype, node_tiledimage_float_22_framerange, node_tiledimage_float_22_frameoffset, node_tiledimage_float_22_frameendaction); + float3 node_tiledimage_vector3_27_out = NG_tiledimage_vector3(node_tiledimage_vector3_27_file, node_tiledimage_vector3_27_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_vector3_27_uvoffset, node_tiledimage_vector3_27_realworldimagesize, node_tiledimage_vector3_27_realworldtilesize, node_tiledimage_vector3_27_filtertype, node_tiledimage_vector3_27_framerange, node_tiledimage_vector3_27_frameoffset, node_tiledimage_vector3_27_frameendaction); + float node_multiply_25_out = node_multiply_25_in1 * node_tiledimage_float_26_out; + float node_multiply_20_out = node_multiply_20_in1 * node_tiledimage_float_26_out; + color node_multiply_9_out = node_multiply_9_in1 * node_tiledimage_float_7_out; + float node_multiply_23_out = node_multiply_23_in1 * node_tiledimage_float_24_out; + float node_max_1_out = math::max(node_tiledimage_float_10_out, node_max_1_in2); + float3 node_normalmap_3_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:node_tiledimage_vector3_27_out, mxp_scale:node_normalmap_3_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + float node_add_19_out = node_multiply_25_out + node_tiledimage_float_7_out; + float node_divide_21_out = node_divide_21_in1 / node_max_1_out; + float node_subtract_18_out = node_add_19_out - node_subtract_18_in2; + float node_multiply_15_out = node_add_19_out * node_multiply_20_out; + float node_multiply_1_out = node_divide_21_out * node_tiledimage_float_22_out; + float node_multiply_14_out = node_subtract_18_out * node_multiply_14_in2; + color node_combine3_color3_13_out = color( node_multiply_14_out,node_combine3_color3_13_in2,node_multiply_15_out ); + color node_add_16_out = node_combine3_color3_13_out + node_rgbtohsv_12_out; + color node_hsvtorgb_17_out = materialx::stdlib_1_8::mx_hsvtorgb_color3(node_add_16_out); + color node_mix_6_out = math::lerp(node_hsvtorgb_17_out, node_mix_6_fg, node_multiply_23_out); + color node_multiply_5_out = node_mix_6_out * node_tiledimage_float_7_out; + color node_mix_8_out = math::lerp(node_multiply_9_out, node_multiply_5_out, node_tiledimage_float_10_out); + color node_clamp_0_out = math::clamp(node_mix_8_out, node_clamp_0_low, node_clamp_0_high); + material N_StandardSurface_out = NG_standard_surface_surfaceshader_100(N_StandardSurface_base, node_clamp_0_out, N_StandardSurface_diffuse_roughness, N_StandardSurface_metalness, N_StandardSurface_specular, N_StandardSurface_specular_color, node_multiply_1_out, N_StandardSurface_specular_IOR, N_StandardSurface_specular_anisotropy, N_StandardSurface_specular_rotation, N_StandardSurface_transmission, N_StandardSurface_transmission_color, N_StandardSurface_transmission_depth, N_StandardSurface_transmission_scatter, N_StandardSurface_transmission_scatter_anisotropy, N_StandardSurface_transmission_dispersion, N_StandardSurface_transmission_extra_roughness, N_StandardSurface_subsurface, N_StandardSurface_subsurface_color, N_StandardSurface_subsurface_radius, N_StandardSurface_subsurface_scale, N_StandardSurface_subsurface_anisotropy, N_StandardSurface_sheen, N_StandardSurface_sheen_color, N_StandardSurface_sheen_roughness, N_StandardSurface_coat, N_StandardSurface_coat_color, N_StandardSurface_coat_roughness, N_StandardSurface_coat_anisotropy, N_StandardSurface_coat_rotation, N_StandardSurface_coat_IOR, geomprop_Nworld_out1, N_StandardSurface_coat_affect_color, N_StandardSurface_coat_affect_roughness, N_StandardSurface_thin_film_thickness, N_StandardSurface_thin_film_IOR, N_StandardSurface_emission, N_StandardSurface_emission_color, N_StandardSurface_opacity, N_StandardSurface_thin_walled, node_normalmap_3_out, geomprop_Tworld_out1); + material M_BrickPattern_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: N_StandardSurface_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_BrickPattern_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_BrickPattern.msl.frag b/Materials/Examples/StandardSurface/M_BrickPattern.msl.frag new file mode 100644 index 0000000000..3d9b164e28 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_BrickPattern.msl.frag @@ -0,0 +1,3299 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + float node_convert_1_in; + vec3 node_rgbtohsv_12_in; + float node_tiledimage_float_26_default; + vec2 node_tiledimage_float_26_uvoffset; + vec2 node_tiledimage_float_26_realworldimagesize; + vec2 node_tiledimage_float_26_realworldtilesize; + int node_tiledimage_float_26_filtertype; + int node_tiledimage_float_26_framerange; + int node_tiledimage_float_26_frameoffset; + int node_tiledimage_float_26_frameendaction; + float node_tiledimage_float_7_default; + vec2 node_tiledimage_float_7_uvoffset; + vec2 node_tiledimage_float_7_realworldimagesize; + vec2 node_tiledimage_float_7_realworldtilesize; + int node_tiledimage_float_7_filtertype; + int node_tiledimage_float_7_framerange; + int node_tiledimage_float_7_frameoffset; + int node_tiledimage_float_7_frameendaction; + float node_tiledimage_float_24_default; + vec2 node_tiledimage_float_24_uvoffset; + vec2 node_tiledimage_float_24_realworldimagesize; + vec2 node_tiledimage_float_24_realworldtilesize; + int node_tiledimage_float_24_filtertype; + int node_tiledimage_float_24_framerange; + int node_tiledimage_float_24_frameoffset; + int node_tiledimage_float_24_frameendaction; + float node_tiledimage_float_10_default; + vec2 node_tiledimage_float_10_uvoffset; + vec2 node_tiledimage_float_10_realworldimagesize; + vec2 node_tiledimage_float_10_realworldtilesize; + int node_tiledimage_float_10_filtertype; + int node_tiledimage_float_10_framerange; + int node_tiledimage_float_10_frameoffset; + int node_tiledimage_float_10_frameendaction; + float node_tiledimage_float_22_default; + vec2 node_tiledimage_float_22_uvoffset; + vec2 node_tiledimage_float_22_realworldimagesize; + vec2 node_tiledimage_float_22_realworldtilesize; + int node_tiledimage_float_22_filtertype; + int node_tiledimage_float_22_framerange; + int node_tiledimage_float_22_frameoffset; + int node_tiledimage_float_22_frameendaction; + vec3 node_tiledimage_vector3_27_default; + vec2 node_tiledimage_vector3_27_uvoffset; + vec2 node_tiledimage_vector3_27_realworldimagesize; + vec2 node_tiledimage_vector3_27_realworldtilesize; + int node_tiledimage_vector3_27_filtertype; + int node_tiledimage_vector3_27_framerange; + int node_tiledimage_vector3_27_frameoffset; + int node_tiledimage_vector3_27_frameendaction; + float node_multiply_25_in1; + float node_multiply_20_in1; + vec3 node_multiply_9_in1; + float node_multiply_23_in1; + float node_max_1_in2; + float node_normalmap_3_scale; + float node_divide_21_in1; + float node_subtract_18_in2; + float node_multiply_14_in2; + float node_combine3_color3_13_in2; + vec3 node_mix_6_fg; + vec3 node_clamp_0_low; + vec3 node_clamp_0_high; + float N_StandardSurface_base; + float N_StandardSurface_diffuse_roughness; + float N_StandardSurface_metalness; + float N_StandardSurface_specular; + vec3 N_StandardSurface_specular_color; + float N_StandardSurface_specular_IOR; + float N_StandardSurface_specular_anisotropy; + float N_StandardSurface_specular_rotation; + float N_StandardSurface_transmission; + vec3 N_StandardSurface_transmission_color; + float N_StandardSurface_transmission_depth; + vec3 N_StandardSurface_transmission_scatter; + float N_StandardSurface_transmission_scatter_anisotropy; + float N_StandardSurface_transmission_dispersion; + float N_StandardSurface_transmission_extra_roughness; + float N_StandardSurface_subsurface; + vec3 N_StandardSurface_subsurface_color; + vec3 N_StandardSurface_subsurface_radius; + float N_StandardSurface_subsurface_scale; + float N_StandardSurface_subsurface_anisotropy; + float N_StandardSurface_sheen; + vec3 N_StandardSurface_sheen_color; + float N_StandardSurface_sheen_roughness; + float N_StandardSurface_coat; + vec3 N_StandardSurface_coat_color; + float N_StandardSurface_coat_roughness; + float N_StandardSurface_coat_anisotropy; + float N_StandardSurface_coat_rotation; + float N_StandardSurface_coat_IOR; + float N_StandardSurface_coat_affect_color; + float N_StandardSurface_coat_affect_roughness; + float N_StandardSurface_thin_film_thickness; + float N_StandardSurface_thin_film_IOR; + float N_StandardSurface_emission; + vec3 N_StandardSurface_emission_color; + vec3 N_StandardSurface_opacity; + bool N_StandardSurface_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec2 texcoord_0 ; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + + , float node_convert_1_in + + , vec3 node_rgbtohsv_12_in + +, MetalTexture node_tiledimage_float_26_file , float node_tiledimage_float_26_default + + , vec2 node_tiledimage_float_26_uvoffset + + , vec2 node_tiledimage_float_26_realworldimagesize + + , vec2 node_tiledimage_float_26_realworldtilesize + + , int node_tiledimage_float_26_filtertype + + , int node_tiledimage_float_26_framerange + + , int node_tiledimage_float_26_frameoffset + + , int node_tiledimage_float_26_frameendaction + +, MetalTexture node_tiledimage_float_7_file , float node_tiledimage_float_7_default + + , vec2 node_tiledimage_float_7_uvoffset + + , vec2 node_tiledimage_float_7_realworldimagesize + + , vec2 node_tiledimage_float_7_realworldtilesize + + , int node_tiledimage_float_7_filtertype + + , int node_tiledimage_float_7_framerange + + , int node_tiledimage_float_7_frameoffset + + , int node_tiledimage_float_7_frameendaction + +, MetalTexture node_tiledimage_float_24_file , float node_tiledimage_float_24_default + + , vec2 node_tiledimage_float_24_uvoffset + + , vec2 node_tiledimage_float_24_realworldimagesize + + , vec2 node_tiledimage_float_24_realworldtilesize + + , int node_tiledimage_float_24_filtertype + + , int node_tiledimage_float_24_framerange + + , int node_tiledimage_float_24_frameoffset + + , int node_tiledimage_float_24_frameendaction + +, MetalTexture node_tiledimage_float_10_file , float node_tiledimage_float_10_default + + , vec2 node_tiledimage_float_10_uvoffset + + , vec2 node_tiledimage_float_10_realworldimagesize + + , vec2 node_tiledimage_float_10_realworldtilesize + + , int node_tiledimage_float_10_filtertype + + , int node_tiledimage_float_10_framerange + + , int node_tiledimage_float_10_frameoffset + + , int node_tiledimage_float_10_frameendaction + +, MetalTexture node_tiledimage_float_22_file , float node_tiledimage_float_22_default + + , vec2 node_tiledimage_float_22_uvoffset + + , vec2 node_tiledimage_float_22_realworldimagesize + + , vec2 node_tiledimage_float_22_realworldtilesize + + , int node_tiledimage_float_22_filtertype + + , int node_tiledimage_float_22_framerange + + , int node_tiledimage_float_22_frameoffset + + , int node_tiledimage_float_22_frameendaction + +, MetalTexture node_tiledimage_vector3_27_file , vec3 node_tiledimage_vector3_27_default + + , vec2 node_tiledimage_vector3_27_uvoffset + + , vec2 node_tiledimage_vector3_27_realworldimagesize + + , vec2 node_tiledimage_vector3_27_realworldtilesize + + , int node_tiledimage_vector3_27_filtertype + + , int node_tiledimage_vector3_27_framerange + + , int node_tiledimage_vector3_27_frameoffset + + , int node_tiledimage_vector3_27_frameendaction + + , float node_multiply_25_in1 + + , float node_multiply_20_in1 + + , vec3 node_multiply_9_in1 + + , float node_multiply_23_in1 + + , float node_max_1_in2 + + , float node_normalmap_3_scale + + , float node_divide_21_in1 + + , float node_subtract_18_in2 + + , float node_multiply_14_in2 + + , float node_combine3_color3_13_in2 + + , vec3 node_mix_6_fg + + , vec3 node_clamp_0_low + + , vec3 node_clamp_0_high + + , float N_StandardSurface_base + + , float N_StandardSurface_diffuse_roughness + + , float N_StandardSurface_metalness + + , float N_StandardSurface_specular + + , vec3 N_StandardSurface_specular_color + + , float N_StandardSurface_specular_IOR + + , float N_StandardSurface_specular_anisotropy + + , float N_StandardSurface_specular_rotation + + , float N_StandardSurface_transmission + + , vec3 N_StandardSurface_transmission_color + + , float N_StandardSurface_transmission_depth + + , vec3 N_StandardSurface_transmission_scatter + + , float N_StandardSurface_transmission_scatter_anisotropy + + , float N_StandardSurface_transmission_dispersion + + , float N_StandardSurface_transmission_extra_roughness + + , float N_StandardSurface_subsurface + + , vec3 N_StandardSurface_subsurface_color + + , vec3 N_StandardSurface_subsurface_radius + + , float N_StandardSurface_subsurface_scale + + , float N_StandardSurface_subsurface_anisotropy + + , float N_StandardSurface_sheen + + , vec3 N_StandardSurface_sheen_color + + , float N_StandardSurface_sheen_roughness + + , float N_StandardSurface_coat + + , vec3 N_StandardSurface_coat_color + + , float N_StandardSurface_coat_roughness + + , float N_StandardSurface_coat_anisotropy + + , float N_StandardSurface_coat_rotation + + , float N_StandardSurface_coat_IOR + + , float N_StandardSurface_coat_affect_color + + , float N_StandardSurface_coat_affect_roughness + + , float N_StandardSurface_thin_film_thickness + + , float N_StandardSurface_thin_film_IOR + + , float N_StandardSurface_emission + + , vec3 N_StandardSurface_emission_color + + , vec3 N_StandardSurface_opacity + + , bool N_StandardSurface_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + + , node_convert_1_in(node_convert_1_in) + + , node_rgbtohsv_12_in(node_rgbtohsv_12_in) + +, node_tiledimage_float_26_file(node_tiledimage_float_26_file) + , node_tiledimage_float_26_default(node_tiledimage_float_26_default) + + , node_tiledimage_float_26_uvoffset(node_tiledimage_float_26_uvoffset) + + , node_tiledimage_float_26_realworldimagesize(node_tiledimage_float_26_realworldimagesize) + + , node_tiledimage_float_26_realworldtilesize(node_tiledimage_float_26_realworldtilesize) + + , node_tiledimage_float_26_filtertype(node_tiledimage_float_26_filtertype) + + , node_tiledimage_float_26_framerange(node_tiledimage_float_26_framerange) + + , node_tiledimage_float_26_frameoffset(node_tiledimage_float_26_frameoffset) + + , node_tiledimage_float_26_frameendaction(node_tiledimage_float_26_frameendaction) + +, node_tiledimage_float_7_file(node_tiledimage_float_7_file) + , node_tiledimage_float_7_default(node_tiledimage_float_7_default) + + , node_tiledimage_float_7_uvoffset(node_tiledimage_float_7_uvoffset) + + , node_tiledimage_float_7_realworldimagesize(node_tiledimage_float_7_realworldimagesize) + + , node_tiledimage_float_7_realworldtilesize(node_tiledimage_float_7_realworldtilesize) + + , node_tiledimage_float_7_filtertype(node_tiledimage_float_7_filtertype) + + , node_tiledimage_float_7_framerange(node_tiledimage_float_7_framerange) + + , node_tiledimage_float_7_frameoffset(node_tiledimage_float_7_frameoffset) + + , node_tiledimage_float_7_frameendaction(node_tiledimage_float_7_frameendaction) + +, node_tiledimage_float_24_file(node_tiledimage_float_24_file) + , node_tiledimage_float_24_default(node_tiledimage_float_24_default) + + , node_tiledimage_float_24_uvoffset(node_tiledimage_float_24_uvoffset) + + , node_tiledimage_float_24_realworldimagesize(node_tiledimage_float_24_realworldimagesize) + + , node_tiledimage_float_24_realworldtilesize(node_tiledimage_float_24_realworldtilesize) + + , node_tiledimage_float_24_filtertype(node_tiledimage_float_24_filtertype) + + , node_tiledimage_float_24_framerange(node_tiledimage_float_24_framerange) + + , node_tiledimage_float_24_frameoffset(node_tiledimage_float_24_frameoffset) + + , node_tiledimage_float_24_frameendaction(node_tiledimage_float_24_frameendaction) + +, node_tiledimage_float_10_file(node_tiledimage_float_10_file) + , node_tiledimage_float_10_default(node_tiledimage_float_10_default) + + , node_tiledimage_float_10_uvoffset(node_tiledimage_float_10_uvoffset) + + , node_tiledimage_float_10_realworldimagesize(node_tiledimage_float_10_realworldimagesize) + + , node_tiledimage_float_10_realworldtilesize(node_tiledimage_float_10_realworldtilesize) + + , node_tiledimage_float_10_filtertype(node_tiledimage_float_10_filtertype) + + , node_tiledimage_float_10_framerange(node_tiledimage_float_10_framerange) + + , node_tiledimage_float_10_frameoffset(node_tiledimage_float_10_frameoffset) + + , node_tiledimage_float_10_frameendaction(node_tiledimage_float_10_frameendaction) + +, node_tiledimage_float_22_file(node_tiledimage_float_22_file) + , node_tiledimage_float_22_default(node_tiledimage_float_22_default) + + , node_tiledimage_float_22_uvoffset(node_tiledimage_float_22_uvoffset) + + , node_tiledimage_float_22_realworldimagesize(node_tiledimage_float_22_realworldimagesize) + + , node_tiledimage_float_22_realworldtilesize(node_tiledimage_float_22_realworldtilesize) + + , node_tiledimage_float_22_filtertype(node_tiledimage_float_22_filtertype) + + , node_tiledimage_float_22_framerange(node_tiledimage_float_22_framerange) + + , node_tiledimage_float_22_frameoffset(node_tiledimage_float_22_frameoffset) + + , node_tiledimage_float_22_frameendaction(node_tiledimage_float_22_frameendaction) + +, node_tiledimage_vector3_27_file(node_tiledimage_vector3_27_file) + , node_tiledimage_vector3_27_default(node_tiledimage_vector3_27_default) + + , node_tiledimage_vector3_27_uvoffset(node_tiledimage_vector3_27_uvoffset) + + , node_tiledimage_vector3_27_realworldimagesize(node_tiledimage_vector3_27_realworldimagesize) + + , node_tiledimage_vector3_27_realworldtilesize(node_tiledimage_vector3_27_realworldtilesize) + + , node_tiledimage_vector3_27_filtertype(node_tiledimage_vector3_27_filtertype) + + , node_tiledimage_vector3_27_framerange(node_tiledimage_vector3_27_framerange) + + , node_tiledimage_vector3_27_frameoffset(node_tiledimage_vector3_27_frameoffset) + + , node_tiledimage_vector3_27_frameendaction(node_tiledimage_vector3_27_frameendaction) + + , node_multiply_25_in1(node_multiply_25_in1) + + , node_multiply_20_in1(node_multiply_20_in1) + + , node_multiply_9_in1(node_multiply_9_in1) + + , node_multiply_23_in1(node_multiply_23_in1) + + , node_max_1_in2(node_max_1_in2) + + , node_normalmap_3_scale(node_normalmap_3_scale) + + , node_divide_21_in1(node_divide_21_in1) + + , node_subtract_18_in2(node_subtract_18_in2) + + , node_multiply_14_in2(node_multiply_14_in2) + + , node_combine3_color3_13_in2(node_combine3_color3_13_in2) + + , node_mix_6_fg(node_mix_6_fg) + + , node_clamp_0_low(node_clamp_0_low) + + , node_clamp_0_high(node_clamp_0_high) + + , N_StandardSurface_base(N_StandardSurface_base) + + , N_StandardSurface_diffuse_roughness(N_StandardSurface_diffuse_roughness) + + , N_StandardSurface_metalness(N_StandardSurface_metalness) + + , N_StandardSurface_specular(N_StandardSurface_specular) + + , N_StandardSurface_specular_color(N_StandardSurface_specular_color) + + , N_StandardSurface_specular_IOR(N_StandardSurface_specular_IOR) + + , N_StandardSurface_specular_anisotropy(N_StandardSurface_specular_anisotropy) + + , N_StandardSurface_specular_rotation(N_StandardSurface_specular_rotation) + + , N_StandardSurface_transmission(N_StandardSurface_transmission) + + , N_StandardSurface_transmission_color(N_StandardSurface_transmission_color) + + , N_StandardSurface_transmission_depth(N_StandardSurface_transmission_depth) + + , N_StandardSurface_transmission_scatter(N_StandardSurface_transmission_scatter) + + , N_StandardSurface_transmission_scatter_anisotropy(N_StandardSurface_transmission_scatter_anisotropy) + + , N_StandardSurface_transmission_dispersion(N_StandardSurface_transmission_dispersion) + + , N_StandardSurface_transmission_extra_roughness(N_StandardSurface_transmission_extra_roughness) + + , N_StandardSurface_subsurface(N_StandardSurface_subsurface) + + , N_StandardSurface_subsurface_color(N_StandardSurface_subsurface_color) + + , N_StandardSurface_subsurface_radius(N_StandardSurface_subsurface_radius) + + , N_StandardSurface_subsurface_scale(N_StandardSurface_subsurface_scale) + + , N_StandardSurface_subsurface_anisotropy(N_StandardSurface_subsurface_anisotropy) + + , N_StandardSurface_sheen(N_StandardSurface_sheen) + + , N_StandardSurface_sheen_color(N_StandardSurface_sheen_color) + + , N_StandardSurface_sheen_roughness(N_StandardSurface_sheen_roughness) + + , N_StandardSurface_coat(N_StandardSurface_coat) + + , N_StandardSurface_coat_color(N_StandardSurface_coat_color) + + , N_StandardSurface_coat_roughness(N_StandardSurface_coat_roughness) + + , N_StandardSurface_coat_anisotropy(N_StandardSurface_coat_anisotropy) + + , N_StandardSurface_coat_rotation(N_StandardSurface_coat_rotation) + + , N_StandardSurface_coat_IOR(N_StandardSurface_coat_IOR) + + , N_StandardSurface_coat_affect_color(N_StandardSurface_coat_affect_color) + + , N_StandardSurface_coat_affect_roughness(N_StandardSurface_coat_affect_roughness) + + , N_StandardSurface_thin_film_thickness(N_StandardSurface_thin_film_thickness) + + , N_StandardSurface_thin_film_IOR(N_StandardSurface_thin_film_IOR) + + , N_StandardSurface_emission(N_StandardSurface_emission) + + , N_StandardSurface_emission_color(N_StandardSurface_emission_color) + + , N_StandardSurface_opacity(N_StandardSurface_opacity) + + , N_StandardSurface_thin_walled(N_StandardSurface_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + + float node_convert_1_in; + + + vec3 node_rgbtohsv_12_in; + + +MetalTexture node_tiledimage_float_26_file; + float node_tiledimage_float_26_default; + + + vec2 node_tiledimage_float_26_uvoffset; + + + vec2 node_tiledimage_float_26_realworldimagesize; + + + vec2 node_tiledimage_float_26_realworldtilesize; + + + int node_tiledimage_float_26_filtertype; + + + int node_tiledimage_float_26_framerange; + + + int node_tiledimage_float_26_frameoffset; + + + int node_tiledimage_float_26_frameendaction; + + +MetalTexture node_tiledimage_float_7_file; + float node_tiledimage_float_7_default; + + + vec2 node_tiledimage_float_7_uvoffset; + + + vec2 node_tiledimage_float_7_realworldimagesize; + + + vec2 node_tiledimage_float_7_realworldtilesize; + + + int node_tiledimage_float_7_filtertype; + + + int node_tiledimage_float_7_framerange; + + + int node_tiledimage_float_7_frameoffset; + + + int node_tiledimage_float_7_frameendaction; + + +MetalTexture node_tiledimage_float_24_file; + float node_tiledimage_float_24_default; + + + vec2 node_tiledimage_float_24_uvoffset; + + + vec2 node_tiledimage_float_24_realworldimagesize; + + + vec2 node_tiledimage_float_24_realworldtilesize; + + + int node_tiledimage_float_24_filtertype; + + + int node_tiledimage_float_24_framerange; + + + int node_tiledimage_float_24_frameoffset; + + + int node_tiledimage_float_24_frameendaction; + + +MetalTexture node_tiledimage_float_10_file; + float node_tiledimage_float_10_default; + + + vec2 node_tiledimage_float_10_uvoffset; + + + vec2 node_tiledimage_float_10_realworldimagesize; + + + vec2 node_tiledimage_float_10_realworldtilesize; + + + int node_tiledimage_float_10_filtertype; + + + int node_tiledimage_float_10_framerange; + + + int node_tiledimage_float_10_frameoffset; + + + int node_tiledimage_float_10_frameendaction; + + +MetalTexture node_tiledimage_float_22_file; + float node_tiledimage_float_22_default; + + + vec2 node_tiledimage_float_22_uvoffset; + + + vec2 node_tiledimage_float_22_realworldimagesize; + + + vec2 node_tiledimage_float_22_realworldtilesize; + + + int node_tiledimage_float_22_filtertype; + + + int node_tiledimage_float_22_framerange; + + + int node_tiledimage_float_22_frameoffset; + + + int node_tiledimage_float_22_frameendaction; + + +MetalTexture node_tiledimage_vector3_27_file; + vec3 node_tiledimage_vector3_27_default; + + + vec2 node_tiledimage_vector3_27_uvoffset; + + + vec2 node_tiledimage_vector3_27_realworldimagesize; + + + vec2 node_tiledimage_vector3_27_realworldtilesize; + + + int node_tiledimage_vector3_27_filtertype; + + + int node_tiledimage_vector3_27_framerange; + + + int node_tiledimage_vector3_27_frameoffset; + + + int node_tiledimage_vector3_27_frameendaction; + + + float node_multiply_25_in1; + + + float node_multiply_20_in1; + + + vec3 node_multiply_9_in1; + + + float node_multiply_23_in1; + + + float node_max_1_in2; + + + float node_normalmap_3_scale; + + + float node_divide_21_in1; + + + float node_subtract_18_in2; + + + float node_multiply_14_in2; + + + float node_combine3_color3_13_in2; + + + vec3 node_mix_6_fg; + + + vec3 node_clamp_0_low; + + + vec3 node_clamp_0_high; + + + float N_StandardSurface_base; + + + float N_StandardSurface_diffuse_roughness; + + + float N_StandardSurface_metalness; + + + float N_StandardSurface_specular; + + + vec3 N_StandardSurface_specular_color; + + + float N_StandardSurface_specular_IOR; + + + float N_StandardSurface_specular_anisotropy; + + + float N_StandardSurface_specular_rotation; + + + float N_StandardSurface_transmission; + + + vec3 N_StandardSurface_transmission_color; + + + float N_StandardSurface_transmission_depth; + + + vec3 N_StandardSurface_transmission_scatter; + + + float N_StandardSurface_transmission_scatter_anisotropy; + + + float N_StandardSurface_transmission_dispersion; + + + float N_StandardSurface_transmission_extra_roughness; + + + float N_StandardSurface_subsurface; + + + vec3 N_StandardSurface_subsurface_color; + + + vec3 N_StandardSurface_subsurface_radius; + + + float N_StandardSurface_subsurface_scale; + + + float N_StandardSurface_subsurface_anisotropy; + + + float N_StandardSurface_sheen; + + + vec3 N_StandardSurface_sheen_color; + + + float N_StandardSurface_sheen_roughness; + + + float N_StandardSurface_coat; + + + vec3 N_StandardSurface_coat_color; + + + float N_StandardSurface_coat_roughness; + + + float N_StandardSurface_coat_anisotropy; + + + float N_StandardSurface_coat_rotation; + + + float N_StandardSurface_coat_IOR; + + + float N_StandardSurface_coat_affect_color; + + + float N_StandardSurface_coat_affect_roughness; + + + float N_StandardSurface_thin_film_thickness; + + + float N_StandardSurface_thin_film_IOR; + + + float N_StandardSurface_emission; + + + vec3 N_StandardSurface_emission_color; + + + vec3 N_StandardSurface_opacity; + + + bool N_StandardSurface_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void NG_convert_float_vector2(float in1, thread vec2& out1) + { + vec2 combine_out = { in1,in1 }; + out1 = combine_out; + } + + /* + Color transform functions. + + These funcions are modified versions of the color operators found in Open Shading Language: + github.com/imageworks/OpenShadingLanguage/blob/master/src/liboslexec/opcolor.cpp + + It contains the subset of color operators needed to implement the MaterialX + standard library. The modifications are for conversions from C++ to GLSL. + + Original copyright notice: + ------------------------------------------------------------------------ + Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. + All Rights Reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Sony Pictures Imageworks nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ------------------------------------------------------------------------ + */ + + vec3 mx_hsvtorgb(vec3 hsv) + { + // Reference for this technique: Foley & van Dam + float h = hsv.x; float s = hsv.y; float v = hsv.z; + if (s < 0.0001f) { + return vec3 (v, v, v); + } else { + h = 6.0f * (h - floor(h)); // expand to [0..6) + int hi = int(trunc(h)); + float f = h - float(hi); + float p = v * (1.0f-s); + float q = v * (1.0f-s*f); + float t = v * (1.0f-s*(1.0f-f)); + if (hi == 0) + return vec3 (v, t, p); + else if (hi == 1) + return vec3 (q, v, p); + else if (hi == 2) + return vec3 (p, v, t); + else if (hi == 3) + return vec3 (p, q, v); + else if (hi == 4) + return vec3 (t, p, v); + return vec3 (v, p, q); + } + } + + + vec3 mx_rgbtohsv(vec3 c) + { + // See Foley & van Dam + float r = c.x; float g = c.y; float b = c.z; + float mincomp = min (r, min(g, b)); + float maxcomp = max (r, max(g, b)); + float delta = maxcomp - mincomp; // chroma + float h, s, v; + v = maxcomp; + if (maxcomp > 0.0f) + s = delta / maxcomp; + else s = 0.0f; + if (s <= 0.0f) + h = 0.0f; + else { + if (r >= maxcomp) h = (g-b) / delta; + else if (g >= maxcomp) h = 2.0f + (b-r) / delta; + else h = 4.0f + (r-g) / delta; + h *= (1.0f/6.0f); + if (h < 0.0f) + h += 1.0f; + } + return vec3(h, s, v); + } + + void mx_rgbtohsv_color3(vec3 _in, thread vec3& result) + { + result = mx_rgbtohsv(_in); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + void NG_tiledimage_float(MetalTexture file, float default1, vec2 texcoord1, vec2 uvtiling, vec2 uvoffset, vec2 realworldimagesize, vec2 realworldtilesize, int filtertype, int framerange, int frameoffset, int frameendaction, thread float& out1) + { + vec2 N_mult_float_out = texcoord1 * uvtiling; + vec2 N_sub_float_out = N_mult_float_out - uvoffset; + vec2 N_divtilesize_float_out = N_sub_float_out / realworldimagesize; + vec2 N_multtilesize_float_out = N_divtilesize_float_out * realworldtilesize; + float N_img_float_out = 0.0; + mx_image_float(file, 0, default1, N_multtilesize_float_out, 2, 2, filtertype, framerange, frameoffset, frameendaction, vec2(1.000000, 1.000000), vec2(0.000000, 0.000000), N_img_float_out); + out1 = N_img_float_out; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_tiledimage_vector3(MetalTexture file, vec3 default1, vec2 texcoord1, vec2 uvtiling, vec2 uvoffset, vec2 realworldimagesize, vec2 realworldtilesize, int filtertype, int framerange, int frameoffset, int frameendaction, thread vec3& out1) + { + vec2 N_mult_vector3_out = texcoord1 * uvtiling; + vec2 N_sub_vector3_out = N_mult_vector3_out - uvoffset; + vec2 N_divtilesize_vector3_out = N_sub_vector3_out / realworldimagesize; + vec2 N_multtilesize_vector3_out = N_divtilesize_vector3_out * realworldtilesize; + vec3 N_img_vector3_out = vec3(0.0); + mx_image_vector3(file, 0, default1, N_multtilesize_vector3_out, 2, 2, filtertype, framerange, frameoffset, frameendaction, vec2(1.000000, 1.000000), vec2(0.000000, 0.000000), N_img_vector3_out); + out1 = N_img_vector3_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + + void mx_hsvtorgb_color3(vec3 _in, thread vec3& result) + { + result = mx_hsvtorgb(_in); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec2 node_convert_1_out = vec2(0.0); + NG_convert_float_vector2(node_convert_1_in, node_convert_1_out); + vec3 node_rgbtohsv_12_out = vec3(0.0); + mx_rgbtohsv_color3(node_rgbtohsv_12_in, node_rgbtohsv_12_out); + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + float node_tiledimage_float_26_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_26_file, node_tiledimage_float_26_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_26_uvoffset, node_tiledimage_float_26_realworldimagesize, node_tiledimage_float_26_realworldtilesize, node_tiledimage_float_26_filtertype, node_tiledimage_float_26_framerange, node_tiledimage_float_26_frameoffset, node_tiledimage_float_26_frameendaction, node_tiledimage_float_26_out); + float node_tiledimage_float_7_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_7_file, node_tiledimage_float_7_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_7_uvoffset, node_tiledimage_float_7_realworldimagesize, node_tiledimage_float_7_realworldtilesize, node_tiledimage_float_7_filtertype, node_tiledimage_float_7_framerange, node_tiledimage_float_7_frameoffset, node_tiledimage_float_7_frameendaction, node_tiledimage_float_7_out); + float node_tiledimage_float_24_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_24_file, node_tiledimage_float_24_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_24_uvoffset, node_tiledimage_float_24_realworldimagesize, node_tiledimage_float_24_realworldtilesize, node_tiledimage_float_24_filtertype, node_tiledimage_float_24_framerange, node_tiledimage_float_24_frameoffset, node_tiledimage_float_24_frameendaction, node_tiledimage_float_24_out); + float node_tiledimage_float_10_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_10_file, node_tiledimage_float_10_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_10_uvoffset, node_tiledimage_float_10_realworldimagesize, node_tiledimage_float_10_realworldtilesize, node_tiledimage_float_10_filtertype, node_tiledimage_float_10_framerange, node_tiledimage_float_10_frameoffset, node_tiledimage_float_10_frameendaction, node_tiledimage_float_10_out); + float node_tiledimage_float_22_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_22_file, node_tiledimage_float_22_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_22_uvoffset, node_tiledimage_float_22_realworldimagesize, node_tiledimage_float_22_realworldtilesize, node_tiledimage_float_22_filtertype, node_tiledimage_float_22_framerange, node_tiledimage_float_22_frameoffset, node_tiledimage_float_22_frameendaction, node_tiledimage_float_22_out); + vec3 node_tiledimage_vector3_27_out = vec3(0.0); + NG_tiledimage_vector3(node_tiledimage_vector3_27_file, node_tiledimage_vector3_27_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_vector3_27_uvoffset, node_tiledimage_vector3_27_realworldimagesize, node_tiledimage_vector3_27_realworldtilesize, node_tiledimage_vector3_27_filtertype, node_tiledimage_vector3_27_framerange, node_tiledimage_vector3_27_frameoffset, node_tiledimage_vector3_27_frameendaction, node_tiledimage_vector3_27_out); + float node_multiply_25_out = node_multiply_25_in1 * node_tiledimage_float_26_out; + float node_multiply_20_out = node_multiply_20_in1 * node_tiledimage_float_26_out; + vec3 node_multiply_9_out = node_multiply_9_in1 * node_tiledimage_float_7_out; + float node_multiply_23_out = node_multiply_23_in1 * node_tiledimage_float_24_out; + float node_max_1_out = max(node_tiledimage_float_10_out, node_max_1_in2); + vec3 node_normalmap_3_out = vec3(0.0); + mx_normalmap_float(node_tiledimage_vector3_27_out, node_normalmap_3_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, node_normalmap_3_out); + float node_add_19_out = node_multiply_25_out + node_tiledimage_float_7_out; + float node_divide_21_out = node_divide_21_in1 / node_max_1_out; + float node_subtract_18_out = node_add_19_out - node_subtract_18_in2; + float node_multiply_15_out = node_add_19_out * node_multiply_20_out; + float node_multiply_1_out = node_divide_21_out * node_tiledimage_float_22_out; + float node_multiply_14_out = node_subtract_18_out * node_multiply_14_in2; + vec3 node_combine3_color3_13_out = { node_multiply_14_out,node_combine3_color3_13_in2,node_multiply_15_out }; + vec3 node_add_16_out = node_combine3_color3_13_out + node_rgbtohsv_12_out; + vec3 node_hsvtorgb_17_out = vec3(0.0); + mx_hsvtorgb_color3(node_add_16_out, node_hsvtorgb_17_out); + vec3 node_mix_6_out = mix(node_hsvtorgb_17_out, node_mix_6_fg, node_multiply_23_out); + vec3 node_multiply_5_out = node_mix_6_out * node_tiledimage_float_7_out; + vec3 node_mix_8_out = mix(node_multiply_9_out, node_multiply_5_out, node_tiledimage_float_10_out); + vec3 node_clamp_0_out = clamp(node_mix_8_out, node_clamp_0_low, node_clamp_0_high); + surfaceshader N_StandardSurface_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(N_StandardSurface_base, node_clamp_0_out, N_StandardSurface_diffuse_roughness, N_StandardSurface_metalness, N_StandardSurface_specular, N_StandardSurface_specular_color, node_multiply_1_out, N_StandardSurface_specular_IOR, N_StandardSurface_specular_anisotropy, N_StandardSurface_specular_rotation, N_StandardSurface_transmission, N_StandardSurface_transmission_color, N_StandardSurface_transmission_depth, N_StandardSurface_transmission_scatter, N_StandardSurface_transmission_scatter_anisotropy, N_StandardSurface_transmission_dispersion, N_StandardSurface_transmission_extra_roughness, N_StandardSurface_subsurface, N_StandardSurface_subsurface_color, N_StandardSurface_subsurface_radius, N_StandardSurface_subsurface_scale, N_StandardSurface_subsurface_anisotropy, N_StandardSurface_sheen, N_StandardSurface_sheen_color, N_StandardSurface_sheen_roughness, N_StandardSurface_coat, N_StandardSurface_coat_color, N_StandardSurface_coat_roughness, N_StandardSurface_coat_anisotropy, N_StandardSurface_coat_rotation, N_StandardSurface_coat_IOR, geomprop_Nworld_out1, N_StandardSurface_coat_affect_color, N_StandardSurface_coat_affect_roughness, N_StandardSurface_thin_film_thickness, N_StandardSurface_thin_film_IOR, N_StandardSurface_emission, N_StandardSurface_emission_color, N_StandardSurface_opacity, N_StandardSurface_thin_walled, node_normalmap_3_out, geomprop_Tworld_out1, N_StandardSurface_out); + material M_BrickPattern_out = N_StandardSurface_out; + out1 = float4(M_BrickPattern_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d node_tiledimage_float_26_file_tex [[texture(0)]], sampler node_tiledimage_float_26_file_sampler [[sampler(0)]] +, texture2d node_tiledimage_float_7_file_tex [[texture(1)]], sampler node_tiledimage_float_7_file_sampler [[sampler(1)]] +, texture2d node_tiledimage_float_24_file_tex [[texture(2)]], sampler node_tiledimage_float_24_file_sampler [[sampler(2)]] +, texture2d node_tiledimage_float_10_file_tex [[texture(3)]], sampler node_tiledimage_float_10_file_sampler [[sampler(3)]] +, texture2d node_tiledimage_float_22_file_tex [[texture(4)]], sampler node_tiledimage_float_22_file_sampler [[sampler(4)]] +, texture2d node_tiledimage_vector3_27_file_tex [[texture(5)]], sampler node_tiledimage_vector3_27_file_sampler [[sampler(5)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(6)]], sampler u_envRadiance_sampler [[sampler(6)]] +, texture2d u_envIrradiance_tex [[texture(7)]], sampler u_envIrradiance_sampler [[sampler(7)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index + , u_pub.node_convert_1_in + , u_pub.node_rgbtohsv_12_in +, MetalTexture { +node_tiledimage_float_26_file_tex, node_tiledimage_float_26_file_sampler } + , u_pub.node_tiledimage_float_26_default + , u_pub.node_tiledimage_float_26_uvoffset + , u_pub.node_tiledimage_float_26_realworldimagesize + , u_pub.node_tiledimage_float_26_realworldtilesize + , u_pub.node_tiledimage_float_26_filtertype + , u_pub.node_tiledimage_float_26_framerange + , u_pub.node_tiledimage_float_26_frameoffset + , u_pub.node_tiledimage_float_26_frameendaction +, MetalTexture { +node_tiledimage_float_7_file_tex, node_tiledimage_float_7_file_sampler } + , u_pub.node_tiledimage_float_7_default + , u_pub.node_tiledimage_float_7_uvoffset + , u_pub.node_tiledimage_float_7_realworldimagesize + , u_pub.node_tiledimage_float_7_realworldtilesize + , u_pub.node_tiledimage_float_7_filtertype + , u_pub.node_tiledimage_float_7_framerange + , u_pub.node_tiledimage_float_7_frameoffset + , u_pub.node_tiledimage_float_7_frameendaction +, MetalTexture { +node_tiledimage_float_24_file_tex, node_tiledimage_float_24_file_sampler } + , u_pub.node_tiledimage_float_24_default + , u_pub.node_tiledimage_float_24_uvoffset + , u_pub.node_tiledimage_float_24_realworldimagesize + , u_pub.node_tiledimage_float_24_realworldtilesize + , u_pub.node_tiledimage_float_24_filtertype + , u_pub.node_tiledimage_float_24_framerange + , u_pub.node_tiledimage_float_24_frameoffset + , u_pub.node_tiledimage_float_24_frameendaction +, MetalTexture { +node_tiledimage_float_10_file_tex, node_tiledimage_float_10_file_sampler } + , u_pub.node_tiledimage_float_10_default + , u_pub.node_tiledimage_float_10_uvoffset + , u_pub.node_tiledimage_float_10_realworldimagesize + , u_pub.node_tiledimage_float_10_realworldtilesize + , u_pub.node_tiledimage_float_10_filtertype + , u_pub.node_tiledimage_float_10_framerange + , u_pub.node_tiledimage_float_10_frameoffset + , u_pub.node_tiledimage_float_10_frameendaction +, MetalTexture { +node_tiledimage_float_22_file_tex, node_tiledimage_float_22_file_sampler } + , u_pub.node_tiledimage_float_22_default + , u_pub.node_tiledimage_float_22_uvoffset + , u_pub.node_tiledimage_float_22_realworldimagesize + , u_pub.node_tiledimage_float_22_realworldtilesize + , u_pub.node_tiledimage_float_22_filtertype + , u_pub.node_tiledimage_float_22_framerange + , u_pub.node_tiledimage_float_22_frameoffset + , u_pub.node_tiledimage_float_22_frameendaction +, MetalTexture { +node_tiledimage_vector3_27_file_tex, node_tiledimage_vector3_27_file_sampler } + , u_pub.node_tiledimage_vector3_27_default + , u_pub.node_tiledimage_vector3_27_uvoffset + , u_pub.node_tiledimage_vector3_27_realworldimagesize + , u_pub.node_tiledimage_vector3_27_realworldtilesize + , u_pub.node_tiledimage_vector3_27_filtertype + , u_pub.node_tiledimage_vector3_27_framerange + , u_pub.node_tiledimage_vector3_27_frameoffset + , u_pub.node_tiledimage_vector3_27_frameendaction + , u_pub.node_multiply_25_in1 + , u_pub.node_multiply_20_in1 + , u_pub.node_multiply_9_in1 + , u_pub.node_multiply_23_in1 + , u_pub.node_max_1_in2 + , u_pub.node_normalmap_3_scale + , u_pub.node_divide_21_in1 + , u_pub.node_subtract_18_in2 + , u_pub.node_multiply_14_in2 + , u_pub.node_combine3_color3_13_in2 + , u_pub.node_mix_6_fg + , u_pub.node_clamp_0_low + , u_pub.node_clamp_0_high + , u_pub.N_StandardSurface_base + , u_pub.N_StandardSurface_diffuse_roughness + , u_pub.N_StandardSurface_metalness + , u_pub.N_StandardSurface_specular + , u_pub.N_StandardSurface_specular_color + , u_pub.N_StandardSurface_specular_IOR + , u_pub.N_StandardSurface_specular_anisotropy + , u_pub.N_StandardSurface_specular_rotation + , u_pub.N_StandardSurface_transmission + , u_pub.N_StandardSurface_transmission_color + , u_pub.N_StandardSurface_transmission_depth + , u_pub.N_StandardSurface_transmission_scatter + , u_pub.N_StandardSurface_transmission_scatter_anisotropy + , u_pub.N_StandardSurface_transmission_dispersion + , u_pub.N_StandardSurface_transmission_extra_roughness + , u_pub.N_StandardSurface_subsurface + , u_pub.N_StandardSurface_subsurface_color + , u_pub.N_StandardSurface_subsurface_radius + , u_pub.N_StandardSurface_subsurface_scale + , u_pub.N_StandardSurface_subsurface_anisotropy + , u_pub.N_StandardSurface_sheen + , u_pub.N_StandardSurface_sheen_color + , u_pub.N_StandardSurface_sheen_roughness + , u_pub.N_StandardSurface_coat + , u_pub.N_StandardSurface_coat_color + , u_pub.N_StandardSurface_coat_roughness + , u_pub.N_StandardSurface_coat_anisotropy + , u_pub.N_StandardSurface_coat_rotation + , u_pub.N_StandardSurface_coat_IOR + , u_pub.N_StandardSurface_coat_affect_color + , u_pub.N_StandardSurface_coat_affect_roughness + , u_pub.N_StandardSurface_thin_film_thickness + , u_pub.N_StandardSurface_thin_film_IOR + , u_pub.N_StandardSurface_emission + , u_pub.N_StandardSurface_emission_color + , u_pub.N_StandardSurface_opacity + , u_pub.N_StandardSurface_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_BrickPattern.msl.vert b/Materials/Examples/StandardSurface/M_BrickPattern.msl.vert new file mode 100644 index 0000000000..def849ebb0 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_BrickPattern.msl.vert @@ -0,0 +1,168 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec2 i_texcoord_0 [[attribute(1)]]; + vec3 i_normal [[attribute(2)]]; + vec3 i_tangent [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec2 texcoord_0; + vec3 normalWorld; + vec3 tangentWorld; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec2 i_texcoord_0 +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_texcoord_0(i_texcoord_0) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec2 i_texcoord_0; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.texcoord_0 = i_texcoord_0; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + // Omitted node 'N_mult_float'. Function already called in this scope. + // Omitted node 'N_sub_float'. Function already called in this scope. + // Omitted node 'N_divtilesize_float'. Function already called in this scope. + // Omitted node 'N_multtilesize_float'. Function already called in this scope. + // Omitted node 'N_img_float'. Function already called in this scope. + // Omitted node 'N_mult_float'. Function already called in this scope. + // Omitted node 'N_sub_float'. Function already called in this scope. + // Omitted node 'N_divtilesize_float'. Function already called in this scope. + // Omitted node 'N_multtilesize_float'. Function already called in this scope. + // Omitted node 'N_img_float'. Function already called in this scope. + // Omitted node 'N_mult_float'. Function already called in this scope. + // Omitted node 'N_sub_float'. Function already called in this scope. + // Omitted node 'N_divtilesize_float'. Function already called in this scope. + // Omitted node 'N_multtilesize_float'. Function already called in this scope. + // Omitted node 'N_img_float'. Function already called in this scope. + // Omitted node 'N_mult_float'. Function already called in this scope. + // Omitted node 'N_sub_float'. Function already called in this scope. + // Omitted node 'N_divtilesize_float'. Function already called in this scope. + // Omitted node 'N_multtilesize_float'. Function already called in this scope. + // Omitted node 'N_img_float'. Function already called in this scope. + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'node_convert_1'. Function already called in this scope. + // Omitted node 'node_rgbtohsv_12'. Function already called in this scope. + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'node_tiledimage_float_26'. Function already called in this scope. + // Omitted node 'node_tiledimage_float_7'. Function already called in this scope. + // Omitted node 'node_tiledimage_float_24'. Function already called in this scope. + // Omitted node 'node_tiledimage_float_10'. Function already called in this scope. + // Omitted node 'node_tiledimage_float_22'. Function already called in this scope. + // Omitted node 'node_tiledimage_vector3_27'. Function already called in this scope. + // Omitted node 'node_multiply_25'. Function already called in this scope. + // Omitted node 'node_multiply_20'. Function already called in this scope. + // Omitted node 'node_multiply_9'. Function already called in this scope. + // Omitted node 'node_multiply_23'. Function already called in this scope. + // Omitted node 'node_max_1'. Function already called in this scope. + // Omitted node 'node_normalmap_3'. Function already called in this scope. + // Omitted node 'node_add_19'. Function already called in this scope. + // Omitted node 'node_divide_21'. Function already called in this scope. + // Omitted node 'node_subtract_18'. Function already called in this scope. + // Omitted node 'node_multiply_15'. Function already called in this scope. + // Omitted node 'node_multiply_1'. Function already called in this scope. + // Omitted node 'node_multiply_14'. Function already called in this scope. + // Omitted node 'node_combine3_color3_13'. Function already called in this scope. + // Omitted node 'node_add_16'. Function already called in this scope. + // Omitted node 'node_hsvtorgb_17'. Function already called in this scope. + // Omitted node 'node_mix_6'. Function already called in this scope. + // Omitted node 'node_multiply_5'. Function already called in this scope. + // Omitted node 'node_mix_8'. Function already called in this scope. + // Omitted node 'node_clamp_0'. Function already called in this scope. + // Omitted node 'N_StandardSurface'. Function already called in this scope. + // Omitted node 'M_BrickPattern'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_texcoord_0, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_BrickPattern.osl b/Materials/Examples/StandardSurface/M_BrickPattern.osl new file mode 100644 index 0000000000..b95069526b --- /dev/null +++ b/Materials/Examples/StandardSurface/M_BrickPattern.osl @@ -0,0 +1,775 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void NG_convert_float_vector2(float in, output vector2 out) +{ + vector2 combine_out = { in,in }; + out = combine_out; +} + +void mx_rgbtohsv_color3(vector _in, output vector result) +{ + result = transformc("rgb","hsv", _in); +} + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + +void NG_tiledimage_float(textureresource file, float default1, vector2 texcoord, vector2 uvtiling, vector2 uvoffset, vector2 realworldimagesize, vector2 realworldtilesize, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + vector2 N_mult_float_out = texcoord * uvtiling; + vector2 N_sub_float_out = N_mult_float_out - uvoffset; + vector2 N_divtilesize_float_out = N_sub_float_out / realworldimagesize; + vector2 N_multtilesize_float_out = N_divtilesize_float_out * realworldtilesize; + float N_img_float_out = 0.0; + mx_image_float(file, "", default1, N_multtilesize_float_out, "periodic", "periodic", filtertype, framerange, frameoffset, frameendaction, N_img_float_out); + out = N_img_float_out; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_tiledimage_vector3(textureresource file, vector default1, vector2 texcoord, vector2 uvtiling, vector2 uvoffset, vector2 realworldimagesize, vector2 realworldtilesize, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + vector2 N_mult_vector3_out = texcoord * uvtiling; + vector2 N_sub_vector3_out = N_mult_vector3_out - uvoffset; + vector2 N_divtilesize_vector3_out = N_sub_vector3_out / realworldimagesize; + vector2 N_multtilesize_vector3_out = N_divtilesize_vector3_out * realworldtilesize; + vector N_img_vector3_out = vector(0.0); + mx_image_vector3(file, "", default1, N_multtilesize_vector3_out, "periodic", "periodic", filtertype, framerange, frameoffset, frameendaction, N_img_vector3_out); + out = N_img_vector3_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_hsvtorgb_color3(vector _in, output vector result) +{ + result = transformc("hsv","rgb", _in); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_BrickPattern +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_BrickPattern" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + float node_convert_1_in = 3.000000 + [[ + string widget = "number" + ]], + color node_rgbtohsv_12_in = color(0.661876, 0.190880, 0.000000), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string node_tiledimage_float_26_file = "../../../Images/brick_variation_mask.jpg" + [[ + string widget = "filename" + ]], + string node_tiledimage_float_26_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + float node_tiledimage_float_26_default = 0.000000 + [[ + string widget = "number" + ]], + vector2 node_tiledimage_float_26_uvoffset = {0.000000, 0.000000}, + vector2 node_tiledimage_float_26_realworldimagesize = {1.000000, 1.000000}, + vector2 node_tiledimage_float_26_realworldtilesize = {1.000000, 1.000000}, + string node_tiledimage_float_26_filtertype = "linear", + string node_tiledimage_float_26_framerange = "", + int node_tiledimage_float_26_frameoffset = 0 + [[ + string widget = "number" + ]], + string node_tiledimage_float_26_frameendaction = "constant", + string node_tiledimage_float_7_file = "../../../Images/brick_base_gray.jpg" + [[ + string widget = "filename" + ]], + string node_tiledimage_float_7_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + float node_tiledimage_float_7_default = 0.000000 + [[ + string widget = "number" + ]], + vector2 node_tiledimage_float_7_uvoffset = {0.000000, 0.000000}, + vector2 node_tiledimage_float_7_realworldimagesize = {1.000000, 1.000000}, + vector2 node_tiledimage_float_7_realworldtilesize = {1.000000, 1.000000}, + string node_tiledimage_float_7_filtertype = "linear", + string node_tiledimage_float_7_framerange = "", + int node_tiledimage_float_7_frameoffset = 0 + [[ + string widget = "number" + ]], + string node_tiledimage_float_7_frameendaction = "constant", + string node_tiledimage_float_24_file = "../../../Images/brick_dirt_mask.jpg" + [[ + string widget = "filename" + ]], + string node_tiledimage_float_24_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + float node_tiledimage_float_24_default = 0.000000 + [[ + string widget = "number" + ]], + vector2 node_tiledimage_float_24_uvoffset = {0.000000, 0.000000}, + vector2 node_tiledimage_float_24_realworldimagesize = {1.000000, 1.000000}, + vector2 node_tiledimage_float_24_realworldtilesize = {1.000000, 1.000000}, + string node_tiledimage_float_24_filtertype = "linear", + string node_tiledimage_float_24_framerange = "", + int node_tiledimage_float_24_frameoffset = 0 + [[ + string widget = "number" + ]], + string node_tiledimage_float_24_frameendaction = "constant", + string node_tiledimage_float_10_file = "../../../Images/brick_mask.jpg" + [[ + string widget = "filename" + ]], + string node_tiledimage_float_10_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + float node_tiledimage_float_10_default = 0.000000 + [[ + string widget = "number" + ]], + vector2 node_tiledimage_float_10_uvoffset = {0.000000, 0.000000}, + vector2 node_tiledimage_float_10_realworldimagesize = {1.000000, 1.000000}, + vector2 node_tiledimage_float_10_realworldtilesize = {1.000000, 1.000000}, + string node_tiledimage_float_10_filtertype = "linear", + string node_tiledimage_float_10_framerange = "", + int node_tiledimage_float_10_frameoffset = 0 + [[ + string widget = "number" + ]], + string node_tiledimage_float_10_frameendaction = "constant", + string node_tiledimage_float_22_file = "../../../Images/brick_roughness.jpg" + [[ + string widget = "filename" + ]], + string node_tiledimage_float_22_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + float node_tiledimage_float_22_default = 0.000000 + [[ + string widget = "number" + ]], + vector2 node_tiledimage_float_22_uvoffset = {0.000000, 0.000000}, + vector2 node_tiledimage_float_22_realworldimagesize = {1.000000, 1.000000}, + vector2 node_tiledimage_float_22_realworldtilesize = {1.000000, 1.000000}, + string node_tiledimage_float_22_filtertype = "linear", + string node_tiledimage_float_22_framerange = "", + int node_tiledimage_float_22_frameoffset = 0 + [[ + string widget = "number" + ]], + string node_tiledimage_float_22_frameendaction = "constant", + string node_tiledimage_vector3_27_file = "../../../Images/brick_normal.jpg" + [[ + string widget = "filename" + ]], + string node_tiledimage_vector3_27_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + vector node_tiledimage_vector3_27_default = vector(0.000000, 0.000000, 0.000000), + vector2 node_tiledimage_vector3_27_uvoffset = {0.000000, 0.000000}, + vector2 node_tiledimage_vector3_27_realworldimagesize = {1.000000, 1.000000}, + vector2 node_tiledimage_vector3_27_realworldtilesize = {1.000000, 1.000000}, + string node_tiledimage_vector3_27_filtertype = "linear", + string node_tiledimage_vector3_27_framerange = "", + int node_tiledimage_vector3_27_frameoffset = 0 + [[ + string widget = "number" + ]], + string node_tiledimage_vector3_27_frameendaction = "constant", + float node_multiply_25_in1 = 0.083000 + [[ + string widget = "number" + ]], + float node_multiply_20_in1 = 0.787000 + [[ + string widget = "number" + ]], + color node_multiply_9_in1 = color(0.263273, 0.263273, 0.263273), + float node_multiply_23_in1 = 0.248000 + [[ + string widget = "number" + ]], + float node_max_1_in2 = 0.000010 + [[ + string widget = "number" + ]], + float node_normalmap_3_scale = 1.000000 + [[ + string widget = "number" + ]], + float node_divide_21_in1 = 0.853000 + [[ + string widget = "number" + ]], + float node_subtract_18_in2 = 0.350000 + [[ + string widget = "number" + ]], + float node_multiply_14_in2 = 0.083000 + [[ + string widget = "number" + ]], + float node_combine3_color3_13_in2 = 0.000000 + [[ + string widget = "number" + ]], + color node_mix_6_fg = color(0.563720, 0.563720, 0.563720), + color node_clamp_0_low = color(0.000000, 0.000000, 0.000000), + color node_clamp_0_high = color(1.000000, 1.000000, 1.000000), + float N_StandardSurface_base = 1.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_metalness = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_specular = 1.000000 + [[ + string widget = "number" + ]], + color N_StandardSurface_specular_color = color(1.000000, 1.000000, 1.000000), + float N_StandardSurface_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float N_StandardSurface_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_transmission = 0.000000 + [[ + string widget = "number" + ]], + color N_StandardSurface_transmission_color = color(1.000000, 1.000000, 1.000000), + float N_StandardSurface_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color N_StandardSurface_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float N_StandardSurface_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color N_StandardSurface_subsurface_color = color(1.000000, 1.000000, 1.000000), + color N_StandardSurface_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float N_StandardSurface_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_sheen = 0.000000 + [[ + string widget = "number" + ]], + color N_StandardSurface_sheen_color = color(1.000000, 1.000000, 1.000000), + float N_StandardSurface_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float N_StandardSurface_coat = 0.000000 + [[ + string widget = "number" + ]], + color N_StandardSurface_coat_color = color(1.000000, 1.000000, 1.000000), + float N_StandardSurface_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float N_StandardSurface_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float N_StandardSurface_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float N_StandardSurface_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float N_StandardSurface_emission = 0.000000 + [[ + string widget = "number" + ]], + color N_StandardSurface_emission_color = color(1.000000, 1.000000, 1.000000), + color N_StandardSurface_opacity = color(1.000000, 1.000000, 1.000000), + int N_StandardSurface_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource node_tiledimage_float_26_file_ = {node_tiledimage_float_26_file, node_tiledimage_float_26_file_colorspace}; + textureresource node_tiledimage_float_7_file_ = {node_tiledimage_float_7_file, node_tiledimage_float_7_file_colorspace}; + textureresource node_tiledimage_float_24_file_ = {node_tiledimage_float_24_file, node_tiledimage_float_24_file_colorspace}; + textureresource node_tiledimage_float_10_file_ = {node_tiledimage_float_10_file, node_tiledimage_float_10_file_colorspace}; + textureresource node_tiledimage_float_22_file_ = {node_tiledimage_float_22_file, node_tiledimage_float_22_file_colorspace}; + textureresource node_tiledimage_vector3_27_file_ = {node_tiledimage_vector3_27_file, node_tiledimage_vector3_27_file_colorspace}; + vector2 geomprop_UV0_out1 = vector2(u,v); + vector2 node_convert_1_out = vector2(0.0, 0.0); + NG_convert_float_vector2(node_convert_1_in, node_convert_1_out); + color node_rgbtohsv_12_out = color(0.0); + mx_rgbtohsv_color3(node_rgbtohsv_12_in, node_rgbtohsv_12_out); + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + float node_tiledimage_float_26_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_26_file_, node_tiledimage_float_26_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_26_uvoffset, node_tiledimage_float_26_realworldimagesize, node_tiledimage_float_26_realworldtilesize, node_tiledimage_float_26_filtertype, node_tiledimage_float_26_framerange, node_tiledimage_float_26_frameoffset, node_tiledimage_float_26_frameendaction, node_tiledimage_float_26_out); + float node_tiledimage_float_7_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_7_file_, node_tiledimage_float_7_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_7_uvoffset, node_tiledimage_float_7_realworldimagesize, node_tiledimage_float_7_realworldtilesize, node_tiledimage_float_7_filtertype, node_tiledimage_float_7_framerange, node_tiledimage_float_7_frameoffset, node_tiledimage_float_7_frameendaction, node_tiledimage_float_7_out); + float node_tiledimage_float_24_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_24_file_, node_tiledimage_float_24_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_24_uvoffset, node_tiledimage_float_24_realworldimagesize, node_tiledimage_float_24_realworldtilesize, node_tiledimage_float_24_filtertype, node_tiledimage_float_24_framerange, node_tiledimage_float_24_frameoffset, node_tiledimage_float_24_frameendaction, node_tiledimage_float_24_out); + float node_tiledimage_float_10_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_10_file_, node_tiledimage_float_10_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_10_uvoffset, node_tiledimage_float_10_realworldimagesize, node_tiledimage_float_10_realworldtilesize, node_tiledimage_float_10_filtertype, node_tiledimage_float_10_framerange, node_tiledimage_float_10_frameoffset, node_tiledimage_float_10_frameendaction, node_tiledimage_float_10_out); + float node_tiledimage_float_22_out = 0.0; + NG_tiledimage_float(node_tiledimage_float_22_file_, node_tiledimage_float_22_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_float_22_uvoffset, node_tiledimage_float_22_realworldimagesize, node_tiledimage_float_22_realworldtilesize, node_tiledimage_float_22_filtertype, node_tiledimage_float_22_framerange, node_tiledimage_float_22_frameoffset, node_tiledimage_float_22_frameendaction, node_tiledimage_float_22_out); + vector node_tiledimage_vector3_27_out = vector(0.0); + NG_tiledimage_vector3(node_tiledimage_vector3_27_file_, node_tiledimage_vector3_27_default, geomprop_UV0_out1, node_convert_1_out, node_tiledimage_vector3_27_uvoffset, node_tiledimage_vector3_27_realworldimagesize, node_tiledimage_vector3_27_realworldtilesize, node_tiledimage_vector3_27_filtertype, node_tiledimage_vector3_27_framerange, node_tiledimage_vector3_27_frameoffset, node_tiledimage_vector3_27_frameendaction, node_tiledimage_vector3_27_out); + float node_multiply_25_out = node_multiply_25_in1 * node_tiledimage_float_26_out; + float node_multiply_20_out = node_multiply_20_in1 * node_tiledimage_float_26_out; + color node_multiply_9_out = node_multiply_9_in1 * node_tiledimage_float_7_out; + float node_multiply_23_out = node_multiply_23_in1 * node_tiledimage_float_24_out; + float node_max_1_out = max(node_tiledimage_float_10_out, node_max_1_in2); + vector node_normalmap_3_out = vector(0.0); + mx_normalmap_float(node_tiledimage_vector3_27_out, node_normalmap_3_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, node_normalmap_3_out); + float node_add_19_out = node_multiply_25_out + node_tiledimage_float_7_out; + float node_divide_21_out = node_divide_21_in1 / node_max_1_out; + float node_subtract_18_out = node_add_19_out - node_subtract_18_in2; + float node_multiply_15_out = node_add_19_out * node_multiply_20_out; + float node_multiply_1_out = node_divide_21_out * node_tiledimage_float_22_out; + float node_multiply_14_out = node_subtract_18_out * node_multiply_14_in2; + color node_combine3_color3_13_out = color( node_multiply_14_out,node_combine3_color3_13_in2,node_multiply_15_out ); + color node_add_16_out = node_combine3_color3_13_out + node_rgbtohsv_12_out; + color node_hsvtorgb_17_out = color(0.0); + mx_hsvtorgb_color3(node_add_16_out, node_hsvtorgb_17_out); + color node_mix_6_out = mix(node_hsvtorgb_17_out, node_mix_6_fg, node_multiply_23_out); + color node_multiply_5_out = node_mix_6_out * node_tiledimage_float_7_out; + color node_mix_8_out = mix(node_multiply_9_out, node_multiply_5_out, node_tiledimage_float_10_out); + color node_clamp_0_out = clamp(node_mix_8_out, node_clamp_0_low, node_clamp_0_high); + surfaceshader N_StandardSurface_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(N_StandardSurface_base, node_clamp_0_out, N_StandardSurface_diffuse_roughness, N_StandardSurface_metalness, N_StandardSurface_specular, N_StandardSurface_specular_color, node_multiply_1_out, N_StandardSurface_specular_IOR, N_StandardSurface_specular_anisotropy, N_StandardSurface_specular_rotation, N_StandardSurface_transmission, N_StandardSurface_transmission_color, N_StandardSurface_transmission_depth, N_StandardSurface_transmission_scatter, N_StandardSurface_transmission_scatter_anisotropy, N_StandardSurface_transmission_dispersion, N_StandardSurface_transmission_extra_roughness, N_StandardSurface_subsurface, N_StandardSurface_subsurface_color, N_StandardSurface_subsurface_radius, N_StandardSurface_subsurface_scale, N_StandardSurface_subsurface_anisotropy, N_StandardSurface_sheen, N_StandardSurface_sheen_color, N_StandardSurface_sheen_roughness, N_StandardSurface_coat, N_StandardSurface_coat_color, N_StandardSurface_coat_roughness, N_StandardSurface_coat_anisotropy, N_StandardSurface_coat_rotation, N_StandardSurface_coat_IOR, geomprop_Nworld_out1, N_StandardSurface_coat_affect_color, N_StandardSurface_coat_affect_roughness, N_StandardSurface_thin_film_thickness, N_StandardSurface_thin_film_IOR, N_StandardSurface_emission, N_StandardSurface_emission_color, N_StandardSurface_opacity, N_StandardSurface_thin_walled, node_normalmap_3_out, geomprop_Tworld_out1, N_StandardSurface_out); + MATERIAL M_BrickPattern_out = mx_surfacematerial(N_StandardSurface_out, backsurfaceshader, displacementshader1); + out = M_BrickPattern_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Castle_B.glsl.frag b/Materials/Examples/StandardSurface/M_Castle_B.glsl.frag new file mode 100644 index 0000000000..7d1edf0228 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Castle_B.glsl.frag @@ -0,0 +1,2013 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D diffuse6_file; +uniform int diffuse6_layer = 0; +uniform vec3 diffuse6_default = vec3(0.000000, 0.000000, 0.000000); +uniform int diffuse6_uaddressmode = 2; +uniform int diffuse6_vaddressmode = 2; +uniform int diffuse6_filtertype = 1; +uniform int diffuse6_framerange = 0; +uniform int diffuse6_frameoffset = 0; +uniform int diffuse6_frameendaction = 0; +uniform vec2 diffuse6_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 diffuse6_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D metallic6_file; +uniform int metallic6_layer = 0; +uniform float metallic6_default = 0.000000; +uniform int metallic6_uaddressmode = 2; +uniform int metallic6_vaddressmode = 2; +uniform int metallic6_filtertype = 1; +uniform int metallic6_framerange = 0; +uniform int metallic6_frameoffset = 0; +uniform int metallic6_frameendaction = 0; +uniform vec2 metallic6_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 metallic6_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D roughness6_file; +uniform int roughness6_layer = 0; +uniform float roughness6_default = 0.000000; +uniform int roughness6_uaddressmode = 2; +uniform int roughness6_vaddressmode = 2; +uniform int roughness6_filtertype = 1; +uniform int roughness6_framerange = 0; +uniform int roughness6_frameoffset = 0; +uniform int roughness6_frameendaction = 0; +uniform vec2 roughness6_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 roughness6_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D normal6_file; +uniform int normal6_layer = 0; +uniform vec3 normal6_default = vec3(0.000000, 0.000000, 0.000000); +uniform int normal6_uaddressmode = 2; +uniform int normal6_vaddressmode = 2; +uniform int normal6_filtertype = 1; +uniform int normal6_framerange = 0; +uniform int normal6_frameoffset = 0; +uniform int normal6_frameendaction = 0; +uniform vec2 normal6_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 normal6_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap8_scale = 1.000000; +uniform float Castle_B_base = 1.000000; +uniform float Castle_B_diffuse_roughness = 0.000000; +uniform float Castle_B_specular = 1.000000; +uniform vec3 Castle_B_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Castle_B_specular_IOR = 1.500000; +uniform float Castle_B_specular_anisotropy = 0.000000; +uniform float Castle_B_specular_rotation = 0.000000; +uniform float Castle_B_transmission = 0.000000; +uniform vec3 Castle_B_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Castle_B_transmission_depth = 0.000000; +uniform vec3 Castle_B_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Castle_B_transmission_scatter_anisotropy = 0.000000; +uniform float Castle_B_transmission_dispersion = 0.000000; +uniform float Castle_B_transmission_extra_roughness = 0.000000; +uniform float Castle_B_subsurface = 0.000000; +uniform float Castle_B_subsurface_scale = 0.003000; +uniform float Castle_B_subsurface_anisotropy = 0.000000; +uniform float Castle_B_sheen = 0.000000; +uniform vec3 Castle_B_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Castle_B_sheen_roughness = 0.300000; +uniform float Castle_B_coat = 0.000000; +uniform vec3 Castle_B_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Castle_B_coat_roughness = 0.100000; +uniform float Castle_B_coat_anisotropy = 0.000000; +uniform float Castle_B_coat_rotation = 0.000000; +uniform float Castle_B_coat_IOR = 1.500000; +uniform float Castle_B_coat_affect_color = 0.000000; +uniform float Castle_B_coat_affect_roughness = 0.000000; +uniform float Castle_B_thin_film_thickness = 0.000000; +uniform float Castle_B_thin_film_IOR = 1.500000; +uniform float Castle_B_emission = 0.000000; +uniform vec3 Castle_B_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Castle_B_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Castle_B_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse6_out = vec3(0.0); + mx_image_color3(diffuse6_file, diffuse6_layer, diffuse6_default, geomprop_UV0_out1, diffuse6_uaddressmode, diffuse6_vaddressmode, diffuse6_filtertype, diffuse6_framerange, diffuse6_frameoffset, diffuse6_frameendaction, diffuse6_uv_scale, diffuse6_uv_offset, diffuse6_out); + float metallic6_out = 0.0; + mx_image_float(metallic6_file, metallic6_layer, metallic6_default, geomprop_UV0_out1, metallic6_uaddressmode, metallic6_vaddressmode, metallic6_filtertype, metallic6_framerange, metallic6_frameoffset, metallic6_frameendaction, metallic6_uv_scale, metallic6_uv_offset, metallic6_out); + float roughness6_out = 0.0; + mx_image_float(roughness6_file, roughness6_layer, roughness6_default, geomprop_UV0_out1, roughness6_uaddressmode, roughness6_vaddressmode, roughness6_filtertype, roughness6_framerange, roughness6_frameoffset, roughness6_frameendaction, roughness6_uv_scale, roughness6_uv_offset, roughness6_out); + vec3 normal6_out = vec3(0.0); + mx_image_vector3(normal6_file, normal6_layer, normal6_default, geomprop_UV0_out1, normal6_uaddressmode, normal6_vaddressmode, normal6_filtertype, normal6_framerange, normal6_frameoffset, normal6_frameendaction, normal6_uv_scale, normal6_uv_offset, normal6_out); + vec3 diffuse6_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse6_out, diffuse6_out_cm_out); + vec3 mtlxnormalmap8_out = vec3(0.0); + mx_normalmap_float(normal6_out, mtlxnormalmap8_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap8_out); + surfaceshader Castle_B_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Castle_B_base, diffuse6_out_cm_out, Castle_B_diffuse_roughness, metallic6_out, Castle_B_specular, Castle_B_specular_color, roughness6_out, Castle_B_specular_IOR, Castle_B_specular_anisotropy, Castle_B_specular_rotation, Castle_B_transmission, Castle_B_transmission_color, Castle_B_transmission_depth, Castle_B_transmission_scatter, Castle_B_transmission_scatter_anisotropy, Castle_B_transmission_dispersion, Castle_B_transmission_extra_roughness, Castle_B_subsurface, diffuse6_out_cm_out, diffuse6_out_cm_out, Castle_B_subsurface_scale, Castle_B_subsurface_anisotropy, Castle_B_sheen, Castle_B_sheen_color, Castle_B_sheen_roughness, Castle_B_coat, Castle_B_coat_color, Castle_B_coat_roughness, Castle_B_coat_anisotropy, Castle_B_coat_rotation, Castle_B_coat_IOR, geomprop_Nworld_out1, Castle_B_coat_affect_color, Castle_B_coat_affect_roughness, Castle_B_thin_film_thickness, Castle_B_thin_film_IOR, Castle_B_emission, Castle_B_emission_color, Castle_B_opacity, Castle_B_thin_walled, mtlxnormalmap8_out, geomprop_Tworld_out1, Castle_B_out); + material M_Castle_B_out = Castle_B_out; + out1 = vec4(M_Castle_B_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Castle_B.glsl.vert b/Materials/Examples/StandardSurface/M_Castle_B.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Castle_B.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Castle_B.mdl b/Materials/Examples/StandardSurface/M_Castle_B.mdl new file mode 100644 index 0000000000..528d06fa92 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Castle_B.mdl @@ -0,0 +1,506 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Castle_B +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d diffuse6_file = texture_2d("/chess_set/castle_black_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_CastleBlack/diffuse6/file") + ]], + uniform string diffuse6_layer = "" + [[ + materialx::core::origin("NG_CastleBlack/diffuse6/layer") + ]], + color diffuse6_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_CastleBlack/diffuse6/default") + ]], + uniform mx_addressmode_type diffuse6_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleBlack/diffuse6/uaddressmode") + ]], + uniform mx_addressmode_type diffuse6_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleBlack/diffuse6/vaddressmode") + ]], + uniform mx_filterlookup_type diffuse6_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_CastleBlack/diffuse6/filtertype") + ]], + uniform string diffuse6_framerange = "" + [[ + materialx::core::origin("NG_CastleBlack/diffuse6/framerange") + ]], + uniform int diffuse6_frameoffset = 0 + [[ + materialx::core::origin("NG_CastleBlack/diffuse6/frameoffset") + ]], + uniform mx_addressmode_type diffuse6_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_CastleBlack/diffuse6/frameendaction") + ]], + uniform texture_2d metallic6_file = texture_2d("/chess_set/castle_shared_metallic.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_CastleBlack/metallic6/file") + ]], + uniform string metallic6_layer = "" + [[ + materialx::core::origin("NG_CastleBlack/metallic6/layer") + ]], + float metallic6_default = 0.000000 + [[ + materialx::core::origin("NG_CastleBlack/metallic6/default") + ]], + uniform mx_addressmode_type metallic6_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleBlack/metallic6/uaddressmode") + ]], + uniform mx_addressmode_type metallic6_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleBlack/metallic6/vaddressmode") + ]], + uniform mx_filterlookup_type metallic6_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_CastleBlack/metallic6/filtertype") + ]], + uniform string metallic6_framerange = "" + [[ + materialx::core::origin("NG_CastleBlack/metallic6/framerange") + ]], + uniform int metallic6_frameoffset = 0 + [[ + materialx::core::origin("NG_CastleBlack/metallic6/frameoffset") + ]], + uniform mx_addressmode_type metallic6_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_CastleBlack/metallic6/frameendaction") + ]], + uniform texture_2d roughness6_file = texture_2d("/chess_set/castle_shared_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_CastleBlack/roughness6/file") + ]], + uniform string roughness6_layer = "" + [[ + materialx::core::origin("NG_CastleBlack/roughness6/layer") + ]], + float roughness6_default = 0.000000 + [[ + materialx::core::origin("NG_CastleBlack/roughness6/default") + ]], + uniform mx_addressmode_type roughness6_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleBlack/roughness6/uaddressmode") + ]], + uniform mx_addressmode_type roughness6_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleBlack/roughness6/vaddressmode") + ]], + uniform mx_filterlookup_type roughness6_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_CastleBlack/roughness6/filtertype") + ]], + uniform string roughness6_framerange = "" + [[ + materialx::core::origin("NG_CastleBlack/roughness6/framerange") + ]], + uniform int roughness6_frameoffset = 0 + [[ + materialx::core::origin("NG_CastleBlack/roughness6/frameoffset") + ]], + uniform mx_addressmode_type roughness6_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_CastleBlack/roughness6/frameendaction") + ]], + uniform texture_2d normal6_file = texture_2d("/chess_set/castle_shared_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_CastleBlack/normal6/file") + ]], + uniform string normal6_layer = "" + [[ + materialx::core::origin("NG_CastleBlack/normal6/layer") + ]], + float3 normal6_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_CastleBlack/normal6/default") + ]], + uniform mx_addressmode_type normal6_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleBlack/normal6/uaddressmode") + ]], + uniform mx_addressmode_type normal6_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleBlack/normal6/vaddressmode") + ]], + uniform mx_filterlookup_type normal6_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_CastleBlack/normal6/filtertype") + ]], + uniform string normal6_framerange = "" + [[ + materialx::core::origin("NG_CastleBlack/normal6/framerange") + ]], + uniform int normal6_frameoffset = 0 + [[ + materialx::core::origin("NG_CastleBlack/normal6/frameoffset") + ]], + uniform mx_addressmode_type normal6_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_CastleBlack/normal6/frameendaction") + ]], + float mtlxnormalmap8_scale = 1.000000 + [[ + materialx::core::origin("NG_CastleBlack/mtlxnormalmap8/scale") + ]], + float Castle_B_base = 1.000000 + [[ + materialx::core::origin("Castle_B/base") + ]], + float Castle_B_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Castle_B/diffuse_roughness") + ]], + float Castle_B_specular = 1.000000 + [[ + materialx::core::origin("Castle_B/specular") + ]], + color Castle_B_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Castle_B/specular_color") + ]], + uniform float Castle_B_specular_IOR = 1.500000 + [[ + materialx::core::origin("Castle_B/specular_IOR") + ]], + float Castle_B_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Castle_B/specular_anisotropy") + ]], + float Castle_B_specular_rotation = 0.000000 + [[ + materialx::core::origin("Castle_B/specular_rotation") + ]], + float Castle_B_transmission = 0.000000 + [[ + materialx::core::origin("Castle_B/transmission") + ]], + color Castle_B_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Castle_B/transmission_color") + ]], + float Castle_B_transmission_depth = 0.000000 + [[ + materialx::core::origin("Castle_B/transmission_depth") + ]], + color Castle_B_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Castle_B/transmission_scatter") + ]], + float Castle_B_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Castle_B/transmission_scatter_anisotropy") + ]], + float Castle_B_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Castle_B/transmission_dispersion") + ]], + float Castle_B_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Castle_B/transmission_extra_roughness") + ]], + float Castle_B_subsurface = 0.000000 + [[ + materialx::core::origin("Castle_B/subsurface") + ]], + float Castle_B_subsurface_scale = 0.003000 + [[ + materialx::core::origin("Castle_B/subsurface_scale") + ]], + float Castle_B_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Castle_B/subsurface_anisotropy") + ]], + float Castle_B_sheen = 0.000000 + [[ + materialx::core::origin("Castle_B/sheen") + ]], + color Castle_B_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Castle_B/sheen_color") + ]], + float Castle_B_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Castle_B/sheen_roughness") + ]], + float Castle_B_coat = 0.000000 + [[ + materialx::core::origin("Castle_B/coat") + ]], + color Castle_B_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Castle_B/coat_color") + ]], + float Castle_B_coat_roughness = 0.100000 + [[ + materialx::core::origin("Castle_B/coat_roughness") + ]], + float Castle_B_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Castle_B/coat_anisotropy") + ]], + float Castle_B_coat_rotation = 0.000000 + [[ + materialx::core::origin("Castle_B/coat_rotation") + ]], + uniform float Castle_B_coat_IOR = 1.500000 + [[ + materialx::core::origin("Castle_B/coat_IOR") + ]], + float Castle_B_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Castle_B/coat_affect_color") + ]], + float Castle_B_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Castle_B/coat_affect_roughness") + ]], + float Castle_B_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Castle_B/thin_film_thickness") + ]], + float Castle_B_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Castle_B/thin_film_IOR") + ]], + float Castle_B_emission = 0.000000 + [[ + materialx::core::origin("Castle_B/emission") + ]], + color Castle_B_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Castle_B/emission_color") + ]], + color Castle_B_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Castle_B/opacity") + ]], + bool Castle_B_thin_walled = false + [[ + materialx::core::origin("Castle_B/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color diffuse6_out = materialx::stdlib_1_8::mx_image_color3(diffuse6_file, diffuse6_layer, diffuse6_default, geomprop_UV0_out1, diffuse6_uaddressmode, diffuse6_vaddressmode, diffuse6_filtertype, diffuse6_framerange, diffuse6_frameoffset, diffuse6_frameendaction, mxp_flip_v:false); + float metallic6_out = materialx::stdlib_1_8::mx_image_float(metallic6_file, metallic6_layer, metallic6_default, geomprop_UV0_out1, metallic6_uaddressmode, metallic6_vaddressmode, metallic6_filtertype, metallic6_framerange, metallic6_frameoffset, metallic6_frameendaction, mxp_flip_v:false); + float roughness6_out = materialx::stdlib_1_8::mx_image_float(roughness6_file, roughness6_layer, roughness6_default, geomprop_UV0_out1, roughness6_uaddressmode, roughness6_vaddressmode, roughness6_filtertype, roughness6_framerange, roughness6_frameoffset, roughness6_frameendaction, mxp_flip_v:false); + float3 normal6_out = materialx::stdlib_1_8::mx_image_vector3(normal6_file, normal6_layer, normal6_default, geomprop_UV0_out1, normal6_uaddressmode, normal6_vaddressmode, normal6_filtertype, normal6_framerange, normal6_frameoffset, normal6_frameendaction, mxp_flip_v:false); + color diffuse6_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(diffuse6_out); + float3 mtlxnormalmap8_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:normal6_out, mxp_scale:mtlxnormalmap8_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Castle_B_out = NG_standard_surface_surfaceshader_100(Castle_B_base, diffuse6_out_cm_out, Castle_B_diffuse_roughness, metallic6_out, Castle_B_specular, Castle_B_specular_color, roughness6_out, Castle_B_specular_IOR, Castle_B_specular_anisotropy, Castle_B_specular_rotation, Castle_B_transmission, Castle_B_transmission_color, Castle_B_transmission_depth, Castle_B_transmission_scatter, Castle_B_transmission_scatter_anisotropy, Castle_B_transmission_dispersion, Castle_B_transmission_extra_roughness, Castle_B_subsurface, diffuse6_out_cm_out, diffuse6_out_cm_out, Castle_B_subsurface_scale, Castle_B_subsurface_anisotropy, Castle_B_sheen, Castle_B_sheen_color, Castle_B_sheen_roughness, Castle_B_coat, Castle_B_coat_color, Castle_B_coat_roughness, Castle_B_coat_anisotropy, Castle_B_coat_rotation, Castle_B_coat_IOR, geomprop_Nworld_out1, Castle_B_coat_affect_color, Castle_B_coat_affect_roughness, Castle_B_thin_film_thickness, Castle_B_thin_film_IOR, Castle_B_emission, Castle_B_emission_color, Castle_B_opacity, Castle_B_thin_walled, mtlxnormalmap8_out, geomprop_Tworld_out1); + material M_Castle_B_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Castle_B_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Castle_B_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Castle_B.msl.frag b/Materials/Examples/StandardSurface/M_Castle_B.msl.frag new file mode 100644 index 0000000000..dd464ec5e0 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Castle_B.msl.frag @@ -0,0 +1,2961 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int diffuse6_layer; + vec3 diffuse6_default; + int diffuse6_uaddressmode; + int diffuse6_vaddressmode; + int diffuse6_filtertype; + int diffuse6_framerange; + int diffuse6_frameoffset; + int diffuse6_frameendaction; + vec2 diffuse6_uv_scale; + vec2 diffuse6_uv_offset; + int metallic6_layer; + float metallic6_default; + int metallic6_uaddressmode; + int metallic6_vaddressmode; + int metallic6_filtertype; + int metallic6_framerange; + int metallic6_frameoffset; + int metallic6_frameendaction; + vec2 metallic6_uv_scale; + vec2 metallic6_uv_offset; + int roughness6_layer; + float roughness6_default; + int roughness6_uaddressmode; + int roughness6_vaddressmode; + int roughness6_filtertype; + int roughness6_framerange; + int roughness6_frameoffset; + int roughness6_frameendaction; + vec2 roughness6_uv_scale; + vec2 roughness6_uv_offset; + int normal6_layer; + vec3 normal6_default; + int normal6_uaddressmode; + int normal6_vaddressmode; + int normal6_filtertype; + int normal6_framerange; + int normal6_frameoffset; + int normal6_frameendaction; + vec2 normal6_uv_scale; + vec2 normal6_uv_offset; + float mtlxnormalmap8_scale; + float Castle_B_base; + float Castle_B_diffuse_roughness; + float Castle_B_specular; + vec3 Castle_B_specular_color; + float Castle_B_specular_IOR; + float Castle_B_specular_anisotropy; + float Castle_B_specular_rotation; + float Castle_B_transmission; + vec3 Castle_B_transmission_color; + float Castle_B_transmission_depth; + vec3 Castle_B_transmission_scatter; + float Castle_B_transmission_scatter_anisotropy; + float Castle_B_transmission_dispersion; + float Castle_B_transmission_extra_roughness; + float Castle_B_subsurface; + float Castle_B_subsurface_scale; + float Castle_B_subsurface_anisotropy; + float Castle_B_sheen; + vec3 Castle_B_sheen_color; + float Castle_B_sheen_roughness; + float Castle_B_coat; + vec3 Castle_B_coat_color; + float Castle_B_coat_roughness; + float Castle_B_coat_anisotropy; + float Castle_B_coat_rotation; + float Castle_B_coat_IOR; + float Castle_B_coat_affect_color; + float Castle_B_coat_affect_roughness; + float Castle_B_thin_film_thickness; + float Castle_B_thin_film_IOR; + float Castle_B_emission; + vec3 Castle_B_emission_color; + vec3 Castle_B_opacity; + bool Castle_B_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture diffuse6_file , int diffuse6_layer + + , vec3 diffuse6_default + + , int diffuse6_uaddressmode + + , int diffuse6_vaddressmode + + , int diffuse6_filtertype + + , int diffuse6_framerange + + , int diffuse6_frameoffset + + , int diffuse6_frameendaction + + , vec2 diffuse6_uv_scale + + , vec2 diffuse6_uv_offset + +, MetalTexture metallic6_file , int metallic6_layer + + , float metallic6_default + + , int metallic6_uaddressmode + + , int metallic6_vaddressmode + + , int metallic6_filtertype + + , int metallic6_framerange + + , int metallic6_frameoffset + + , int metallic6_frameendaction + + , vec2 metallic6_uv_scale + + , vec2 metallic6_uv_offset + +, MetalTexture roughness6_file , int roughness6_layer + + , float roughness6_default + + , int roughness6_uaddressmode + + , int roughness6_vaddressmode + + , int roughness6_filtertype + + , int roughness6_framerange + + , int roughness6_frameoffset + + , int roughness6_frameendaction + + , vec2 roughness6_uv_scale + + , vec2 roughness6_uv_offset + +, MetalTexture normal6_file , int normal6_layer + + , vec3 normal6_default + + , int normal6_uaddressmode + + , int normal6_vaddressmode + + , int normal6_filtertype + + , int normal6_framerange + + , int normal6_frameoffset + + , int normal6_frameendaction + + , vec2 normal6_uv_scale + + , vec2 normal6_uv_offset + + , float mtlxnormalmap8_scale + + , float Castle_B_base + + , float Castle_B_diffuse_roughness + + , float Castle_B_specular + + , vec3 Castle_B_specular_color + + , float Castle_B_specular_IOR + + , float Castle_B_specular_anisotropy + + , float Castle_B_specular_rotation + + , float Castle_B_transmission + + , vec3 Castle_B_transmission_color + + , float Castle_B_transmission_depth + + , vec3 Castle_B_transmission_scatter + + , float Castle_B_transmission_scatter_anisotropy + + , float Castle_B_transmission_dispersion + + , float Castle_B_transmission_extra_roughness + + , float Castle_B_subsurface + + , float Castle_B_subsurface_scale + + , float Castle_B_subsurface_anisotropy + + , float Castle_B_sheen + + , vec3 Castle_B_sheen_color + + , float Castle_B_sheen_roughness + + , float Castle_B_coat + + , vec3 Castle_B_coat_color + + , float Castle_B_coat_roughness + + , float Castle_B_coat_anisotropy + + , float Castle_B_coat_rotation + + , float Castle_B_coat_IOR + + , float Castle_B_coat_affect_color + + , float Castle_B_coat_affect_roughness + + , float Castle_B_thin_film_thickness + + , float Castle_B_thin_film_IOR + + , float Castle_B_emission + + , vec3 Castle_B_emission_color + + , vec3 Castle_B_opacity + + , bool Castle_B_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, diffuse6_file(diffuse6_file) + , diffuse6_layer(diffuse6_layer) + + , diffuse6_default(diffuse6_default) + + , diffuse6_uaddressmode(diffuse6_uaddressmode) + + , diffuse6_vaddressmode(diffuse6_vaddressmode) + + , diffuse6_filtertype(diffuse6_filtertype) + + , diffuse6_framerange(diffuse6_framerange) + + , diffuse6_frameoffset(diffuse6_frameoffset) + + , diffuse6_frameendaction(diffuse6_frameendaction) + + , diffuse6_uv_scale(diffuse6_uv_scale) + + , diffuse6_uv_offset(diffuse6_uv_offset) + +, metallic6_file(metallic6_file) + , metallic6_layer(metallic6_layer) + + , metallic6_default(metallic6_default) + + , metallic6_uaddressmode(metallic6_uaddressmode) + + , metallic6_vaddressmode(metallic6_vaddressmode) + + , metallic6_filtertype(metallic6_filtertype) + + , metallic6_framerange(metallic6_framerange) + + , metallic6_frameoffset(metallic6_frameoffset) + + , metallic6_frameendaction(metallic6_frameendaction) + + , metallic6_uv_scale(metallic6_uv_scale) + + , metallic6_uv_offset(metallic6_uv_offset) + +, roughness6_file(roughness6_file) + , roughness6_layer(roughness6_layer) + + , roughness6_default(roughness6_default) + + , roughness6_uaddressmode(roughness6_uaddressmode) + + , roughness6_vaddressmode(roughness6_vaddressmode) + + , roughness6_filtertype(roughness6_filtertype) + + , roughness6_framerange(roughness6_framerange) + + , roughness6_frameoffset(roughness6_frameoffset) + + , roughness6_frameendaction(roughness6_frameendaction) + + , roughness6_uv_scale(roughness6_uv_scale) + + , roughness6_uv_offset(roughness6_uv_offset) + +, normal6_file(normal6_file) + , normal6_layer(normal6_layer) + + , normal6_default(normal6_default) + + , normal6_uaddressmode(normal6_uaddressmode) + + , normal6_vaddressmode(normal6_vaddressmode) + + , normal6_filtertype(normal6_filtertype) + + , normal6_framerange(normal6_framerange) + + , normal6_frameoffset(normal6_frameoffset) + + , normal6_frameendaction(normal6_frameendaction) + + , normal6_uv_scale(normal6_uv_scale) + + , normal6_uv_offset(normal6_uv_offset) + + , mtlxnormalmap8_scale(mtlxnormalmap8_scale) + + , Castle_B_base(Castle_B_base) + + , Castle_B_diffuse_roughness(Castle_B_diffuse_roughness) + + , Castle_B_specular(Castle_B_specular) + + , Castle_B_specular_color(Castle_B_specular_color) + + , Castle_B_specular_IOR(Castle_B_specular_IOR) + + , Castle_B_specular_anisotropy(Castle_B_specular_anisotropy) + + , Castle_B_specular_rotation(Castle_B_specular_rotation) + + , Castle_B_transmission(Castle_B_transmission) + + , Castle_B_transmission_color(Castle_B_transmission_color) + + , Castle_B_transmission_depth(Castle_B_transmission_depth) + + , Castle_B_transmission_scatter(Castle_B_transmission_scatter) + + , Castle_B_transmission_scatter_anisotropy(Castle_B_transmission_scatter_anisotropy) + + , Castle_B_transmission_dispersion(Castle_B_transmission_dispersion) + + , Castle_B_transmission_extra_roughness(Castle_B_transmission_extra_roughness) + + , Castle_B_subsurface(Castle_B_subsurface) + + , Castle_B_subsurface_scale(Castle_B_subsurface_scale) + + , Castle_B_subsurface_anisotropy(Castle_B_subsurface_anisotropy) + + , Castle_B_sheen(Castle_B_sheen) + + , Castle_B_sheen_color(Castle_B_sheen_color) + + , Castle_B_sheen_roughness(Castle_B_sheen_roughness) + + , Castle_B_coat(Castle_B_coat) + + , Castle_B_coat_color(Castle_B_coat_color) + + , Castle_B_coat_roughness(Castle_B_coat_roughness) + + , Castle_B_coat_anisotropy(Castle_B_coat_anisotropy) + + , Castle_B_coat_rotation(Castle_B_coat_rotation) + + , Castle_B_coat_IOR(Castle_B_coat_IOR) + + , Castle_B_coat_affect_color(Castle_B_coat_affect_color) + + , Castle_B_coat_affect_roughness(Castle_B_coat_affect_roughness) + + , Castle_B_thin_film_thickness(Castle_B_thin_film_thickness) + + , Castle_B_thin_film_IOR(Castle_B_thin_film_IOR) + + , Castle_B_emission(Castle_B_emission) + + , Castle_B_emission_color(Castle_B_emission_color) + + , Castle_B_opacity(Castle_B_opacity) + + , Castle_B_thin_walled(Castle_B_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture diffuse6_file; + int diffuse6_layer; + + + vec3 diffuse6_default; + + + int diffuse6_uaddressmode; + + + int diffuse6_vaddressmode; + + + int diffuse6_filtertype; + + + int diffuse6_framerange; + + + int diffuse6_frameoffset; + + + int diffuse6_frameendaction; + + + vec2 diffuse6_uv_scale; + + + vec2 diffuse6_uv_offset; + + +MetalTexture metallic6_file; + int metallic6_layer; + + + float metallic6_default; + + + int metallic6_uaddressmode; + + + int metallic6_vaddressmode; + + + int metallic6_filtertype; + + + int metallic6_framerange; + + + int metallic6_frameoffset; + + + int metallic6_frameendaction; + + + vec2 metallic6_uv_scale; + + + vec2 metallic6_uv_offset; + + +MetalTexture roughness6_file; + int roughness6_layer; + + + float roughness6_default; + + + int roughness6_uaddressmode; + + + int roughness6_vaddressmode; + + + int roughness6_filtertype; + + + int roughness6_framerange; + + + int roughness6_frameoffset; + + + int roughness6_frameendaction; + + + vec2 roughness6_uv_scale; + + + vec2 roughness6_uv_offset; + + +MetalTexture normal6_file; + int normal6_layer; + + + vec3 normal6_default; + + + int normal6_uaddressmode; + + + int normal6_vaddressmode; + + + int normal6_filtertype; + + + int normal6_framerange; + + + int normal6_frameoffset; + + + int normal6_frameendaction; + + + vec2 normal6_uv_scale; + + + vec2 normal6_uv_offset; + + + float mtlxnormalmap8_scale; + + + float Castle_B_base; + + + float Castle_B_diffuse_roughness; + + + float Castle_B_specular; + + + vec3 Castle_B_specular_color; + + + float Castle_B_specular_IOR; + + + float Castle_B_specular_anisotropy; + + + float Castle_B_specular_rotation; + + + float Castle_B_transmission; + + + vec3 Castle_B_transmission_color; + + + float Castle_B_transmission_depth; + + + vec3 Castle_B_transmission_scatter; + + + float Castle_B_transmission_scatter_anisotropy; + + + float Castle_B_transmission_dispersion; + + + float Castle_B_transmission_extra_roughness; + + + float Castle_B_subsurface; + + + float Castle_B_subsurface_scale; + + + float Castle_B_subsurface_anisotropy; + + + float Castle_B_sheen; + + + vec3 Castle_B_sheen_color; + + + float Castle_B_sheen_roughness; + + + float Castle_B_coat; + + + vec3 Castle_B_coat_color; + + + float Castle_B_coat_roughness; + + + float Castle_B_coat_anisotropy; + + + float Castle_B_coat_rotation; + + + float Castle_B_coat_IOR; + + + float Castle_B_coat_affect_color; + + + float Castle_B_coat_affect_roughness; + + + float Castle_B_thin_film_thickness; + + + float Castle_B_thin_film_IOR; + + + float Castle_B_emission; + + + vec3 Castle_B_emission_color; + + + vec3 Castle_B_opacity; + + + bool Castle_B_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse6_out = vec3(0.0); + mx_image_color3(diffuse6_file, diffuse6_layer, diffuse6_default, geomprop_UV0_out1, diffuse6_uaddressmode, diffuse6_vaddressmode, diffuse6_filtertype, diffuse6_framerange, diffuse6_frameoffset, diffuse6_frameendaction, diffuse6_uv_scale, diffuse6_uv_offset, diffuse6_out); + float metallic6_out = 0.0; + mx_image_float(metallic6_file, metallic6_layer, metallic6_default, geomprop_UV0_out1, metallic6_uaddressmode, metallic6_vaddressmode, metallic6_filtertype, metallic6_framerange, metallic6_frameoffset, metallic6_frameendaction, metallic6_uv_scale, metallic6_uv_offset, metallic6_out); + float roughness6_out = 0.0; + mx_image_float(roughness6_file, roughness6_layer, roughness6_default, geomprop_UV0_out1, roughness6_uaddressmode, roughness6_vaddressmode, roughness6_filtertype, roughness6_framerange, roughness6_frameoffset, roughness6_frameendaction, roughness6_uv_scale, roughness6_uv_offset, roughness6_out); + vec3 normal6_out = vec3(0.0); + mx_image_vector3(normal6_file, normal6_layer, normal6_default, geomprop_UV0_out1, normal6_uaddressmode, normal6_vaddressmode, normal6_filtertype, normal6_framerange, normal6_frameoffset, normal6_frameendaction, normal6_uv_scale, normal6_uv_offset, normal6_out); + vec3 diffuse6_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse6_out, diffuse6_out_cm_out); + vec3 mtlxnormalmap8_out = vec3(0.0); + mx_normalmap_float(normal6_out, mtlxnormalmap8_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap8_out); + surfaceshader Castle_B_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Castle_B_base, diffuse6_out_cm_out, Castle_B_diffuse_roughness, metallic6_out, Castle_B_specular, Castle_B_specular_color, roughness6_out, Castle_B_specular_IOR, Castle_B_specular_anisotropy, Castle_B_specular_rotation, Castle_B_transmission, Castle_B_transmission_color, Castle_B_transmission_depth, Castle_B_transmission_scatter, Castle_B_transmission_scatter_anisotropy, Castle_B_transmission_dispersion, Castle_B_transmission_extra_roughness, Castle_B_subsurface, diffuse6_out_cm_out, diffuse6_out_cm_out, Castle_B_subsurface_scale, Castle_B_subsurface_anisotropy, Castle_B_sheen, Castle_B_sheen_color, Castle_B_sheen_roughness, Castle_B_coat, Castle_B_coat_color, Castle_B_coat_roughness, Castle_B_coat_anisotropy, Castle_B_coat_rotation, Castle_B_coat_IOR, geomprop_Nworld_out1, Castle_B_coat_affect_color, Castle_B_coat_affect_roughness, Castle_B_thin_film_thickness, Castle_B_thin_film_IOR, Castle_B_emission, Castle_B_emission_color, Castle_B_opacity, Castle_B_thin_walled, mtlxnormalmap8_out, geomprop_Tworld_out1, Castle_B_out); + material M_Castle_B_out = Castle_B_out; + out1 = float4(M_Castle_B_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d diffuse6_file_tex [[texture(0)]], sampler diffuse6_file_sampler [[sampler(0)]] +, texture2d metallic6_file_tex [[texture(1)]], sampler metallic6_file_sampler [[sampler(1)]] +, texture2d roughness6_file_tex [[texture(2)]], sampler roughness6_file_sampler [[sampler(2)]] +, texture2d normal6_file_tex [[texture(3)]], sampler normal6_file_sampler [[sampler(3)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(4)]], sampler u_envRadiance_sampler [[sampler(4)]] +, texture2d u_envIrradiance_tex [[texture(5)]], sampler u_envIrradiance_sampler [[sampler(5)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +diffuse6_file_tex, diffuse6_file_sampler } + , u_pub.diffuse6_layer + , u_pub.diffuse6_default + , u_pub.diffuse6_uaddressmode + , u_pub.diffuse6_vaddressmode + , u_pub.diffuse6_filtertype + , u_pub.diffuse6_framerange + , u_pub.diffuse6_frameoffset + , u_pub.diffuse6_frameendaction + , u_pub.diffuse6_uv_scale + , u_pub.diffuse6_uv_offset +, MetalTexture { +metallic6_file_tex, metallic6_file_sampler } + , u_pub.metallic6_layer + , u_pub.metallic6_default + , u_pub.metallic6_uaddressmode + , u_pub.metallic6_vaddressmode + , u_pub.metallic6_filtertype + , u_pub.metallic6_framerange + , u_pub.metallic6_frameoffset + , u_pub.metallic6_frameendaction + , u_pub.metallic6_uv_scale + , u_pub.metallic6_uv_offset +, MetalTexture { +roughness6_file_tex, roughness6_file_sampler } + , u_pub.roughness6_layer + , u_pub.roughness6_default + , u_pub.roughness6_uaddressmode + , u_pub.roughness6_vaddressmode + , u_pub.roughness6_filtertype + , u_pub.roughness6_framerange + , u_pub.roughness6_frameoffset + , u_pub.roughness6_frameendaction + , u_pub.roughness6_uv_scale + , u_pub.roughness6_uv_offset +, MetalTexture { +normal6_file_tex, normal6_file_sampler } + , u_pub.normal6_layer + , u_pub.normal6_default + , u_pub.normal6_uaddressmode + , u_pub.normal6_vaddressmode + , u_pub.normal6_filtertype + , u_pub.normal6_framerange + , u_pub.normal6_frameoffset + , u_pub.normal6_frameendaction + , u_pub.normal6_uv_scale + , u_pub.normal6_uv_offset + , u_pub.mtlxnormalmap8_scale + , u_pub.Castle_B_base + , u_pub.Castle_B_diffuse_roughness + , u_pub.Castle_B_specular + , u_pub.Castle_B_specular_color + , u_pub.Castle_B_specular_IOR + , u_pub.Castle_B_specular_anisotropy + , u_pub.Castle_B_specular_rotation + , u_pub.Castle_B_transmission + , u_pub.Castle_B_transmission_color + , u_pub.Castle_B_transmission_depth + , u_pub.Castle_B_transmission_scatter + , u_pub.Castle_B_transmission_scatter_anisotropy + , u_pub.Castle_B_transmission_dispersion + , u_pub.Castle_B_transmission_extra_roughness + , u_pub.Castle_B_subsurface + , u_pub.Castle_B_subsurface_scale + , u_pub.Castle_B_subsurface_anisotropy + , u_pub.Castle_B_sheen + , u_pub.Castle_B_sheen_color + , u_pub.Castle_B_sheen_roughness + , u_pub.Castle_B_coat + , u_pub.Castle_B_coat_color + , u_pub.Castle_B_coat_roughness + , u_pub.Castle_B_coat_anisotropy + , u_pub.Castle_B_coat_rotation + , u_pub.Castle_B_coat_IOR + , u_pub.Castle_B_coat_affect_color + , u_pub.Castle_B_coat_affect_roughness + , u_pub.Castle_B_thin_film_thickness + , u_pub.Castle_B_thin_film_IOR + , u_pub.Castle_B_emission + , u_pub.Castle_B_emission_color + , u_pub.Castle_B_opacity + , u_pub.Castle_B_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Castle_B.msl.vert b/Materials/Examples/StandardSurface/M_Castle_B.msl.vert new file mode 100644 index 0000000000..9d884f39ac --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Castle_B.msl.vert @@ -0,0 +1,127 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'diffuse6'. Function already called in this scope. + // Omitted node 'metallic6'. Function already called in this scope. + // Omitted node 'roughness6'. Function already called in this scope. + // Omitted node 'normal6'. Function already called in this scope. + // Omitted node 'diffuse6_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap8'. Function already called in this scope. + // Omitted node 'Castle_B'. Function already called in this scope. + // Omitted node 'M_Castle_B'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Castle_B.osl b/Materials/Examples/StandardSurface/M_Castle_B.osl new file mode 100644 index 0000000000..955440b0c1 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Castle_B.osl @@ -0,0 +1,678 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Castle_B +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Castle_B" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string diffuse6_file = "chess_set/castle_black_base_color.jpg" + [[ + string widget = "filename" + ]], + string diffuse6_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string diffuse6_layer = "", + color diffuse6_default = color(0.000000, 0.000000, 0.000000), + string diffuse6_uaddressmode = "periodic", + string diffuse6_vaddressmode = "periodic", + string diffuse6_filtertype = "linear", + string diffuse6_framerange = "", + int diffuse6_frameoffset = 0 + [[ + string widget = "number" + ]], + string diffuse6_frameendaction = "constant", + string metallic6_file = "chess_set/castle_shared_metallic.jpg" + [[ + string widget = "filename" + ]], + string metallic6_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string metallic6_layer = "", + float metallic6_default = 0.000000 + [[ + string widget = "number" + ]], + string metallic6_uaddressmode = "periodic", + string metallic6_vaddressmode = "periodic", + string metallic6_filtertype = "linear", + string metallic6_framerange = "", + int metallic6_frameoffset = 0 + [[ + string widget = "number" + ]], + string metallic6_frameendaction = "constant", + string roughness6_file = "chess_set/castle_shared_roughness.jpg" + [[ + string widget = "filename" + ]], + string roughness6_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string roughness6_layer = "", + float roughness6_default = 0.000000 + [[ + string widget = "number" + ]], + string roughness6_uaddressmode = "periodic", + string roughness6_vaddressmode = "periodic", + string roughness6_filtertype = "linear", + string roughness6_framerange = "", + int roughness6_frameoffset = 0 + [[ + string widget = "number" + ]], + string roughness6_frameendaction = "constant", + string normal6_file = "chess_set/castle_shared_normal.jpg" + [[ + string widget = "filename" + ]], + string normal6_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string normal6_layer = "", + vector normal6_default = vector(0.000000, 0.000000, 0.000000), + string normal6_uaddressmode = "periodic", + string normal6_vaddressmode = "periodic", + string normal6_filtertype = "linear", + string normal6_framerange = "", + int normal6_frameoffset = 0 + [[ + string widget = "number" + ]], + string normal6_frameendaction = "constant", + float mtlxnormalmap8_scale = 1.000000 + [[ + string widget = "number" + ]], + float Castle_B_base = 1.000000 + [[ + string widget = "number" + ]], + float Castle_B_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_specular = 1.000000 + [[ + string widget = "number" + ]], + color Castle_B_specular_color = color(1.000000, 1.000000, 1.000000), + float Castle_B_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Castle_B_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_transmission = 0.000000 + [[ + string widget = "number" + ]], + color Castle_B_transmission_color = color(1.000000, 1.000000, 1.000000), + float Castle_B_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Castle_B_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Castle_B_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_subsurface = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float Castle_B_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Castle_B_sheen_color = color(1.000000, 1.000000, 1.000000), + float Castle_B_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Castle_B_coat = 0.000000 + [[ + string widget = "number" + ]], + color Castle_B_coat_color = color(1.000000, 1.000000, 1.000000), + float Castle_B_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Castle_B_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Castle_B_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Castle_B_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Castle_B_emission = 0.000000 + [[ + string widget = "number" + ]], + color Castle_B_emission_color = color(1.000000, 1.000000, 1.000000), + color Castle_B_opacity = color(1.000000, 1.000000, 1.000000), + int Castle_B_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource diffuse6_file_ = {diffuse6_file, diffuse6_file_colorspace}; + textureresource metallic6_file_ = {metallic6_file, metallic6_file_colorspace}; + textureresource roughness6_file_ = {roughness6_file, roughness6_file_colorspace}; + textureresource normal6_file_ = {normal6_file, normal6_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color diffuse6_out = color(0.0); + mx_image_color3(diffuse6_file_, diffuse6_layer, diffuse6_default, geomprop_UV0_out1, diffuse6_uaddressmode, diffuse6_vaddressmode, diffuse6_filtertype, diffuse6_framerange, diffuse6_frameoffset, diffuse6_frameendaction, diffuse6_out); + float metallic6_out = 0.0; + mx_image_float(metallic6_file_, metallic6_layer, metallic6_default, geomprop_UV0_out1, metallic6_uaddressmode, metallic6_vaddressmode, metallic6_filtertype, metallic6_framerange, metallic6_frameoffset, metallic6_frameendaction, metallic6_out); + float roughness6_out = 0.0; + mx_image_float(roughness6_file_, roughness6_layer, roughness6_default, geomprop_UV0_out1, roughness6_uaddressmode, roughness6_vaddressmode, roughness6_filtertype, roughness6_framerange, roughness6_frameoffset, roughness6_frameendaction, roughness6_out); + vector normal6_out = vector(0.0); + mx_image_vector3(normal6_file_, normal6_layer, normal6_default, geomprop_UV0_out1, normal6_uaddressmode, normal6_vaddressmode, normal6_filtertype, normal6_framerange, normal6_frameoffset, normal6_frameendaction, normal6_out); + color diffuse6_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse6_out, diffuse6_out_cm_out); + vector mtlxnormalmap8_out = vector(0.0); + mx_normalmap_float(normal6_out, mtlxnormalmap8_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap8_out); + surfaceshader Castle_B_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Castle_B_base, diffuse6_out_cm_out, Castle_B_diffuse_roughness, metallic6_out, Castle_B_specular, Castle_B_specular_color, roughness6_out, Castle_B_specular_IOR, Castle_B_specular_anisotropy, Castle_B_specular_rotation, Castle_B_transmission, Castle_B_transmission_color, Castle_B_transmission_depth, Castle_B_transmission_scatter, Castle_B_transmission_scatter_anisotropy, Castle_B_transmission_dispersion, Castle_B_transmission_extra_roughness, Castle_B_subsurface, diffuse6_out_cm_out, diffuse6_out_cm_out, Castle_B_subsurface_scale, Castle_B_subsurface_anisotropy, Castle_B_sheen, Castle_B_sheen_color, Castle_B_sheen_roughness, Castle_B_coat, Castle_B_coat_color, Castle_B_coat_roughness, Castle_B_coat_anisotropy, Castle_B_coat_rotation, Castle_B_coat_IOR, geomprop_Nworld_out1, Castle_B_coat_affect_color, Castle_B_coat_affect_roughness, Castle_B_thin_film_thickness, Castle_B_thin_film_IOR, Castle_B_emission, Castle_B_emission_color, Castle_B_opacity, Castle_B_thin_walled, mtlxnormalmap8_out, geomprop_Tworld_out1, Castle_B_out); + MATERIAL M_Castle_B_out = mx_surfacematerial(Castle_B_out, backsurfaceshader, displacementshader1); + out = M_Castle_B_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Castle_W.glsl.frag b/Materials/Examples/StandardSurface/M_Castle_W.glsl.frag new file mode 100644 index 0000000000..1a010eaa8b --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Castle_W.glsl.frag @@ -0,0 +1,2013 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D diffuse7_file; +uniform int diffuse7_layer = 0; +uniform vec3 diffuse7_default = vec3(0.000000, 0.000000, 0.000000); +uniform int diffuse7_uaddressmode = 2; +uniform int diffuse7_vaddressmode = 2; +uniform int diffuse7_filtertype = 1; +uniform int diffuse7_framerange = 0; +uniform int diffuse7_frameoffset = 0; +uniform int diffuse7_frameendaction = 0; +uniform vec2 diffuse7_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 diffuse7_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D metallic7_file; +uniform int metallic7_layer = 0; +uniform float metallic7_default = 0.000000; +uniform int metallic7_uaddressmode = 2; +uniform int metallic7_vaddressmode = 2; +uniform int metallic7_filtertype = 1; +uniform int metallic7_framerange = 0; +uniform int metallic7_frameoffset = 0; +uniform int metallic7_frameendaction = 0; +uniform vec2 metallic7_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 metallic7_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D roughness7_file; +uniform int roughness7_layer = 0; +uniform float roughness7_default = 0.000000; +uniform int roughness7_uaddressmode = 2; +uniform int roughness7_vaddressmode = 2; +uniform int roughness7_filtertype = 1; +uniform int roughness7_framerange = 0; +uniform int roughness7_frameoffset = 0; +uniform int roughness7_frameendaction = 0; +uniform vec2 roughness7_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 roughness7_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D normal7_file; +uniform int normal7_layer = 0; +uniform vec3 normal7_default = vec3(0.000000, 0.000000, 0.000000); +uniform int normal7_uaddressmode = 2; +uniform int normal7_vaddressmode = 2; +uniform int normal7_filtertype = 1; +uniform int normal7_framerange = 0; +uniform int normal7_frameoffset = 0; +uniform int normal7_frameendaction = 0; +uniform vec2 normal7_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 normal7_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap9_scale = 1.000000; +uniform float Castle_W_base = 1.000000; +uniform float Castle_W_diffuse_roughness = 0.000000; +uniform float Castle_W_specular = 1.000000; +uniform vec3 Castle_W_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Castle_W_specular_IOR = 1.500000; +uniform float Castle_W_specular_anisotropy = 0.000000; +uniform float Castle_W_specular_rotation = 0.000000; +uniform float Castle_W_transmission = 0.000000; +uniform vec3 Castle_W_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Castle_W_transmission_depth = 0.000000; +uniform vec3 Castle_W_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Castle_W_transmission_scatter_anisotropy = 0.000000; +uniform float Castle_W_transmission_dispersion = 0.000000; +uniform float Castle_W_transmission_extra_roughness = 0.000000; +uniform float Castle_W_subsurface = 0.000000; +uniform float Castle_W_subsurface_scale = 0.003000; +uniform float Castle_W_subsurface_anisotropy = 0.000000; +uniform float Castle_W_sheen = 0.000000; +uniform vec3 Castle_W_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Castle_W_sheen_roughness = 0.300000; +uniform float Castle_W_coat = 0.000000; +uniform vec3 Castle_W_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Castle_W_coat_roughness = 0.100000; +uniform float Castle_W_coat_anisotropy = 0.000000; +uniform float Castle_W_coat_rotation = 0.000000; +uniform float Castle_W_coat_IOR = 1.500000; +uniform float Castle_W_coat_affect_color = 0.000000; +uniform float Castle_W_coat_affect_roughness = 0.000000; +uniform float Castle_W_thin_film_thickness = 0.000000; +uniform float Castle_W_thin_film_IOR = 1.500000; +uniform float Castle_W_emission = 0.000000; +uniform vec3 Castle_W_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Castle_W_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Castle_W_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse7_out = vec3(0.0); + mx_image_color3(diffuse7_file, diffuse7_layer, diffuse7_default, geomprop_UV0_out1, diffuse7_uaddressmode, diffuse7_vaddressmode, diffuse7_filtertype, diffuse7_framerange, diffuse7_frameoffset, diffuse7_frameendaction, diffuse7_uv_scale, diffuse7_uv_offset, diffuse7_out); + float metallic7_out = 0.0; + mx_image_float(metallic7_file, metallic7_layer, metallic7_default, geomprop_UV0_out1, metallic7_uaddressmode, metallic7_vaddressmode, metallic7_filtertype, metallic7_framerange, metallic7_frameoffset, metallic7_frameendaction, metallic7_uv_scale, metallic7_uv_offset, metallic7_out); + float roughness7_out = 0.0; + mx_image_float(roughness7_file, roughness7_layer, roughness7_default, geomprop_UV0_out1, roughness7_uaddressmode, roughness7_vaddressmode, roughness7_filtertype, roughness7_framerange, roughness7_frameoffset, roughness7_frameendaction, roughness7_uv_scale, roughness7_uv_offset, roughness7_out); + vec3 normal7_out = vec3(0.0); + mx_image_vector3(normal7_file, normal7_layer, normal7_default, geomprop_UV0_out1, normal7_uaddressmode, normal7_vaddressmode, normal7_filtertype, normal7_framerange, normal7_frameoffset, normal7_frameendaction, normal7_uv_scale, normal7_uv_offset, normal7_out); + vec3 diffuse7_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse7_out, diffuse7_out_cm_out); + vec3 mtlxnormalmap9_out = vec3(0.0); + mx_normalmap_float(normal7_out, mtlxnormalmap9_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap9_out); + surfaceshader Castle_W_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Castle_W_base, diffuse7_out_cm_out, Castle_W_diffuse_roughness, metallic7_out, Castle_W_specular, Castle_W_specular_color, roughness7_out, Castle_W_specular_IOR, Castle_W_specular_anisotropy, Castle_W_specular_rotation, Castle_W_transmission, Castle_W_transmission_color, Castle_W_transmission_depth, Castle_W_transmission_scatter, Castle_W_transmission_scatter_anisotropy, Castle_W_transmission_dispersion, Castle_W_transmission_extra_roughness, Castle_W_subsurface, diffuse7_out_cm_out, diffuse7_out_cm_out, Castle_W_subsurface_scale, Castle_W_subsurface_anisotropy, Castle_W_sheen, Castle_W_sheen_color, Castle_W_sheen_roughness, Castle_W_coat, Castle_W_coat_color, Castle_W_coat_roughness, Castle_W_coat_anisotropy, Castle_W_coat_rotation, Castle_W_coat_IOR, geomprop_Nworld_out1, Castle_W_coat_affect_color, Castle_W_coat_affect_roughness, Castle_W_thin_film_thickness, Castle_W_thin_film_IOR, Castle_W_emission, Castle_W_emission_color, Castle_W_opacity, Castle_W_thin_walled, mtlxnormalmap9_out, geomprop_Tworld_out1, Castle_W_out); + material M_Castle_W_out = Castle_W_out; + out1 = vec4(M_Castle_W_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Castle_W.glsl.vert b/Materials/Examples/StandardSurface/M_Castle_W.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Castle_W.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Castle_W.mdl b/Materials/Examples/StandardSurface/M_Castle_W.mdl new file mode 100644 index 0000000000..b2a2553c4e --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Castle_W.mdl @@ -0,0 +1,506 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Castle_W +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d diffuse7_file = texture_2d("/chess_set/castle_white_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_CastleWhite/diffuse7/file") + ]], + uniform string diffuse7_layer = "" + [[ + materialx::core::origin("NG_CastleWhite/diffuse7/layer") + ]], + color diffuse7_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_CastleWhite/diffuse7/default") + ]], + uniform mx_addressmode_type diffuse7_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleWhite/diffuse7/uaddressmode") + ]], + uniform mx_addressmode_type diffuse7_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleWhite/diffuse7/vaddressmode") + ]], + uniform mx_filterlookup_type diffuse7_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_CastleWhite/diffuse7/filtertype") + ]], + uniform string diffuse7_framerange = "" + [[ + materialx::core::origin("NG_CastleWhite/diffuse7/framerange") + ]], + uniform int diffuse7_frameoffset = 0 + [[ + materialx::core::origin("NG_CastleWhite/diffuse7/frameoffset") + ]], + uniform mx_addressmode_type diffuse7_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_CastleWhite/diffuse7/frameendaction") + ]], + uniform texture_2d metallic7_file = texture_2d("/chess_set/castle_shared_metallic.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_CastleWhite/metallic7/file") + ]], + uniform string metallic7_layer = "" + [[ + materialx::core::origin("NG_CastleWhite/metallic7/layer") + ]], + float metallic7_default = 0.000000 + [[ + materialx::core::origin("NG_CastleWhite/metallic7/default") + ]], + uniform mx_addressmode_type metallic7_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleWhite/metallic7/uaddressmode") + ]], + uniform mx_addressmode_type metallic7_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleWhite/metallic7/vaddressmode") + ]], + uniform mx_filterlookup_type metallic7_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_CastleWhite/metallic7/filtertype") + ]], + uniform string metallic7_framerange = "" + [[ + materialx::core::origin("NG_CastleWhite/metallic7/framerange") + ]], + uniform int metallic7_frameoffset = 0 + [[ + materialx::core::origin("NG_CastleWhite/metallic7/frameoffset") + ]], + uniform mx_addressmode_type metallic7_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_CastleWhite/metallic7/frameendaction") + ]], + uniform texture_2d roughness7_file = texture_2d("/chess_set/castle_shared_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_CastleWhite/roughness7/file") + ]], + uniform string roughness7_layer = "" + [[ + materialx::core::origin("NG_CastleWhite/roughness7/layer") + ]], + float roughness7_default = 0.000000 + [[ + materialx::core::origin("NG_CastleWhite/roughness7/default") + ]], + uniform mx_addressmode_type roughness7_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleWhite/roughness7/uaddressmode") + ]], + uniform mx_addressmode_type roughness7_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleWhite/roughness7/vaddressmode") + ]], + uniform mx_filterlookup_type roughness7_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_CastleWhite/roughness7/filtertype") + ]], + uniform string roughness7_framerange = "" + [[ + materialx::core::origin("NG_CastleWhite/roughness7/framerange") + ]], + uniform int roughness7_frameoffset = 0 + [[ + materialx::core::origin("NG_CastleWhite/roughness7/frameoffset") + ]], + uniform mx_addressmode_type roughness7_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_CastleWhite/roughness7/frameendaction") + ]], + uniform texture_2d normal7_file = texture_2d("/chess_set/castle_shared_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_CastleWhite/normal7/file") + ]], + uniform string normal7_layer = "" + [[ + materialx::core::origin("NG_CastleWhite/normal7/layer") + ]], + float3 normal7_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_CastleWhite/normal7/default") + ]], + uniform mx_addressmode_type normal7_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleWhite/normal7/uaddressmode") + ]], + uniform mx_addressmode_type normal7_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_CastleWhite/normal7/vaddressmode") + ]], + uniform mx_filterlookup_type normal7_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_CastleWhite/normal7/filtertype") + ]], + uniform string normal7_framerange = "" + [[ + materialx::core::origin("NG_CastleWhite/normal7/framerange") + ]], + uniform int normal7_frameoffset = 0 + [[ + materialx::core::origin("NG_CastleWhite/normal7/frameoffset") + ]], + uniform mx_addressmode_type normal7_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_CastleWhite/normal7/frameendaction") + ]], + float mtlxnormalmap9_scale = 1.000000 + [[ + materialx::core::origin("NG_CastleWhite/mtlxnormalmap9/scale") + ]], + float Castle_W_base = 1.000000 + [[ + materialx::core::origin("Castle_W/base") + ]], + float Castle_W_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Castle_W/diffuse_roughness") + ]], + float Castle_W_specular = 1.000000 + [[ + materialx::core::origin("Castle_W/specular") + ]], + color Castle_W_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Castle_W/specular_color") + ]], + uniform float Castle_W_specular_IOR = 1.500000 + [[ + materialx::core::origin("Castle_W/specular_IOR") + ]], + float Castle_W_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Castle_W/specular_anisotropy") + ]], + float Castle_W_specular_rotation = 0.000000 + [[ + materialx::core::origin("Castle_W/specular_rotation") + ]], + float Castle_W_transmission = 0.000000 + [[ + materialx::core::origin("Castle_W/transmission") + ]], + color Castle_W_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Castle_W/transmission_color") + ]], + float Castle_W_transmission_depth = 0.000000 + [[ + materialx::core::origin("Castle_W/transmission_depth") + ]], + color Castle_W_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Castle_W/transmission_scatter") + ]], + float Castle_W_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Castle_W/transmission_scatter_anisotropy") + ]], + float Castle_W_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Castle_W/transmission_dispersion") + ]], + float Castle_W_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Castle_W/transmission_extra_roughness") + ]], + float Castle_W_subsurface = 0.000000 + [[ + materialx::core::origin("Castle_W/subsurface") + ]], + float Castle_W_subsurface_scale = 0.003000 + [[ + materialx::core::origin("Castle_W/subsurface_scale") + ]], + float Castle_W_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Castle_W/subsurface_anisotropy") + ]], + float Castle_W_sheen = 0.000000 + [[ + materialx::core::origin("Castle_W/sheen") + ]], + color Castle_W_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Castle_W/sheen_color") + ]], + float Castle_W_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Castle_W/sheen_roughness") + ]], + float Castle_W_coat = 0.000000 + [[ + materialx::core::origin("Castle_W/coat") + ]], + color Castle_W_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Castle_W/coat_color") + ]], + float Castle_W_coat_roughness = 0.100000 + [[ + materialx::core::origin("Castle_W/coat_roughness") + ]], + float Castle_W_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Castle_W/coat_anisotropy") + ]], + float Castle_W_coat_rotation = 0.000000 + [[ + materialx::core::origin("Castle_W/coat_rotation") + ]], + uniform float Castle_W_coat_IOR = 1.500000 + [[ + materialx::core::origin("Castle_W/coat_IOR") + ]], + float Castle_W_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Castle_W/coat_affect_color") + ]], + float Castle_W_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Castle_W/coat_affect_roughness") + ]], + float Castle_W_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Castle_W/thin_film_thickness") + ]], + float Castle_W_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Castle_W/thin_film_IOR") + ]], + float Castle_W_emission = 0.000000 + [[ + materialx::core::origin("Castle_W/emission") + ]], + color Castle_W_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Castle_W/emission_color") + ]], + color Castle_W_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Castle_W/opacity") + ]], + bool Castle_W_thin_walled = false + [[ + materialx::core::origin("Castle_W/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color diffuse7_out = materialx::stdlib_1_8::mx_image_color3(diffuse7_file, diffuse7_layer, diffuse7_default, geomprop_UV0_out1, diffuse7_uaddressmode, diffuse7_vaddressmode, diffuse7_filtertype, diffuse7_framerange, diffuse7_frameoffset, diffuse7_frameendaction, mxp_flip_v:false); + float metallic7_out = materialx::stdlib_1_8::mx_image_float(metallic7_file, metallic7_layer, metallic7_default, geomprop_UV0_out1, metallic7_uaddressmode, metallic7_vaddressmode, metallic7_filtertype, metallic7_framerange, metallic7_frameoffset, metallic7_frameendaction, mxp_flip_v:false); + float roughness7_out = materialx::stdlib_1_8::mx_image_float(roughness7_file, roughness7_layer, roughness7_default, geomprop_UV0_out1, roughness7_uaddressmode, roughness7_vaddressmode, roughness7_filtertype, roughness7_framerange, roughness7_frameoffset, roughness7_frameendaction, mxp_flip_v:false); + float3 normal7_out = materialx::stdlib_1_8::mx_image_vector3(normal7_file, normal7_layer, normal7_default, geomprop_UV0_out1, normal7_uaddressmode, normal7_vaddressmode, normal7_filtertype, normal7_framerange, normal7_frameoffset, normal7_frameendaction, mxp_flip_v:false); + color diffuse7_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(diffuse7_out); + float3 mtlxnormalmap9_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:normal7_out, mxp_scale:mtlxnormalmap9_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Castle_W_out = NG_standard_surface_surfaceshader_100(Castle_W_base, diffuse7_out_cm_out, Castle_W_diffuse_roughness, metallic7_out, Castle_W_specular, Castle_W_specular_color, roughness7_out, Castle_W_specular_IOR, Castle_W_specular_anisotropy, Castle_W_specular_rotation, Castle_W_transmission, Castle_W_transmission_color, Castle_W_transmission_depth, Castle_W_transmission_scatter, Castle_W_transmission_scatter_anisotropy, Castle_W_transmission_dispersion, Castle_W_transmission_extra_roughness, Castle_W_subsurface, diffuse7_out_cm_out, diffuse7_out_cm_out, Castle_W_subsurface_scale, Castle_W_subsurface_anisotropy, Castle_W_sheen, Castle_W_sheen_color, Castle_W_sheen_roughness, Castle_W_coat, Castle_W_coat_color, Castle_W_coat_roughness, Castle_W_coat_anisotropy, Castle_W_coat_rotation, Castle_W_coat_IOR, geomprop_Nworld_out1, Castle_W_coat_affect_color, Castle_W_coat_affect_roughness, Castle_W_thin_film_thickness, Castle_W_thin_film_IOR, Castle_W_emission, Castle_W_emission_color, Castle_W_opacity, Castle_W_thin_walled, mtlxnormalmap9_out, geomprop_Tworld_out1); + material M_Castle_W_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Castle_W_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Castle_W_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Castle_W.msl.frag b/Materials/Examples/StandardSurface/M_Castle_W.msl.frag new file mode 100644 index 0000000000..0cc2fd1f4f --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Castle_W.msl.frag @@ -0,0 +1,2961 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int diffuse7_layer; + vec3 diffuse7_default; + int diffuse7_uaddressmode; + int diffuse7_vaddressmode; + int diffuse7_filtertype; + int diffuse7_framerange; + int diffuse7_frameoffset; + int diffuse7_frameendaction; + vec2 diffuse7_uv_scale; + vec2 diffuse7_uv_offset; + int metallic7_layer; + float metallic7_default; + int metallic7_uaddressmode; + int metallic7_vaddressmode; + int metallic7_filtertype; + int metallic7_framerange; + int metallic7_frameoffset; + int metallic7_frameendaction; + vec2 metallic7_uv_scale; + vec2 metallic7_uv_offset; + int roughness7_layer; + float roughness7_default; + int roughness7_uaddressmode; + int roughness7_vaddressmode; + int roughness7_filtertype; + int roughness7_framerange; + int roughness7_frameoffset; + int roughness7_frameendaction; + vec2 roughness7_uv_scale; + vec2 roughness7_uv_offset; + int normal7_layer; + vec3 normal7_default; + int normal7_uaddressmode; + int normal7_vaddressmode; + int normal7_filtertype; + int normal7_framerange; + int normal7_frameoffset; + int normal7_frameendaction; + vec2 normal7_uv_scale; + vec2 normal7_uv_offset; + float mtlxnormalmap9_scale; + float Castle_W_base; + float Castle_W_diffuse_roughness; + float Castle_W_specular; + vec3 Castle_W_specular_color; + float Castle_W_specular_IOR; + float Castle_W_specular_anisotropy; + float Castle_W_specular_rotation; + float Castle_W_transmission; + vec3 Castle_W_transmission_color; + float Castle_W_transmission_depth; + vec3 Castle_W_transmission_scatter; + float Castle_W_transmission_scatter_anisotropy; + float Castle_W_transmission_dispersion; + float Castle_W_transmission_extra_roughness; + float Castle_W_subsurface; + float Castle_W_subsurface_scale; + float Castle_W_subsurface_anisotropy; + float Castle_W_sheen; + vec3 Castle_W_sheen_color; + float Castle_W_sheen_roughness; + float Castle_W_coat; + vec3 Castle_W_coat_color; + float Castle_W_coat_roughness; + float Castle_W_coat_anisotropy; + float Castle_W_coat_rotation; + float Castle_W_coat_IOR; + float Castle_W_coat_affect_color; + float Castle_W_coat_affect_roughness; + float Castle_W_thin_film_thickness; + float Castle_W_thin_film_IOR; + float Castle_W_emission; + vec3 Castle_W_emission_color; + vec3 Castle_W_opacity; + bool Castle_W_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture diffuse7_file , int diffuse7_layer + + , vec3 diffuse7_default + + , int diffuse7_uaddressmode + + , int diffuse7_vaddressmode + + , int diffuse7_filtertype + + , int diffuse7_framerange + + , int diffuse7_frameoffset + + , int diffuse7_frameendaction + + , vec2 diffuse7_uv_scale + + , vec2 diffuse7_uv_offset + +, MetalTexture metallic7_file , int metallic7_layer + + , float metallic7_default + + , int metallic7_uaddressmode + + , int metallic7_vaddressmode + + , int metallic7_filtertype + + , int metallic7_framerange + + , int metallic7_frameoffset + + , int metallic7_frameendaction + + , vec2 metallic7_uv_scale + + , vec2 metallic7_uv_offset + +, MetalTexture roughness7_file , int roughness7_layer + + , float roughness7_default + + , int roughness7_uaddressmode + + , int roughness7_vaddressmode + + , int roughness7_filtertype + + , int roughness7_framerange + + , int roughness7_frameoffset + + , int roughness7_frameendaction + + , vec2 roughness7_uv_scale + + , vec2 roughness7_uv_offset + +, MetalTexture normal7_file , int normal7_layer + + , vec3 normal7_default + + , int normal7_uaddressmode + + , int normal7_vaddressmode + + , int normal7_filtertype + + , int normal7_framerange + + , int normal7_frameoffset + + , int normal7_frameendaction + + , vec2 normal7_uv_scale + + , vec2 normal7_uv_offset + + , float mtlxnormalmap9_scale + + , float Castle_W_base + + , float Castle_W_diffuse_roughness + + , float Castle_W_specular + + , vec3 Castle_W_specular_color + + , float Castle_W_specular_IOR + + , float Castle_W_specular_anisotropy + + , float Castle_W_specular_rotation + + , float Castle_W_transmission + + , vec3 Castle_W_transmission_color + + , float Castle_W_transmission_depth + + , vec3 Castle_W_transmission_scatter + + , float Castle_W_transmission_scatter_anisotropy + + , float Castle_W_transmission_dispersion + + , float Castle_W_transmission_extra_roughness + + , float Castle_W_subsurface + + , float Castle_W_subsurface_scale + + , float Castle_W_subsurface_anisotropy + + , float Castle_W_sheen + + , vec3 Castle_W_sheen_color + + , float Castle_W_sheen_roughness + + , float Castle_W_coat + + , vec3 Castle_W_coat_color + + , float Castle_W_coat_roughness + + , float Castle_W_coat_anisotropy + + , float Castle_W_coat_rotation + + , float Castle_W_coat_IOR + + , float Castle_W_coat_affect_color + + , float Castle_W_coat_affect_roughness + + , float Castle_W_thin_film_thickness + + , float Castle_W_thin_film_IOR + + , float Castle_W_emission + + , vec3 Castle_W_emission_color + + , vec3 Castle_W_opacity + + , bool Castle_W_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, diffuse7_file(diffuse7_file) + , diffuse7_layer(diffuse7_layer) + + , diffuse7_default(diffuse7_default) + + , diffuse7_uaddressmode(diffuse7_uaddressmode) + + , diffuse7_vaddressmode(diffuse7_vaddressmode) + + , diffuse7_filtertype(diffuse7_filtertype) + + , diffuse7_framerange(diffuse7_framerange) + + , diffuse7_frameoffset(diffuse7_frameoffset) + + , diffuse7_frameendaction(diffuse7_frameendaction) + + , diffuse7_uv_scale(diffuse7_uv_scale) + + , diffuse7_uv_offset(diffuse7_uv_offset) + +, metallic7_file(metallic7_file) + , metallic7_layer(metallic7_layer) + + , metallic7_default(metallic7_default) + + , metallic7_uaddressmode(metallic7_uaddressmode) + + , metallic7_vaddressmode(metallic7_vaddressmode) + + , metallic7_filtertype(metallic7_filtertype) + + , metallic7_framerange(metallic7_framerange) + + , metallic7_frameoffset(metallic7_frameoffset) + + , metallic7_frameendaction(metallic7_frameendaction) + + , metallic7_uv_scale(metallic7_uv_scale) + + , metallic7_uv_offset(metallic7_uv_offset) + +, roughness7_file(roughness7_file) + , roughness7_layer(roughness7_layer) + + , roughness7_default(roughness7_default) + + , roughness7_uaddressmode(roughness7_uaddressmode) + + , roughness7_vaddressmode(roughness7_vaddressmode) + + , roughness7_filtertype(roughness7_filtertype) + + , roughness7_framerange(roughness7_framerange) + + , roughness7_frameoffset(roughness7_frameoffset) + + , roughness7_frameendaction(roughness7_frameendaction) + + , roughness7_uv_scale(roughness7_uv_scale) + + , roughness7_uv_offset(roughness7_uv_offset) + +, normal7_file(normal7_file) + , normal7_layer(normal7_layer) + + , normal7_default(normal7_default) + + , normal7_uaddressmode(normal7_uaddressmode) + + , normal7_vaddressmode(normal7_vaddressmode) + + , normal7_filtertype(normal7_filtertype) + + , normal7_framerange(normal7_framerange) + + , normal7_frameoffset(normal7_frameoffset) + + , normal7_frameendaction(normal7_frameendaction) + + , normal7_uv_scale(normal7_uv_scale) + + , normal7_uv_offset(normal7_uv_offset) + + , mtlxnormalmap9_scale(mtlxnormalmap9_scale) + + , Castle_W_base(Castle_W_base) + + , Castle_W_diffuse_roughness(Castle_W_diffuse_roughness) + + , Castle_W_specular(Castle_W_specular) + + , Castle_W_specular_color(Castle_W_specular_color) + + , Castle_W_specular_IOR(Castle_W_specular_IOR) + + , Castle_W_specular_anisotropy(Castle_W_specular_anisotropy) + + , Castle_W_specular_rotation(Castle_W_specular_rotation) + + , Castle_W_transmission(Castle_W_transmission) + + , Castle_W_transmission_color(Castle_W_transmission_color) + + , Castle_W_transmission_depth(Castle_W_transmission_depth) + + , Castle_W_transmission_scatter(Castle_W_transmission_scatter) + + , Castle_W_transmission_scatter_anisotropy(Castle_W_transmission_scatter_anisotropy) + + , Castle_W_transmission_dispersion(Castle_W_transmission_dispersion) + + , Castle_W_transmission_extra_roughness(Castle_W_transmission_extra_roughness) + + , Castle_W_subsurface(Castle_W_subsurface) + + , Castle_W_subsurface_scale(Castle_W_subsurface_scale) + + , Castle_W_subsurface_anisotropy(Castle_W_subsurface_anisotropy) + + , Castle_W_sheen(Castle_W_sheen) + + , Castle_W_sheen_color(Castle_W_sheen_color) + + , Castle_W_sheen_roughness(Castle_W_sheen_roughness) + + , Castle_W_coat(Castle_W_coat) + + , Castle_W_coat_color(Castle_W_coat_color) + + , Castle_W_coat_roughness(Castle_W_coat_roughness) + + , Castle_W_coat_anisotropy(Castle_W_coat_anisotropy) + + , Castle_W_coat_rotation(Castle_W_coat_rotation) + + , Castle_W_coat_IOR(Castle_W_coat_IOR) + + , Castle_W_coat_affect_color(Castle_W_coat_affect_color) + + , Castle_W_coat_affect_roughness(Castle_W_coat_affect_roughness) + + , Castle_W_thin_film_thickness(Castle_W_thin_film_thickness) + + , Castle_W_thin_film_IOR(Castle_W_thin_film_IOR) + + , Castle_W_emission(Castle_W_emission) + + , Castle_W_emission_color(Castle_W_emission_color) + + , Castle_W_opacity(Castle_W_opacity) + + , Castle_W_thin_walled(Castle_W_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture diffuse7_file; + int diffuse7_layer; + + + vec3 diffuse7_default; + + + int diffuse7_uaddressmode; + + + int diffuse7_vaddressmode; + + + int diffuse7_filtertype; + + + int diffuse7_framerange; + + + int diffuse7_frameoffset; + + + int diffuse7_frameendaction; + + + vec2 diffuse7_uv_scale; + + + vec2 diffuse7_uv_offset; + + +MetalTexture metallic7_file; + int metallic7_layer; + + + float metallic7_default; + + + int metallic7_uaddressmode; + + + int metallic7_vaddressmode; + + + int metallic7_filtertype; + + + int metallic7_framerange; + + + int metallic7_frameoffset; + + + int metallic7_frameendaction; + + + vec2 metallic7_uv_scale; + + + vec2 metallic7_uv_offset; + + +MetalTexture roughness7_file; + int roughness7_layer; + + + float roughness7_default; + + + int roughness7_uaddressmode; + + + int roughness7_vaddressmode; + + + int roughness7_filtertype; + + + int roughness7_framerange; + + + int roughness7_frameoffset; + + + int roughness7_frameendaction; + + + vec2 roughness7_uv_scale; + + + vec2 roughness7_uv_offset; + + +MetalTexture normal7_file; + int normal7_layer; + + + vec3 normal7_default; + + + int normal7_uaddressmode; + + + int normal7_vaddressmode; + + + int normal7_filtertype; + + + int normal7_framerange; + + + int normal7_frameoffset; + + + int normal7_frameendaction; + + + vec2 normal7_uv_scale; + + + vec2 normal7_uv_offset; + + + float mtlxnormalmap9_scale; + + + float Castle_W_base; + + + float Castle_W_diffuse_roughness; + + + float Castle_W_specular; + + + vec3 Castle_W_specular_color; + + + float Castle_W_specular_IOR; + + + float Castle_W_specular_anisotropy; + + + float Castle_W_specular_rotation; + + + float Castle_W_transmission; + + + vec3 Castle_W_transmission_color; + + + float Castle_W_transmission_depth; + + + vec3 Castle_W_transmission_scatter; + + + float Castle_W_transmission_scatter_anisotropy; + + + float Castle_W_transmission_dispersion; + + + float Castle_W_transmission_extra_roughness; + + + float Castle_W_subsurface; + + + float Castle_W_subsurface_scale; + + + float Castle_W_subsurface_anisotropy; + + + float Castle_W_sheen; + + + vec3 Castle_W_sheen_color; + + + float Castle_W_sheen_roughness; + + + float Castle_W_coat; + + + vec3 Castle_W_coat_color; + + + float Castle_W_coat_roughness; + + + float Castle_W_coat_anisotropy; + + + float Castle_W_coat_rotation; + + + float Castle_W_coat_IOR; + + + float Castle_W_coat_affect_color; + + + float Castle_W_coat_affect_roughness; + + + float Castle_W_thin_film_thickness; + + + float Castle_W_thin_film_IOR; + + + float Castle_W_emission; + + + vec3 Castle_W_emission_color; + + + vec3 Castle_W_opacity; + + + bool Castle_W_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse7_out = vec3(0.0); + mx_image_color3(diffuse7_file, diffuse7_layer, diffuse7_default, geomprop_UV0_out1, diffuse7_uaddressmode, diffuse7_vaddressmode, diffuse7_filtertype, diffuse7_framerange, diffuse7_frameoffset, diffuse7_frameendaction, diffuse7_uv_scale, diffuse7_uv_offset, diffuse7_out); + float metallic7_out = 0.0; + mx_image_float(metallic7_file, metallic7_layer, metallic7_default, geomprop_UV0_out1, metallic7_uaddressmode, metallic7_vaddressmode, metallic7_filtertype, metallic7_framerange, metallic7_frameoffset, metallic7_frameendaction, metallic7_uv_scale, metallic7_uv_offset, metallic7_out); + float roughness7_out = 0.0; + mx_image_float(roughness7_file, roughness7_layer, roughness7_default, geomprop_UV0_out1, roughness7_uaddressmode, roughness7_vaddressmode, roughness7_filtertype, roughness7_framerange, roughness7_frameoffset, roughness7_frameendaction, roughness7_uv_scale, roughness7_uv_offset, roughness7_out); + vec3 normal7_out = vec3(0.0); + mx_image_vector3(normal7_file, normal7_layer, normal7_default, geomprop_UV0_out1, normal7_uaddressmode, normal7_vaddressmode, normal7_filtertype, normal7_framerange, normal7_frameoffset, normal7_frameendaction, normal7_uv_scale, normal7_uv_offset, normal7_out); + vec3 diffuse7_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse7_out, diffuse7_out_cm_out); + vec3 mtlxnormalmap9_out = vec3(0.0); + mx_normalmap_float(normal7_out, mtlxnormalmap9_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap9_out); + surfaceshader Castle_W_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Castle_W_base, diffuse7_out_cm_out, Castle_W_diffuse_roughness, metallic7_out, Castle_W_specular, Castle_W_specular_color, roughness7_out, Castle_W_specular_IOR, Castle_W_specular_anisotropy, Castle_W_specular_rotation, Castle_W_transmission, Castle_W_transmission_color, Castle_W_transmission_depth, Castle_W_transmission_scatter, Castle_W_transmission_scatter_anisotropy, Castle_W_transmission_dispersion, Castle_W_transmission_extra_roughness, Castle_W_subsurface, diffuse7_out_cm_out, diffuse7_out_cm_out, Castle_W_subsurface_scale, Castle_W_subsurface_anisotropy, Castle_W_sheen, Castle_W_sheen_color, Castle_W_sheen_roughness, Castle_W_coat, Castle_W_coat_color, Castle_W_coat_roughness, Castle_W_coat_anisotropy, Castle_W_coat_rotation, Castle_W_coat_IOR, geomprop_Nworld_out1, Castle_W_coat_affect_color, Castle_W_coat_affect_roughness, Castle_W_thin_film_thickness, Castle_W_thin_film_IOR, Castle_W_emission, Castle_W_emission_color, Castle_W_opacity, Castle_W_thin_walled, mtlxnormalmap9_out, geomprop_Tworld_out1, Castle_W_out); + material M_Castle_W_out = Castle_W_out; + out1 = float4(M_Castle_W_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d diffuse7_file_tex [[texture(0)]], sampler diffuse7_file_sampler [[sampler(0)]] +, texture2d metallic7_file_tex [[texture(1)]], sampler metallic7_file_sampler [[sampler(1)]] +, texture2d roughness7_file_tex [[texture(2)]], sampler roughness7_file_sampler [[sampler(2)]] +, texture2d normal7_file_tex [[texture(3)]], sampler normal7_file_sampler [[sampler(3)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(4)]], sampler u_envRadiance_sampler [[sampler(4)]] +, texture2d u_envIrradiance_tex [[texture(5)]], sampler u_envIrradiance_sampler [[sampler(5)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +diffuse7_file_tex, diffuse7_file_sampler } + , u_pub.diffuse7_layer + , u_pub.diffuse7_default + , u_pub.diffuse7_uaddressmode + , u_pub.diffuse7_vaddressmode + , u_pub.diffuse7_filtertype + , u_pub.diffuse7_framerange + , u_pub.diffuse7_frameoffset + , u_pub.diffuse7_frameendaction + , u_pub.diffuse7_uv_scale + , u_pub.diffuse7_uv_offset +, MetalTexture { +metallic7_file_tex, metallic7_file_sampler } + , u_pub.metallic7_layer + , u_pub.metallic7_default + , u_pub.metallic7_uaddressmode + , u_pub.metallic7_vaddressmode + , u_pub.metallic7_filtertype + , u_pub.metallic7_framerange + , u_pub.metallic7_frameoffset + , u_pub.metallic7_frameendaction + , u_pub.metallic7_uv_scale + , u_pub.metallic7_uv_offset +, MetalTexture { +roughness7_file_tex, roughness7_file_sampler } + , u_pub.roughness7_layer + , u_pub.roughness7_default + , u_pub.roughness7_uaddressmode + , u_pub.roughness7_vaddressmode + , u_pub.roughness7_filtertype + , u_pub.roughness7_framerange + , u_pub.roughness7_frameoffset + , u_pub.roughness7_frameendaction + , u_pub.roughness7_uv_scale + , u_pub.roughness7_uv_offset +, MetalTexture { +normal7_file_tex, normal7_file_sampler } + , u_pub.normal7_layer + , u_pub.normal7_default + , u_pub.normal7_uaddressmode + , u_pub.normal7_vaddressmode + , u_pub.normal7_filtertype + , u_pub.normal7_framerange + , u_pub.normal7_frameoffset + , u_pub.normal7_frameendaction + , u_pub.normal7_uv_scale + , u_pub.normal7_uv_offset + , u_pub.mtlxnormalmap9_scale + , u_pub.Castle_W_base + , u_pub.Castle_W_diffuse_roughness + , u_pub.Castle_W_specular + , u_pub.Castle_W_specular_color + , u_pub.Castle_W_specular_IOR + , u_pub.Castle_W_specular_anisotropy + , u_pub.Castle_W_specular_rotation + , u_pub.Castle_W_transmission + , u_pub.Castle_W_transmission_color + , u_pub.Castle_W_transmission_depth + , u_pub.Castle_W_transmission_scatter + , u_pub.Castle_W_transmission_scatter_anisotropy + , u_pub.Castle_W_transmission_dispersion + , u_pub.Castle_W_transmission_extra_roughness + , u_pub.Castle_W_subsurface + , u_pub.Castle_W_subsurface_scale + , u_pub.Castle_W_subsurface_anisotropy + , u_pub.Castle_W_sheen + , u_pub.Castle_W_sheen_color + , u_pub.Castle_W_sheen_roughness + , u_pub.Castle_W_coat + , u_pub.Castle_W_coat_color + , u_pub.Castle_W_coat_roughness + , u_pub.Castle_W_coat_anisotropy + , u_pub.Castle_W_coat_rotation + , u_pub.Castle_W_coat_IOR + , u_pub.Castle_W_coat_affect_color + , u_pub.Castle_W_coat_affect_roughness + , u_pub.Castle_W_thin_film_thickness + , u_pub.Castle_W_thin_film_IOR + , u_pub.Castle_W_emission + , u_pub.Castle_W_emission_color + , u_pub.Castle_W_opacity + , u_pub.Castle_W_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Castle_W.msl.vert b/Materials/Examples/StandardSurface/M_Castle_W.msl.vert new file mode 100644 index 0000000000..3fbbf72cca --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Castle_W.msl.vert @@ -0,0 +1,127 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'diffuse7'. Function already called in this scope. + // Omitted node 'metallic7'. Function already called in this scope. + // Omitted node 'roughness7'. Function already called in this scope. + // Omitted node 'normal7'. Function already called in this scope. + // Omitted node 'diffuse7_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap9'. Function already called in this scope. + // Omitted node 'Castle_W'. Function already called in this scope. + // Omitted node 'M_Castle_W'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Castle_W.osl b/Materials/Examples/StandardSurface/M_Castle_W.osl new file mode 100644 index 0000000000..e9b58773a7 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Castle_W.osl @@ -0,0 +1,678 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Castle_W +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Castle_W" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string diffuse7_file = "chess_set/castle_white_base_color.jpg" + [[ + string widget = "filename" + ]], + string diffuse7_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string diffuse7_layer = "", + color diffuse7_default = color(0.000000, 0.000000, 0.000000), + string diffuse7_uaddressmode = "periodic", + string diffuse7_vaddressmode = "periodic", + string diffuse7_filtertype = "linear", + string diffuse7_framerange = "", + int diffuse7_frameoffset = 0 + [[ + string widget = "number" + ]], + string diffuse7_frameendaction = "constant", + string metallic7_file = "chess_set/castle_shared_metallic.jpg" + [[ + string widget = "filename" + ]], + string metallic7_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string metallic7_layer = "", + float metallic7_default = 0.000000 + [[ + string widget = "number" + ]], + string metallic7_uaddressmode = "periodic", + string metallic7_vaddressmode = "periodic", + string metallic7_filtertype = "linear", + string metallic7_framerange = "", + int metallic7_frameoffset = 0 + [[ + string widget = "number" + ]], + string metallic7_frameendaction = "constant", + string roughness7_file = "chess_set/castle_shared_roughness.jpg" + [[ + string widget = "filename" + ]], + string roughness7_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string roughness7_layer = "", + float roughness7_default = 0.000000 + [[ + string widget = "number" + ]], + string roughness7_uaddressmode = "periodic", + string roughness7_vaddressmode = "periodic", + string roughness7_filtertype = "linear", + string roughness7_framerange = "", + int roughness7_frameoffset = 0 + [[ + string widget = "number" + ]], + string roughness7_frameendaction = "constant", + string normal7_file = "chess_set/castle_shared_normal.jpg" + [[ + string widget = "filename" + ]], + string normal7_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string normal7_layer = "", + vector normal7_default = vector(0.000000, 0.000000, 0.000000), + string normal7_uaddressmode = "periodic", + string normal7_vaddressmode = "periodic", + string normal7_filtertype = "linear", + string normal7_framerange = "", + int normal7_frameoffset = 0 + [[ + string widget = "number" + ]], + string normal7_frameendaction = "constant", + float mtlxnormalmap9_scale = 1.000000 + [[ + string widget = "number" + ]], + float Castle_W_base = 1.000000 + [[ + string widget = "number" + ]], + float Castle_W_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_specular = 1.000000 + [[ + string widget = "number" + ]], + color Castle_W_specular_color = color(1.000000, 1.000000, 1.000000), + float Castle_W_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Castle_W_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_transmission = 0.000000 + [[ + string widget = "number" + ]], + color Castle_W_transmission_color = color(1.000000, 1.000000, 1.000000), + float Castle_W_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Castle_W_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Castle_W_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_subsurface = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float Castle_W_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Castle_W_sheen_color = color(1.000000, 1.000000, 1.000000), + float Castle_W_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Castle_W_coat = 0.000000 + [[ + string widget = "number" + ]], + color Castle_W_coat_color = color(1.000000, 1.000000, 1.000000), + float Castle_W_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Castle_W_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Castle_W_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Castle_W_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Castle_W_emission = 0.000000 + [[ + string widget = "number" + ]], + color Castle_W_emission_color = color(1.000000, 1.000000, 1.000000), + color Castle_W_opacity = color(1.000000, 1.000000, 1.000000), + int Castle_W_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource diffuse7_file_ = {diffuse7_file, diffuse7_file_colorspace}; + textureresource metallic7_file_ = {metallic7_file, metallic7_file_colorspace}; + textureresource roughness7_file_ = {roughness7_file, roughness7_file_colorspace}; + textureresource normal7_file_ = {normal7_file, normal7_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color diffuse7_out = color(0.0); + mx_image_color3(diffuse7_file_, diffuse7_layer, diffuse7_default, geomprop_UV0_out1, diffuse7_uaddressmode, diffuse7_vaddressmode, diffuse7_filtertype, diffuse7_framerange, diffuse7_frameoffset, diffuse7_frameendaction, diffuse7_out); + float metallic7_out = 0.0; + mx_image_float(metallic7_file_, metallic7_layer, metallic7_default, geomprop_UV0_out1, metallic7_uaddressmode, metallic7_vaddressmode, metallic7_filtertype, metallic7_framerange, metallic7_frameoffset, metallic7_frameendaction, metallic7_out); + float roughness7_out = 0.0; + mx_image_float(roughness7_file_, roughness7_layer, roughness7_default, geomprop_UV0_out1, roughness7_uaddressmode, roughness7_vaddressmode, roughness7_filtertype, roughness7_framerange, roughness7_frameoffset, roughness7_frameendaction, roughness7_out); + vector normal7_out = vector(0.0); + mx_image_vector3(normal7_file_, normal7_layer, normal7_default, geomprop_UV0_out1, normal7_uaddressmode, normal7_vaddressmode, normal7_filtertype, normal7_framerange, normal7_frameoffset, normal7_frameendaction, normal7_out); + color diffuse7_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse7_out, diffuse7_out_cm_out); + vector mtlxnormalmap9_out = vector(0.0); + mx_normalmap_float(normal7_out, mtlxnormalmap9_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap9_out); + surfaceshader Castle_W_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Castle_W_base, diffuse7_out_cm_out, Castle_W_diffuse_roughness, metallic7_out, Castle_W_specular, Castle_W_specular_color, roughness7_out, Castle_W_specular_IOR, Castle_W_specular_anisotropy, Castle_W_specular_rotation, Castle_W_transmission, Castle_W_transmission_color, Castle_W_transmission_depth, Castle_W_transmission_scatter, Castle_W_transmission_scatter_anisotropy, Castle_W_transmission_dispersion, Castle_W_transmission_extra_roughness, Castle_W_subsurface, diffuse7_out_cm_out, diffuse7_out_cm_out, Castle_W_subsurface_scale, Castle_W_subsurface_anisotropy, Castle_W_sheen, Castle_W_sheen_color, Castle_W_sheen_roughness, Castle_W_coat, Castle_W_coat_color, Castle_W_coat_roughness, Castle_W_coat_anisotropy, Castle_W_coat_rotation, Castle_W_coat_IOR, geomprop_Nworld_out1, Castle_W_coat_affect_color, Castle_W_coat_affect_roughness, Castle_W_thin_film_thickness, Castle_W_thin_film_IOR, Castle_W_emission, Castle_W_emission_color, Castle_W_opacity, Castle_W_thin_walled, mtlxnormalmap9_out, geomprop_Tworld_out1, Castle_W_out); + MATERIAL M_Castle_W_out = mx_surfacematerial(Castle_W_out, backsurfaceshader, displacementshader1); + out = M_Castle_W_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Chessboard.glsl.frag b/Materials/Examples/StandardSurface/M_Chessboard.glsl.frag new file mode 100644 index 0000000000..a9d00b4696 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Chessboard.glsl.frag @@ -0,0 +1,2013 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D mtlximage13_file; +uniform int mtlximage13_layer = 0; +uniform vec3 mtlximage13_default = vec3(0.000000, 0.000000, 0.000000); +uniform int mtlximage13_uaddressmode = 2; +uniform int mtlximage13_vaddressmode = 2; +uniform int mtlximage13_filtertype = 1; +uniform int mtlximage13_framerange = 0; +uniform int mtlximage13_frameoffset = 0; +uniform int mtlximage13_frameendaction = 0; +uniform vec2 mtlximage13_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage13_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage16_file; +uniform int mtlximage16_layer = 0; +uniform float mtlximage16_default = 0.000000; +uniform int mtlximage16_uaddressmode = 2; +uniform int mtlximage16_vaddressmode = 2; +uniform int mtlximage16_filtertype = 1; +uniform int mtlximage16_framerange = 0; +uniform int mtlximage16_frameoffset = 0; +uniform int mtlximage16_frameendaction = 0; +uniform vec2 mtlximage16_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage16_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage17_file; +uniform int mtlximage17_layer = 0; +uniform float mtlximage17_default = 0.000000; +uniform int mtlximage17_uaddressmode = 2; +uniform int mtlximage17_vaddressmode = 2; +uniform int mtlximage17_filtertype = 1; +uniform int mtlximage17_framerange = 0; +uniform int mtlximage17_frameoffset = 0; +uniform int mtlximage17_frameendaction = 0; +uniform vec2 mtlximage17_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage17_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage15_file; +uniform int mtlximage15_layer = 0; +uniform vec3 mtlximage15_default = vec3(0.000000, 0.000000, 0.000000); +uniform int mtlximage15_uaddressmode = 2; +uniform int mtlximage15_vaddressmode = 2; +uniform int mtlximage15_filtertype = 1; +uniform int mtlximage15_framerange = 0; +uniform int mtlximage15_frameoffset = 0; +uniform int mtlximage15_frameendaction = 0; +uniform vec2 mtlximage15_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage15_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap12_scale = 1.000000; +uniform float Chessboard_base = 1.000000; +uniform float Chessboard_diffuse_roughness = 0.000000; +uniform float Chessboard_specular = 1.000000; +uniform vec3 Chessboard_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Chessboard_specular_IOR = 1.500000; +uniform float Chessboard_specular_anisotropy = 0.000000; +uniform float Chessboard_specular_rotation = 0.000000; +uniform float Chessboard_transmission = 0.000000; +uniform vec3 Chessboard_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Chessboard_transmission_depth = 0.000000; +uniform vec3 Chessboard_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Chessboard_transmission_scatter_anisotropy = 0.000000; +uniform float Chessboard_transmission_dispersion = 0.000000; +uniform float Chessboard_transmission_extra_roughness = 0.000000; +uniform float Chessboard_subsurface = 0.000000; +uniform float Chessboard_subsurface_scale = 0.003000; +uniform float Chessboard_subsurface_anisotropy = 0.000000; +uniform float Chessboard_sheen = 0.000000; +uniform vec3 Chessboard_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Chessboard_sheen_roughness = 0.300000; +uniform float Chessboard_coat = 0.000000; +uniform vec3 Chessboard_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Chessboard_coat_roughness = 0.100000; +uniform float Chessboard_coat_anisotropy = 0.000000; +uniform float Chessboard_coat_rotation = 0.000000; +uniform float Chessboard_coat_IOR = 1.500000; +uniform float Chessboard_coat_affect_color = 0.000000; +uniform float Chessboard_coat_affect_roughness = 0.000000; +uniform float Chessboard_thin_film_thickness = 0.000000; +uniform float Chessboard_thin_film_IOR = 1.500000; +uniform float Chessboard_emission = 0.000000; +uniform vec3 Chessboard_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Chessboard_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Chessboard_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 mtlximage13_out = vec3(0.0); + mx_image_color3(mtlximage13_file, mtlximage13_layer, mtlximage13_default, geomprop_UV0_out1, mtlximage13_uaddressmode, mtlximage13_vaddressmode, mtlximage13_filtertype, mtlximage13_framerange, mtlximage13_frameoffset, mtlximage13_frameendaction, mtlximage13_uv_scale, mtlximage13_uv_offset, mtlximage13_out); + float mtlximage16_out = 0.0; + mx_image_float(mtlximage16_file, mtlximage16_layer, mtlximage16_default, geomprop_UV0_out1, mtlximage16_uaddressmode, mtlximage16_vaddressmode, mtlximage16_filtertype, mtlximage16_framerange, mtlximage16_frameoffset, mtlximage16_frameendaction, mtlximage16_uv_scale, mtlximage16_uv_offset, mtlximage16_out); + float mtlximage17_out = 0.0; + mx_image_float(mtlximage17_file, mtlximage17_layer, mtlximage17_default, geomprop_UV0_out1, mtlximage17_uaddressmode, mtlximage17_vaddressmode, mtlximage17_filtertype, mtlximage17_framerange, mtlximage17_frameoffset, mtlximage17_frameendaction, mtlximage17_uv_scale, mtlximage17_uv_offset, mtlximage17_out); + vec3 mtlximage15_out = vec3(0.0); + mx_image_vector3(mtlximage15_file, mtlximage15_layer, mtlximage15_default, geomprop_UV0_out1, mtlximage15_uaddressmode, mtlximage15_vaddressmode, mtlximage15_filtertype, mtlximage15_framerange, mtlximage15_frameoffset, mtlximage15_frameendaction, mtlximage15_uv_scale, mtlximage15_uv_offset, mtlximage15_out); + vec3 mtlximage13_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(mtlximage13_out, mtlximage13_out_cm_out); + vec3 mtlxnormalmap12_out = vec3(0.0); + mx_normalmap_float(mtlximage15_out, mtlxnormalmap12_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap12_out); + surfaceshader Chessboard_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Chessboard_base, mtlximage13_out_cm_out, Chessboard_diffuse_roughness, mtlximage16_out, Chessboard_specular, Chessboard_specular_color, mtlximage17_out, Chessboard_specular_IOR, Chessboard_specular_anisotropy, Chessboard_specular_rotation, Chessboard_transmission, Chessboard_transmission_color, Chessboard_transmission_depth, Chessboard_transmission_scatter, Chessboard_transmission_scatter_anisotropy, Chessboard_transmission_dispersion, Chessboard_transmission_extra_roughness, Chessboard_subsurface, mtlximage13_out_cm_out, mtlximage13_out_cm_out, Chessboard_subsurface_scale, Chessboard_subsurface_anisotropy, Chessboard_sheen, Chessboard_sheen_color, Chessboard_sheen_roughness, Chessboard_coat, Chessboard_coat_color, Chessboard_coat_roughness, Chessboard_coat_anisotropy, Chessboard_coat_rotation, Chessboard_coat_IOR, geomprop_Nworld_out1, Chessboard_coat_affect_color, Chessboard_coat_affect_roughness, Chessboard_thin_film_thickness, Chessboard_thin_film_IOR, Chessboard_emission, Chessboard_emission_color, Chessboard_opacity, Chessboard_thin_walled, mtlxnormalmap12_out, geomprop_Tworld_out1, Chessboard_out); + material M_Chessboard_out = Chessboard_out; + out1 = vec4(M_Chessboard_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Chessboard.glsl.vert b/Materials/Examples/StandardSurface/M_Chessboard.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Chessboard.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Chessboard.mdl b/Materials/Examples/StandardSurface/M_Chessboard.mdl new file mode 100644 index 0000000000..19aa5f631e --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Chessboard.mdl @@ -0,0 +1,506 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Chessboard +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d mtlximage13_file = texture_2d("/chess_set/chessboard_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_ChessBoard/mtlximage13/file") + ]], + uniform string mtlximage13_layer = "" + [[ + materialx::core::origin("NG_ChessBoard/mtlximage13/layer") + ]], + color mtlximage13_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_ChessBoard/mtlximage13/default") + ]], + uniform mx_addressmode_type mtlximage13_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_ChessBoard/mtlximage13/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage13_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_ChessBoard/mtlximage13/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage13_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_ChessBoard/mtlximage13/filtertype") + ]], + uniform string mtlximage13_framerange = "" + [[ + materialx::core::origin("NG_ChessBoard/mtlximage13/framerange") + ]], + uniform int mtlximage13_frameoffset = 0 + [[ + materialx::core::origin("NG_ChessBoard/mtlximage13/frameoffset") + ]], + uniform mx_addressmode_type mtlximage13_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_ChessBoard/mtlximage13/frameendaction") + ]], + uniform texture_2d mtlximage16_file = texture_2d("/chess_set/chessboard_metallic.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_ChessBoard/mtlximage16/file") + ]], + uniform string mtlximage16_layer = "" + [[ + materialx::core::origin("NG_ChessBoard/mtlximage16/layer") + ]], + float mtlximage16_default = 0.000000 + [[ + materialx::core::origin("NG_ChessBoard/mtlximage16/default") + ]], + uniform mx_addressmode_type mtlximage16_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_ChessBoard/mtlximage16/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage16_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_ChessBoard/mtlximage16/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage16_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_ChessBoard/mtlximage16/filtertype") + ]], + uniform string mtlximage16_framerange = "" + [[ + materialx::core::origin("NG_ChessBoard/mtlximage16/framerange") + ]], + uniform int mtlximage16_frameoffset = 0 + [[ + materialx::core::origin("NG_ChessBoard/mtlximage16/frameoffset") + ]], + uniform mx_addressmode_type mtlximage16_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_ChessBoard/mtlximage16/frameendaction") + ]], + uniform texture_2d mtlximage17_file = texture_2d("/chess_set/chessboard_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_ChessBoard/mtlximage17/file") + ]], + uniform string mtlximage17_layer = "" + [[ + materialx::core::origin("NG_ChessBoard/mtlximage17/layer") + ]], + float mtlximage17_default = 0.000000 + [[ + materialx::core::origin("NG_ChessBoard/mtlximage17/default") + ]], + uniform mx_addressmode_type mtlximage17_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_ChessBoard/mtlximage17/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage17_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_ChessBoard/mtlximage17/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage17_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_ChessBoard/mtlximage17/filtertype") + ]], + uniform string mtlximage17_framerange = "" + [[ + materialx::core::origin("NG_ChessBoard/mtlximage17/framerange") + ]], + uniform int mtlximage17_frameoffset = 0 + [[ + materialx::core::origin("NG_ChessBoard/mtlximage17/frameoffset") + ]], + uniform mx_addressmode_type mtlximage17_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_ChessBoard/mtlximage17/frameendaction") + ]], + uniform texture_2d mtlximage15_file = texture_2d("/chess_set/chessboard_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_ChessBoard/mtlximage15/file") + ]], + uniform string mtlximage15_layer = "" + [[ + materialx::core::origin("NG_ChessBoard/mtlximage15/layer") + ]], + float3 mtlximage15_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_ChessBoard/mtlximage15/default") + ]], + uniform mx_addressmode_type mtlximage15_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_ChessBoard/mtlximage15/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage15_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_ChessBoard/mtlximage15/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage15_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_ChessBoard/mtlximage15/filtertype") + ]], + uniform string mtlximage15_framerange = "" + [[ + materialx::core::origin("NG_ChessBoard/mtlximage15/framerange") + ]], + uniform int mtlximage15_frameoffset = 0 + [[ + materialx::core::origin("NG_ChessBoard/mtlximage15/frameoffset") + ]], + uniform mx_addressmode_type mtlximage15_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_ChessBoard/mtlximage15/frameendaction") + ]], + float mtlxnormalmap12_scale = 1.000000 + [[ + materialx::core::origin("NG_ChessBoard/mtlxnormalmap12/scale") + ]], + float Chessboard_base = 1.000000 + [[ + materialx::core::origin("Chessboard/base") + ]], + float Chessboard_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Chessboard/diffuse_roughness") + ]], + float Chessboard_specular = 1.000000 + [[ + materialx::core::origin("Chessboard/specular") + ]], + color Chessboard_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Chessboard/specular_color") + ]], + uniform float Chessboard_specular_IOR = 1.500000 + [[ + materialx::core::origin("Chessboard/specular_IOR") + ]], + float Chessboard_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Chessboard/specular_anisotropy") + ]], + float Chessboard_specular_rotation = 0.000000 + [[ + materialx::core::origin("Chessboard/specular_rotation") + ]], + float Chessboard_transmission = 0.000000 + [[ + materialx::core::origin("Chessboard/transmission") + ]], + color Chessboard_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Chessboard/transmission_color") + ]], + float Chessboard_transmission_depth = 0.000000 + [[ + materialx::core::origin("Chessboard/transmission_depth") + ]], + color Chessboard_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Chessboard/transmission_scatter") + ]], + float Chessboard_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Chessboard/transmission_scatter_anisotropy") + ]], + float Chessboard_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Chessboard/transmission_dispersion") + ]], + float Chessboard_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Chessboard/transmission_extra_roughness") + ]], + float Chessboard_subsurface = 0.000000 + [[ + materialx::core::origin("Chessboard/subsurface") + ]], + float Chessboard_subsurface_scale = 0.003000 + [[ + materialx::core::origin("Chessboard/subsurface_scale") + ]], + float Chessboard_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Chessboard/subsurface_anisotropy") + ]], + float Chessboard_sheen = 0.000000 + [[ + materialx::core::origin("Chessboard/sheen") + ]], + color Chessboard_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Chessboard/sheen_color") + ]], + float Chessboard_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Chessboard/sheen_roughness") + ]], + float Chessboard_coat = 0.000000 + [[ + materialx::core::origin("Chessboard/coat") + ]], + color Chessboard_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Chessboard/coat_color") + ]], + float Chessboard_coat_roughness = 0.100000 + [[ + materialx::core::origin("Chessboard/coat_roughness") + ]], + float Chessboard_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Chessboard/coat_anisotropy") + ]], + float Chessboard_coat_rotation = 0.000000 + [[ + materialx::core::origin("Chessboard/coat_rotation") + ]], + uniform float Chessboard_coat_IOR = 1.500000 + [[ + materialx::core::origin("Chessboard/coat_IOR") + ]], + float Chessboard_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Chessboard/coat_affect_color") + ]], + float Chessboard_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Chessboard/coat_affect_roughness") + ]], + float Chessboard_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Chessboard/thin_film_thickness") + ]], + float Chessboard_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Chessboard/thin_film_IOR") + ]], + float Chessboard_emission = 0.000000 + [[ + materialx::core::origin("Chessboard/emission") + ]], + color Chessboard_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Chessboard/emission_color") + ]], + color Chessboard_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Chessboard/opacity") + ]], + bool Chessboard_thin_walled = false + [[ + materialx::core::origin("Chessboard/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color mtlximage13_out = materialx::stdlib_1_8::mx_image_color3(mtlximage13_file, mtlximage13_layer, mtlximage13_default, geomprop_UV0_out1, mtlximage13_uaddressmode, mtlximage13_vaddressmode, mtlximage13_filtertype, mtlximage13_framerange, mtlximage13_frameoffset, mtlximage13_frameendaction, mxp_flip_v:false); + float mtlximage16_out = materialx::stdlib_1_8::mx_image_float(mtlximage16_file, mtlximage16_layer, mtlximage16_default, geomprop_UV0_out1, mtlximage16_uaddressmode, mtlximage16_vaddressmode, mtlximage16_filtertype, mtlximage16_framerange, mtlximage16_frameoffset, mtlximage16_frameendaction, mxp_flip_v:false); + float mtlximage17_out = materialx::stdlib_1_8::mx_image_float(mtlximage17_file, mtlximage17_layer, mtlximage17_default, geomprop_UV0_out1, mtlximage17_uaddressmode, mtlximage17_vaddressmode, mtlximage17_filtertype, mtlximage17_framerange, mtlximage17_frameoffset, mtlximage17_frameendaction, mxp_flip_v:false); + float3 mtlximage15_out = materialx::stdlib_1_8::mx_image_vector3(mtlximage15_file, mtlximage15_layer, mtlximage15_default, geomprop_UV0_out1, mtlximage15_uaddressmode, mtlximage15_vaddressmode, mtlximage15_filtertype, mtlximage15_framerange, mtlximage15_frameoffset, mtlximage15_frameendaction, mxp_flip_v:false); + color mtlximage13_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(mtlximage13_out); + float3 mtlxnormalmap12_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:mtlximage15_out, mxp_scale:mtlxnormalmap12_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Chessboard_out = NG_standard_surface_surfaceshader_100(Chessboard_base, mtlximage13_out_cm_out, Chessboard_diffuse_roughness, mtlximage16_out, Chessboard_specular, Chessboard_specular_color, mtlximage17_out, Chessboard_specular_IOR, Chessboard_specular_anisotropy, Chessboard_specular_rotation, Chessboard_transmission, Chessboard_transmission_color, Chessboard_transmission_depth, Chessboard_transmission_scatter, Chessboard_transmission_scatter_anisotropy, Chessboard_transmission_dispersion, Chessboard_transmission_extra_roughness, Chessboard_subsurface, mtlximage13_out_cm_out, mtlximage13_out_cm_out, Chessboard_subsurface_scale, Chessboard_subsurface_anisotropy, Chessboard_sheen, Chessboard_sheen_color, Chessboard_sheen_roughness, Chessboard_coat, Chessboard_coat_color, Chessboard_coat_roughness, Chessboard_coat_anisotropy, Chessboard_coat_rotation, Chessboard_coat_IOR, geomprop_Nworld_out1, Chessboard_coat_affect_color, Chessboard_coat_affect_roughness, Chessboard_thin_film_thickness, Chessboard_thin_film_IOR, Chessboard_emission, Chessboard_emission_color, Chessboard_opacity, Chessboard_thin_walled, mtlxnormalmap12_out, geomprop_Tworld_out1); + material M_Chessboard_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Chessboard_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Chessboard_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Chessboard.msl.frag b/Materials/Examples/StandardSurface/M_Chessboard.msl.frag new file mode 100644 index 0000000000..7aa7d90b2f --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Chessboard.msl.frag @@ -0,0 +1,2961 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int mtlximage13_layer; + vec3 mtlximage13_default; + int mtlximage13_uaddressmode; + int mtlximage13_vaddressmode; + int mtlximage13_filtertype; + int mtlximage13_framerange; + int mtlximage13_frameoffset; + int mtlximage13_frameendaction; + vec2 mtlximage13_uv_scale; + vec2 mtlximage13_uv_offset; + int mtlximage16_layer; + float mtlximage16_default; + int mtlximage16_uaddressmode; + int mtlximage16_vaddressmode; + int mtlximage16_filtertype; + int mtlximage16_framerange; + int mtlximage16_frameoffset; + int mtlximage16_frameendaction; + vec2 mtlximage16_uv_scale; + vec2 mtlximage16_uv_offset; + int mtlximage17_layer; + float mtlximage17_default; + int mtlximage17_uaddressmode; + int mtlximage17_vaddressmode; + int mtlximage17_filtertype; + int mtlximage17_framerange; + int mtlximage17_frameoffset; + int mtlximage17_frameendaction; + vec2 mtlximage17_uv_scale; + vec2 mtlximage17_uv_offset; + int mtlximage15_layer; + vec3 mtlximage15_default; + int mtlximage15_uaddressmode; + int mtlximage15_vaddressmode; + int mtlximage15_filtertype; + int mtlximage15_framerange; + int mtlximage15_frameoffset; + int mtlximage15_frameendaction; + vec2 mtlximage15_uv_scale; + vec2 mtlximage15_uv_offset; + float mtlxnormalmap12_scale; + float Chessboard_base; + float Chessboard_diffuse_roughness; + float Chessboard_specular; + vec3 Chessboard_specular_color; + float Chessboard_specular_IOR; + float Chessboard_specular_anisotropy; + float Chessboard_specular_rotation; + float Chessboard_transmission; + vec3 Chessboard_transmission_color; + float Chessboard_transmission_depth; + vec3 Chessboard_transmission_scatter; + float Chessboard_transmission_scatter_anisotropy; + float Chessboard_transmission_dispersion; + float Chessboard_transmission_extra_roughness; + float Chessboard_subsurface; + float Chessboard_subsurface_scale; + float Chessboard_subsurface_anisotropy; + float Chessboard_sheen; + vec3 Chessboard_sheen_color; + float Chessboard_sheen_roughness; + float Chessboard_coat; + vec3 Chessboard_coat_color; + float Chessboard_coat_roughness; + float Chessboard_coat_anisotropy; + float Chessboard_coat_rotation; + float Chessboard_coat_IOR; + float Chessboard_coat_affect_color; + float Chessboard_coat_affect_roughness; + float Chessboard_thin_film_thickness; + float Chessboard_thin_film_IOR; + float Chessboard_emission; + vec3 Chessboard_emission_color; + vec3 Chessboard_opacity; + bool Chessboard_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture mtlximage13_file , int mtlximage13_layer + + , vec3 mtlximage13_default + + , int mtlximage13_uaddressmode + + , int mtlximage13_vaddressmode + + , int mtlximage13_filtertype + + , int mtlximage13_framerange + + , int mtlximage13_frameoffset + + , int mtlximage13_frameendaction + + , vec2 mtlximage13_uv_scale + + , vec2 mtlximage13_uv_offset + +, MetalTexture mtlximage16_file , int mtlximage16_layer + + , float mtlximage16_default + + , int mtlximage16_uaddressmode + + , int mtlximage16_vaddressmode + + , int mtlximage16_filtertype + + , int mtlximage16_framerange + + , int mtlximage16_frameoffset + + , int mtlximage16_frameendaction + + , vec2 mtlximage16_uv_scale + + , vec2 mtlximage16_uv_offset + +, MetalTexture mtlximage17_file , int mtlximage17_layer + + , float mtlximage17_default + + , int mtlximage17_uaddressmode + + , int mtlximage17_vaddressmode + + , int mtlximage17_filtertype + + , int mtlximage17_framerange + + , int mtlximage17_frameoffset + + , int mtlximage17_frameendaction + + , vec2 mtlximage17_uv_scale + + , vec2 mtlximage17_uv_offset + +, MetalTexture mtlximage15_file , int mtlximage15_layer + + , vec3 mtlximage15_default + + , int mtlximage15_uaddressmode + + , int mtlximage15_vaddressmode + + , int mtlximage15_filtertype + + , int mtlximage15_framerange + + , int mtlximage15_frameoffset + + , int mtlximage15_frameendaction + + , vec2 mtlximage15_uv_scale + + , vec2 mtlximage15_uv_offset + + , float mtlxnormalmap12_scale + + , float Chessboard_base + + , float Chessboard_diffuse_roughness + + , float Chessboard_specular + + , vec3 Chessboard_specular_color + + , float Chessboard_specular_IOR + + , float Chessboard_specular_anisotropy + + , float Chessboard_specular_rotation + + , float Chessboard_transmission + + , vec3 Chessboard_transmission_color + + , float Chessboard_transmission_depth + + , vec3 Chessboard_transmission_scatter + + , float Chessboard_transmission_scatter_anisotropy + + , float Chessboard_transmission_dispersion + + , float Chessboard_transmission_extra_roughness + + , float Chessboard_subsurface + + , float Chessboard_subsurface_scale + + , float Chessboard_subsurface_anisotropy + + , float Chessboard_sheen + + , vec3 Chessboard_sheen_color + + , float Chessboard_sheen_roughness + + , float Chessboard_coat + + , vec3 Chessboard_coat_color + + , float Chessboard_coat_roughness + + , float Chessboard_coat_anisotropy + + , float Chessboard_coat_rotation + + , float Chessboard_coat_IOR + + , float Chessboard_coat_affect_color + + , float Chessboard_coat_affect_roughness + + , float Chessboard_thin_film_thickness + + , float Chessboard_thin_film_IOR + + , float Chessboard_emission + + , vec3 Chessboard_emission_color + + , vec3 Chessboard_opacity + + , bool Chessboard_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, mtlximage13_file(mtlximage13_file) + , mtlximage13_layer(mtlximage13_layer) + + , mtlximage13_default(mtlximage13_default) + + , mtlximage13_uaddressmode(mtlximage13_uaddressmode) + + , mtlximage13_vaddressmode(mtlximage13_vaddressmode) + + , mtlximage13_filtertype(mtlximage13_filtertype) + + , mtlximage13_framerange(mtlximage13_framerange) + + , mtlximage13_frameoffset(mtlximage13_frameoffset) + + , mtlximage13_frameendaction(mtlximage13_frameendaction) + + , mtlximage13_uv_scale(mtlximage13_uv_scale) + + , mtlximage13_uv_offset(mtlximage13_uv_offset) + +, mtlximage16_file(mtlximage16_file) + , mtlximage16_layer(mtlximage16_layer) + + , mtlximage16_default(mtlximage16_default) + + , mtlximage16_uaddressmode(mtlximage16_uaddressmode) + + , mtlximage16_vaddressmode(mtlximage16_vaddressmode) + + , mtlximage16_filtertype(mtlximage16_filtertype) + + , mtlximage16_framerange(mtlximage16_framerange) + + , mtlximage16_frameoffset(mtlximage16_frameoffset) + + , mtlximage16_frameendaction(mtlximage16_frameendaction) + + , mtlximage16_uv_scale(mtlximage16_uv_scale) + + , mtlximage16_uv_offset(mtlximage16_uv_offset) + +, mtlximage17_file(mtlximage17_file) + , mtlximage17_layer(mtlximage17_layer) + + , mtlximage17_default(mtlximage17_default) + + , mtlximage17_uaddressmode(mtlximage17_uaddressmode) + + , mtlximage17_vaddressmode(mtlximage17_vaddressmode) + + , mtlximage17_filtertype(mtlximage17_filtertype) + + , mtlximage17_framerange(mtlximage17_framerange) + + , mtlximage17_frameoffset(mtlximage17_frameoffset) + + , mtlximage17_frameendaction(mtlximage17_frameendaction) + + , mtlximage17_uv_scale(mtlximage17_uv_scale) + + , mtlximage17_uv_offset(mtlximage17_uv_offset) + +, mtlximage15_file(mtlximage15_file) + , mtlximage15_layer(mtlximage15_layer) + + , mtlximage15_default(mtlximage15_default) + + , mtlximage15_uaddressmode(mtlximage15_uaddressmode) + + , mtlximage15_vaddressmode(mtlximage15_vaddressmode) + + , mtlximage15_filtertype(mtlximage15_filtertype) + + , mtlximage15_framerange(mtlximage15_framerange) + + , mtlximage15_frameoffset(mtlximage15_frameoffset) + + , mtlximage15_frameendaction(mtlximage15_frameendaction) + + , mtlximage15_uv_scale(mtlximage15_uv_scale) + + , mtlximage15_uv_offset(mtlximage15_uv_offset) + + , mtlxnormalmap12_scale(mtlxnormalmap12_scale) + + , Chessboard_base(Chessboard_base) + + , Chessboard_diffuse_roughness(Chessboard_diffuse_roughness) + + , Chessboard_specular(Chessboard_specular) + + , Chessboard_specular_color(Chessboard_specular_color) + + , Chessboard_specular_IOR(Chessboard_specular_IOR) + + , Chessboard_specular_anisotropy(Chessboard_specular_anisotropy) + + , Chessboard_specular_rotation(Chessboard_specular_rotation) + + , Chessboard_transmission(Chessboard_transmission) + + , Chessboard_transmission_color(Chessboard_transmission_color) + + , Chessboard_transmission_depth(Chessboard_transmission_depth) + + , Chessboard_transmission_scatter(Chessboard_transmission_scatter) + + , Chessboard_transmission_scatter_anisotropy(Chessboard_transmission_scatter_anisotropy) + + , Chessboard_transmission_dispersion(Chessboard_transmission_dispersion) + + , Chessboard_transmission_extra_roughness(Chessboard_transmission_extra_roughness) + + , Chessboard_subsurface(Chessboard_subsurface) + + , Chessboard_subsurface_scale(Chessboard_subsurface_scale) + + , Chessboard_subsurface_anisotropy(Chessboard_subsurface_anisotropy) + + , Chessboard_sheen(Chessboard_sheen) + + , Chessboard_sheen_color(Chessboard_sheen_color) + + , Chessboard_sheen_roughness(Chessboard_sheen_roughness) + + , Chessboard_coat(Chessboard_coat) + + , Chessboard_coat_color(Chessboard_coat_color) + + , Chessboard_coat_roughness(Chessboard_coat_roughness) + + , Chessboard_coat_anisotropy(Chessboard_coat_anisotropy) + + , Chessboard_coat_rotation(Chessboard_coat_rotation) + + , Chessboard_coat_IOR(Chessboard_coat_IOR) + + , Chessboard_coat_affect_color(Chessboard_coat_affect_color) + + , Chessboard_coat_affect_roughness(Chessboard_coat_affect_roughness) + + , Chessboard_thin_film_thickness(Chessboard_thin_film_thickness) + + , Chessboard_thin_film_IOR(Chessboard_thin_film_IOR) + + , Chessboard_emission(Chessboard_emission) + + , Chessboard_emission_color(Chessboard_emission_color) + + , Chessboard_opacity(Chessboard_opacity) + + , Chessboard_thin_walled(Chessboard_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture mtlximage13_file; + int mtlximage13_layer; + + + vec3 mtlximage13_default; + + + int mtlximage13_uaddressmode; + + + int mtlximage13_vaddressmode; + + + int mtlximage13_filtertype; + + + int mtlximage13_framerange; + + + int mtlximage13_frameoffset; + + + int mtlximage13_frameendaction; + + + vec2 mtlximage13_uv_scale; + + + vec2 mtlximage13_uv_offset; + + +MetalTexture mtlximage16_file; + int mtlximage16_layer; + + + float mtlximage16_default; + + + int mtlximage16_uaddressmode; + + + int mtlximage16_vaddressmode; + + + int mtlximage16_filtertype; + + + int mtlximage16_framerange; + + + int mtlximage16_frameoffset; + + + int mtlximage16_frameendaction; + + + vec2 mtlximage16_uv_scale; + + + vec2 mtlximage16_uv_offset; + + +MetalTexture mtlximage17_file; + int mtlximage17_layer; + + + float mtlximage17_default; + + + int mtlximage17_uaddressmode; + + + int mtlximage17_vaddressmode; + + + int mtlximage17_filtertype; + + + int mtlximage17_framerange; + + + int mtlximage17_frameoffset; + + + int mtlximage17_frameendaction; + + + vec2 mtlximage17_uv_scale; + + + vec2 mtlximage17_uv_offset; + + +MetalTexture mtlximage15_file; + int mtlximage15_layer; + + + vec3 mtlximage15_default; + + + int mtlximage15_uaddressmode; + + + int mtlximage15_vaddressmode; + + + int mtlximage15_filtertype; + + + int mtlximage15_framerange; + + + int mtlximage15_frameoffset; + + + int mtlximage15_frameendaction; + + + vec2 mtlximage15_uv_scale; + + + vec2 mtlximage15_uv_offset; + + + float mtlxnormalmap12_scale; + + + float Chessboard_base; + + + float Chessboard_diffuse_roughness; + + + float Chessboard_specular; + + + vec3 Chessboard_specular_color; + + + float Chessboard_specular_IOR; + + + float Chessboard_specular_anisotropy; + + + float Chessboard_specular_rotation; + + + float Chessboard_transmission; + + + vec3 Chessboard_transmission_color; + + + float Chessboard_transmission_depth; + + + vec3 Chessboard_transmission_scatter; + + + float Chessboard_transmission_scatter_anisotropy; + + + float Chessboard_transmission_dispersion; + + + float Chessboard_transmission_extra_roughness; + + + float Chessboard_subsurface; + + + float Chessboard_subsurface_scale; + + + float Chessboard_subsurface_anisotropy; + + + float Chessboard_sheen; + + + vec3 Chessboard_sheen_color; + + + float Chessboard_sheen_roughness; + + + float Chessboard_coat; + + + vec3 Chessboard_coat_color; + + + float Chessboard_coat_roughness; + + + float Chessboard_coat_anisotropy; + + + float Chessboard_coat_rotation; + + + float Chessboard_coat_IOR; + + + float Chessboard_coat_affect_color; + + + float Chessboard_coat_affect_roughness; + + + float Chessboard_thin_film_thickness; + + + float Chessboard_thin_film_IOR; + + + float Chessboard_emission; + + + vec3 Chessboard_emission_color; + + + vec3 Chessboard_opacity; + + + bool Chessboard_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 mtlximage13_out = vec3(0.0); + mx_image_color3(mtlximage13_file, mtlximage13_layer, mtlximage13_default, geomprop_UV0_out1, mtlximage13_uaddressmode, mtlximage13_vaddressmode, mtlximage13_filtertype, mtlximage13_framerange, mtlximage13_frameoffset, mtlximage13_frameendaction, mtlximage13_uv_scale, mtlximage13_uv_offset, mtlximage13_out); + float mtlximage16_out = 0.0; + mx_image_float(mtlximage16_file, mtlximage16_layer, mtlximage16_default, geomprop_UV0_out1, mtlximage16_uaddressmode, mtlximage16_vaddressmode, mtlximage16_filtertype, mtlximage16_framerange, mtlximage16_frameoffset, mtlximage16_frameendaction, mtlximage16_uv_scale, mtlximage16_uv_offset, mtlximage16_out); + float mtlximage17_out = 0.0; + mx_image_float(mtlximage17_file, mtlximage17_layer, mtlximage17_default, geomprop_UV0_out1, mtlximage17_uaddressmode, mtlximage17_vaddressmode, mtlximage17_filtertype, mtlximage17_framerange, mtlximage17_frameoffset, mtlximage17_frameendaction, mtlximage17_uv_scale, mtlximage17_uv_offset, mtlximage17_out); + vec3 mtlximage15_out = vec3(0.0); + mx_image_vector3(mtlximage15_file, mtlximage15_layer, mtlximage15_default, geomprop_UV0_out1, mtlximage15_uaddressmode, mtlximage15_vaddressmode, mtlximage15_filtertype, mtlximage15_framerange, mtlximage15_frameoffset, mtlximage15_frameendaction, mtlximage15_uv_scale, mtlximage15_uv_offset, mtlximage15_out); + vec3 mtlximage13_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(mtlximage13_out, mtlximage13_out_cm_out); + vec3 mtlxnormalmap12_out = vec3(0.0); + mx_normalmap_float(mtlximage15_out, mtlxnormalmap12_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap12_out); + surfaceshader Chessboard_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Chessboard_base, mtlximage13_out_cm_out, Chessboard_diffuse_roughness, mtlximage16_out, Chessboard_specular, Chessboard_specular_color, mtlximage17_out, Chessboard_specular_IOR, Chessboard_specular_anisotropy, Chessboard_specular_rotation, Chessboard_transmission, Chessboard_transmission_color, Chessboard_transmission_depth, Chessboard_transmission_scatter, Chessboard_transmission_scatter_anisotropy, Chessboard_transmission_dispersion, Chessboard_transmission_extra_roughness, Chessboard_subsurface, mtlximage13_out_cm_out, mtlximage13_out_cm_out, Chessboard_subsurface_scale, Chessboard_subsurface_anisotropy, Chessboard_sheen, Chessboard_sheen_color, Chessboard_sheen_roughness, Chessboard_coat, Chessboard_coat_color, Chessboard_coat_roughness, Chessboard_coat_anisotropy, Chessboard_coat_rotation, Chessboard_coat_IOR, geomprop_Nworld_out1, Chessboard_coat_affect_color, Chessboard_coat_affect_roughness, Chessboard_thin_film_thickness, Chessboard_thin_film_IOR, Chessboard_emission, Chessboard_emission_color, Chessboard_opacity, Chessboard_thin_walled, mtlxnormalmap12_out, geomprop_Tworld_out1, Chessboard_out); + material M_Chessboard_out = Chessboard_out; + out1 = float4(M_Chessboard_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d mtlximage13_file_tex [[texture(0)]], sampler mtlximage13_file_sampler [[sampler(0)]] +, texture2d mtlximage16_file_tex [[texture(1)]], sampler mtlximage16_file_sampler [[sampler(1)]] +, texture2d mtlximage17_file_tex [[texture(2)]], sampler mtlximage17_file_sampler [[sampler(2)]] +, texture2d mtlximage15_file_tex [[texture(3)]], sampler mtlximage15_file_sampler [[sampler(3)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(4)]], sampler u_envRadiance_sampler [[sampler(4)]] +, texture2d u_envIrradiance_tex [[texture(5)]], sampler u_envIrradiance_sampler [[sampler(5)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +mtlximage13_file_tex, mtlximage13_file_sampler } + , u_pub.mtlximage13_layer + , u_pub.mtlximage13_default + , u_pub.mtlximage13_uaddressmode + , u_pub.mtlximage13_vaddressmode + , u_pub.mtlximage13_filtertype + , u_pub.mtlximage13_framerange + , u_pub.mtlximage13_frameoffset + , u_pub.mtlximage13_frameendaction + , u_pub.mtlximage13_uv_scale + , u_pub.mtlximage13_uv_offset +, MetalTexture { +mtlximage16_file_tex, mtlximage16_file_sampler } + , u_pub.mtlximage16_layer + , u_pub.mtlximage16_default + , u_pub.mtlximage16_uaddressmode + , u_pub.mtlximage16_vaddressmode + , u_pub.mtlximage16_filtertype + , u_pub.mtlximage16_framerange + , u_pub.mtlximage16_frameoffset + , u_pub.mtlximage16_frameendaction + , u_pub.mtlximage16_uv_scale + , u_pub.mtlximage16_uv_offset +, MetalTexture { +mtlximage17_file_tex, mtlximage17_file_sampler } + , u_pub.mtlximage17_layer + , u_pub.mtlximage17_default + , u_pub.mtlximage17_uaddressmode + , u_pub.mtlximage17_vaddressmode + , u_pub.mtlximage17_filtertype + , u_pub.mtlximage17_framerange + , u_pub.mtlximage17_frameoffset + , u_pub.mtlximage17_frameendaction + , u_pub.mtlximage17_uv_scale + , u_pub.mtlximage17_uv_offset +, MetalTexture { +mtlximage15_file_tex, mtlximage15_file_sampler } + , u_pub.mtlximage15_layer + , u_pub.mtlximage15_default + , u_pub.mtlximage15_uaddressmode + , u_pub.mtlximage15_vaddressmode + , u_pub.mtlximage15_filtertype + , u_pub.mtlximage15_framerange + , u_pub.mtlximage15_frameoffset + , u_pub.mtlximage15_frameendaction + , u_pub.mtlximage15_uv_scale + , u_pub.mtlximage15_uv_offset + , u_pub.mtlxnormalmap12_scale + , u_pub.Chessboard_base + , u_pub.Chessboard_diffuse_roughness + , u_pub.Chessboard_specular + , u_pub.Chessboard_specular_color + , u_pub.Chessboard_specular_IOR + , u_pub.Chessboard_specular_anisotropy + , u_pub.Chessboard_specular_rotation + , u_pub.Chessboard_transmission + , u_pub.Chessboard_transmission_color + , u_pub.Chessboard_transmission_depth + , u_pub.Chessboard_transmission_scatter + , u_pub.Chessboard_transmission_scatter_anisotropy + , u_pub.Chessboard_transmission_dispersion + , u_pub.Chessboard_transmission_extra_roughness + , u_pub.Chessboard_subsurface + , u_pub.Chessboard_subsurface_scale + , u_pub.Chessboard_subsurface_anisotropy + , u_pub.Chessboard_sheen + , u_pub.Chessboard_sheen_color + , u_pub.Chessboard_sheen_roughness + , u_pub.Chessboard_coat + , u_pub.Chessboard_coat_color + , u_pub.Chessboard_coat_roughness + , u_pub.Chessboard_coat_anisotropy + , u_pub.Chessboard_coat_rotation + , u_pub.Chessboard_coat_IOR + , u_pub.Chessboard_coat_affect_color + , u_pub.Chessboard_coat_affect_roughness + , u_pub.Chessboard_thin_film_thickness + , u_pub.Chessboard_thin_film_IOR + , u_pub.Chessboard_emission + , u_pub.Chessboard_emission_color + , u_pub.Chessboard_opacity + , u_pub.Chessboard_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Chessboard.msl.vert b/Materials/Examples/StandardSurface/M_Chessboard.msl.vert new file mode 100644 index 0000000000..2cab9e794c --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Chessboard.msl.vert @@ -0,0 +1,127 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'mtlximage13'. Function already called in this scope. + // Omitted node 'mtlximage16'. Function already called in this scope. + // Omitted node 'mtlximage17'. Function already called in this scope. + // Omitted node 'mtlximage15'. Function already called in this scope. + // Omitted node 'mtlximage13_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap12'. Function already called in this scope. + // Omitted node 'Chessboard'. Function already called in this scope. + // Omitted node 'M_Chessboard'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Chessboard.osl b/Materials/Examples/StandardSurface/M_Chessboard.osl new file mode 100644 index 0000000000..0317379b4a --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Chessboard.osl @@ -0,0 +1,678 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Chessboard +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Chessboard" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string mtlximage13_file = "chess_set/chessboard_base_color.jpg" + [[ + string widget = "filename" + ]], + string mtlximage13_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage13_layer = "", + color mtlximage13_default = color(0.000000, 0.000000, 0.000000), + string mtlximage13_uaddressmode = "periodic", + string mtlximage13_vaddressmode = "periodic", + string mtlximage13_filtertype = "linear", + string mtlximage13_framerange = "", + int mtlximage13_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage13_frameendaction = "constant", + string mtlximage16_file = "chess_set/chessboard_metallic.jpg" + [[ + string widget = "filename" + ]], + string mtlximage16_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage16_layer = "", + float mtlximage16_default = 0.000000 + [[ + string widget = "number" + ]], + string mtlximage16_uaddressmode = "periodic", + string mtlximage16_vaddressmode = "periodic", + string mtlximage16_filtertype = "linear", + string mtlximage16_framerange = "", + int mtlximage16_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage16_frameendaction = "constant", + string mtlximage17_file = "chess_set/chessboard_roughness.jpg" + [[ + string widget = "filename" + ]], + string mtlximage17_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage17_layer = "", + float mtlximage17_default = 0.000000 + [[ + string widget = "number" + ]], + string mtlximage17_uaddressmode = "periodic", + string mtlximage17_vaddressmode = "periodic", + string mtlximage17_filtertype = "linear", + string mtlximage17_framerange = "", + int mtlximage17_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage17_frameendaction = "constant", + string mtlximage15_file = "chess_set/chessboard_normal.jpg" + [[ + string widget = "filename" + ]], + string mtlximage15_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage15_layer = "", + vector mtlximage15_default = vector(0.000000, 0.000000, 0.000000), + string mtlximage15_uaddressmode = "periodic", + string mtlximage15_vaddressmode = "periodic", + string mtlximage15_filtertype = "linear", + string mtlximage15_framerange = "", + int mtlximage15_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage15_frameendaction = "constant", + float mtlxnormalmap12_scale = 1.000000 + [[ + string widget = "number" + ]], + float Chessboard_base = 1.000000 + [[ + string widget = "number" + ]], + float Chessboard_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_specular = 1.000000 + [[ + string widget = "number" + ]], + color Chessboard_specular_color = color(1.000000, 1.000000, 1.000000), + float Chessboard_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Chessboard_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_transmission = 0.000000 + [[ + string widget = "number" + ]], + color Chessboard_transmission_color = color(1.000000, 1.000000, 1.000000), + float Chessboard_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Chessboard_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Chessboard_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_subsurface = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float Chessboard_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Chessboard_sheen_color = color(1.000000, 1.000000, 1.000000), + float Chessboard_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Chessboard_coat = 0.000000 + [[ + string widget = "number" + ]], + color Chessboard_coat_color = color(1.000000, 1.000000, 1.000000), + float Chessboard_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Chessboard_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Chessboard_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Chessboard_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Chessboard_emission = 0.000000 + [[ + string widget = "number" + ]], + color Chessboard_emission_color = color(1.000000, 1.000000, 1.000000), + color Chessboard_opacity = color(1.000000, 1.000000, 1.000000), + int Chessboard_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource mtlximage13_file_ = {mtlximage13_file, mtlximage13_file_colorspace}; + textureresource mtlximage16_file_ = {mtlximage16_file, mtlximage16_file_colorspace}; + textureresource mtlximage17_file_ = {mtlximage17_file, mtlximage17_file_colorspace}; + textureresource mtlximage15_file_ = {mtlximage15_file, mtlximage15_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color mtlximage13_out = color(0.0); + mx_image_color3(mtlximage13_file_, mtlximage13_layer, mtlximage13_default, geomprop_UV0_out1, mtlximage13_uaddressmode, mtlximage13_vaddressmode, mtlximage13_filtertype, mtlximage13_framerange, mtlximage13_frameoffset, mtlximage13_frameendaction, mtlximage13_out); + float mtlximage16_out = 0.0; + mx_image_float(mtlximage16_file_, mtlximage16_layer, mtlximage16_default, geomprop_UV0_out1, mtlximage16_uaddressmode, mtlximage16_vaddressmode, mtlximage16_filtertype, mtlximage16_framerange, mtlximage16_frameoffset, mtlximage16_frameendaction, mtlximage16_out); + float mtlximage17_out = 0.0; + mx_image_float(mtlximage17_file_, mtlximage17_layer, mtlximage17_default, geomprop_UV0_out1, mtlximage17_uaddressmode, mtlximage17_vaddressmode, mtlximage17_filtertype, mtlximage17_framerange, mtlximage17_frameoffset, mtlximage17_frameendaction, mtlximage17_out); + vector mtlximage15_out = vector(0.0); + mx_image_vector3(mtlximage15_file_, mtlximage15_layer, mtlximage15_default, geomprop_UV0_out1, mtlximage15_uaddressmode, mtlximage15_vaddressmode, mtlximage15_filtertype, mtlximage15_framerange, mtlximage15_frameoffset, mtlximage15_frameendaction, mtlximage15_out); + color mtlximage13_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(mtlximage13_out, mtlximage13_out_cm_out); + vector mtlxnormalmap12_out = vector(0.0); + mx_normalmap_float(mtlximage15_out, mtlxnormalmap12_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap12_out); + surfaceshader Chessboard_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Chessboard_base, mtlximage13_out_cm_out, Chessboard_diffuse_roughness, mtlximage16_out, Chessboard_specular, Chessboard_specular_color, mtlximage17_out, Chessboard_specular_IOR, Chessboard_specular_anisotropy, Chessboard_specular_rotation, Chessboard_transmission, Chessboard_transmission_color, Chessboard_transmission_depth, Chessboard_transmission_scatter, Chessboard_transmission_scatter_anisotropy, Chessboard_transmission_dispersion, Chessboard_transmission_extra_roughness, Chessboard_subsurface, mtlximage13_out_cm_out, mtlximage13_out_cm_out, Chessboard_subsurface_scale, Chessboard_subsurface_anisotropy, Chessboard_sheen, Chessboard_sheen_color, Chessboard_sheen_roughness, Chessboard_coat, Chessboard_coat_color, Chessboard_coat_roughness, Chessboard_coat_anisotropy, Chessboard_coat_rotation, Chessboard_coat_IOR, geomprop_Nworld_out1, Chessboard_coat_affect_color, Chessboard_coat_affect_roughness, Chessboard_thin_film_thickness, Chessboard_thin_film_IOR, Chessboard_emission, Chessboard_emission_color, Chessboard_opacity, Chessboard_thin_walled, mtlxnormalmap12_out, geomprop_Tworld_out1, Chessboard_out); + MATERIAL M_Chessboard_out = mx_surfacematerial(Chessboard_out, backsurfaceshader, displacementshader1); + out = M_Chessboard_out; +} + diff --git a/Materials/Examples/StandardSurface/M_King_B.glsl.frag b/Materials/Examples/StandardSurface/M_King_B.glsl.frag new file mode 100644 index 0000000000..285d5e8473 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_King_B.glsl.frag @@ -0,0 +1,2025 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D mtlximage1_file; +uniform int mtlximage1_layer = 0; +uniform vec3 mtlximage1_default = vec3(0.000000, 0.000000, 0.000000); +uniform int mtlximage1_uaddressmode = 2; +uniform int mtlximage1_vaddressmode = 2; +uniform int mtlximage1_filtertype = 1; +uniform int mtlximage1_framerange = 0; +uniform int mtlximage1_frameoffset = 0; +uniform int mtlximage1_frameendaction = 0; +uniform vec2 mtlximage1_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage1_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage2_file; +uniform int mtlximage2_layer = 0; +uniform float mtlximage2_default = 0.000000; +uniform int mtlximage2_uaddressmode = 2; +uniform int mtlximage2_vaddressmode = 2; +uniform int mtlximage2_filtertype = 1; +uniform int mtlximage2_framerange = 0; +uniform int mtlximage2_frameoffset = 0; +uniform int mtlximage2_frameendaction = 0; +uniform vec2 mtlximage2_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage2_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage4_file; +uniform int mtlximage4_layer = 0; +uniform float mtlximage4_default = 0.000000; +uniform int mtlximage4_uaddressmode = 2; +uniform int mtlximage4_vaddressmode = 2; +uniform int mtlximage4_filtertype = 1; +uniform int mtlximage4_framerange = 0; +uniform int mtlximage4_frameoffset = 0; +uniform int mtlximage4_frameendaction = 0; +uniform vec2 mtlximage4_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage4_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage3_file; +uniform int mtlximage3_layer = 0; +uniform float mtlximage3_default = 0.000000; +uniform int mtlximage3_uaddressmode = 2; +uniform int mtlximage3_vaddressmode = 2; +uniform int mtlximage3_filtertype = 1; +uniform int mtlximage3_framerange = 0; +uniform int mtlximage3_frameoffset = 0; +uniform int mtlximage3_frameendaction = 0; +uniform vec2 mtlximage3_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage3_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage6_file; +uniform int mtlximage6_layer = 0; +uniform vec3 mtlximage6_default = vec3(0.000000, 0.000000, 0.000000); +uniform int mtlximage6_uaddressmode = 2; +uniform int mtlximage6_vaddressmode = 2; +uniform int mtlximage6_filtertype = 1; +uniform int mtlximage6_framerange = 0; +uniform int mtlximage6_frameoffset = 0; +uniform int mtlximage6_frameendaction = 0; +uniform vec2 mtlximage6_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage6_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap1_scale = 1.000000; +uniform float King_B_base = 1.000000; +uniform float King_B_diffuse_roughness = 0.000000; +uniform float King_B_specular = 1.000000; +uniform vec3 King_B_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float King_B_specular_IOR = 1.500000; +uniform float King_B_specular_anisotropy = 0.000000; +uniform float King_B_specular_rotation = 0.000000; +uniform float King_B_transmission = 0.000000; +uniform vec3 King_B_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float King_B_transmission_depth = 0.000000; +uniform vec3 King_B_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float King_B_transmission_scatter_anisotropy = 0.000000; +uniform float King_B_transmission_dispersion = 0.000000; +uniform float King_B_transmission_extra_roughness = 0.000000; +uniform float King_B_subsurface_scale = 0.003000; +uniform float King_B_subsurface_anisotropy = 0.000000; +uniform float King_B_sheen = 0.000000; +uniform vec3 King_B_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float King_B_sheen_roughness = 0.300000; +uniform float King_B_coat = 0.000000; +uniform vec3 King_B_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float King_B_coat_roughness = 0.100000; +uniform float King_B_coat_anisotropy = 0.000000; +uniform float King_B_coat_rotation = 0.000000; +uniform float King_B_coat_IOR = 1.500000; +uniform float King_B_coat_affect_color = 0.000000; +uniform float King_B_coat_affect_roughness = 0.000000; +uniform float King_B_thin_film_thickness = 0.000000; +uniform float King_B_thin_film_IOR = 1.500000; +uniform float King_B_emission = 0.000000; +uniform vec3 King_B_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 King_B_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool King_B_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 mtlximage1_out = vec3(0.0); + mx_image_color3(mtlximage1_file, mtlximage1_layer, mtlximage1_default, geomprop_UV0_out1, mtlximage1_uaddressmode, mtlximage1_vaddressmode, mtlximage1_filtertype, mtlximage1_framerange, mtlximage1_frameoffset, mtlximage1_frameendaction, mtlximage1_uv_scale, mtlximage1_uv_offset, mtlximage1_out); + float mtlximage2_out = 0.0; + mx_image_float(mtlximage2_file, mtlximage2_layer, mtlximage2_default, geomprop_UV0_out1, mtlximage2_uaddressmode, mtlximage2_vaddressmode, mtlximage2_filtertype, mtlximage2_framerange, mtlximage2_frameoffset, mtlximage2_frameendaction, mtlximage2_uv_scale, mtlximage2_uv_offset, mtlximage2_out); + float mtlximage4_out = 0.0; + mx_image_float(mtlximage4_file, mtlximage4_layer, mtlximage4_default, geomprop_UV0_out1, mtlximage4_uaddressmode, mtlximage4_vaddressmode, mtlximage4_filtertype, mtlximage4_framerange, mtlximage4_frameoffset, mtlximage4_frameendaction, mtlximage4_uv_scale, mtlximage4_uv_offset, mtlximage4_out); + float mtlximage3_out = 0.0; + mx_image_float(mtlximage3_file, mtlximage3_layer, mtlximage3_default, geomprop_UV0_out1, mtlximage3_uaddressmode, mtlximage3_vaddressmode, mtlximage3_filtertype, mtlximage3_framerange, mtlximage3_frameoffset, mtlximage3_frameendaction, mtlximage3_uv_scale, mtlximage3_uv_offset, mtlximage3_out); + vec3 mtlximage6_out = vec3(0.0); + mx_image_vector3(mtlximage6_file, mtlximage6_layer, mtlximage6_default, geomprop_UV0_out1, mtlximage6_uaddressmode, mtlximage6_vaddressmode, mtlximage6_filtertype, mtlximage6_framerange, mtlximage6_frameoffset, mtlximage6_frameendaction, mtlximage6_uv_scale, mtlximage6_uv_offset, mtlximage6_out); + vec3 mtlximage1_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(mtlximage1_out, mtlximage1_out_cm_out); + vec3 mtlxnormalmap1_out = vec3(0.0); + mx_normalmap_float(mtlximage6_out, mtlxnormalmap1_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap1_out); + surfaceshader King_B_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(King_B_base, mtlximage1_out_cm_out, King_B_diffuse_roughness, mtlximage2_out, King_B_specular, King_B_specular_color, mtlximage4_out, King_B_specular_IOR, King_B_specular_anisotropy, King_B_specular_rotation, King_B_transmission, King_B_transmission_color, King_B_transmission_depth, King_B_transmission_scatter, King_B_transmission_scatter_anisotropy, King_B_transmission_dispersion, King_B_transmission_extra_roughness, mtlximage3_out, mtlximage1_out_cm_out, mtlximage1_out_cm_out, King_B_subsurface_scale, King_B_subsurface_anisotropy, King_B_sheen, King_B_sheen_color, King_B_sheen_roughness, King_B_coat, King_B_coat_color, King_B_coat_roughness, King_B_coat_anisotropy, King_B_coat_rotation, King_B_coat_IOR, geomprop_Nworld_out1, King_B_coat_affect_color, King_B_coat_affect_roughness, King_B_thin_film_thickness, King_B_thin_film_IOR, King_B_emission, King_B_emission_color, King_B_opacity, King_B_thin_walled, mtlxnormalmap1_out, geomprop_Tworld_out1, King_B_out); + material M_King_B_out = King_B_out; + out1 = vec4(M_King_B_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_King_B.glsl.vert b/Materials/Examples/StandardSurface/M_King_B.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_King_B.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_King_B.mdl b/Materials/Examples/StandardSurface/M_King_B.mdl new file mode 100644 index 0000000000..2ab3720a06 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_King_B.mdl @@ -0,0 +1,539 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_King_B +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d mtlximage1_file = texture_2d("/chess_set/king_black_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KingBlack/mtlximage1/file") + ]], + uniform string mtlximage1_layer = "" + [[ + materialx::core::origin("NG_KingBlack/mtlximage1/layer") + ]], + color mtlximage1_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_KingBlack/mtlximage1/default") + ]], + uniform mx_addressmode_type mtlximage1_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingBlack/mtlximage1/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage1_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingBlack/mtlximage1/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage1_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KingBlack/mtlximage1/filtertype") + ]], + uniform string mtlximage1_framerange = "" + [[ + materialx::core::origin("NG_KingBlack/mtlximage1/framerange") + ]], + uniform int mtlximage1_frameoffset = 0 + [[ + materialx::core::origin("NG_KingBlack/mtlximage1/frameoffset") + ]], + uniform mx_addressmode_type mtlximage1_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KingBlack/mtlximage1/frameendaction") + ]], + uniform texture_2d mtlximage2_file = texture_2d("/chess_set/king_shared_metallic.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KingBlack/mtlximage2/file") + ]], + uniform string mtlximage2_layer = "" + [[ + materialx::core::origin("NG_KingBlack/mtlximage2/layer") + ]], + float mtlximage2_default = 0.000000 + [[ + materialx::core::origin("NG_KingBlack/mtlximage2/default") + ]], + uniform mx_addressmode_type mtlximage2_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingBlack/mtlximage2/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage2_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingBlack/mtlximage2/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage2_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KingBlack/mtlximage2/filtertype") + ]], + uniform string mtlximage2_framerange = "" + [[ + materialx::core::origin("NG_KingBlack/mtlximage2/framerange") + ]], + uniform int mtlximage2_frameoffset = 0 + [[ + materialx::core::origin("NG_KingBlack/mtlximage2/frameoffset") + ]], + uniform mx_addressmode_type mtlximage2_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KingBlack/mtlximage2/frameendaction") + ]], + uniform texture_2d mtlximage4_file = texture_2d("/chess_set/king_black_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KingBlack/mtlximage4/file") + ]], + uniform string mtlximage4_layer = "" + [[ + materialx::core::origin("NG_KingBlack/mtlximage4/layer") + ]], + float mtlximage4_default = 0.000000 + [[ + materialx::core::origin("NG_KingBlack/mtlximage4/default") + ]], + uniform mx_addressmode_type mtlximage4_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingBlack/mtlximage4/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage4_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingBlack/mtlximage4/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage4_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KingBlack/mtlximage4/filtertype") + ]], + uniform string mtlximage4_framerange = "" + [[ + materialx::core::origin("NG_KingBlack/mtlximage4/framerange") + ]], + uniform int mtlximage4_frameoffset = 0 + [[ + materialx::core::origin("NG_KingBlack/mtlximage4/frameoffset") + ]], + uniform mx_addressmode_type mtlximage4_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KingBlack/mtlximage4/frameendaction") + ]], + uniform texture_2d mtlximage3_file = texture_2d("/chess_set/king_shared_scattering.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KingBlack/mtlximage3/file") + ]], + uniform string mtlximage3_layer = "" + [[ + materialx::core::origin("NG_KingBlack/mtlximage3/layer") + ]], + float mtlximage3_default = 0.000000 + [[ + materialx::core::origin("NG_KingBlack/mtlximage3/default") + ]], + uniform mx_addressmode_type mtlximage3_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingBlack/mtlximage3/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage3_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingBlack/mtlximage3/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage3_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KingBlack/mtlximage3/filtertype") + ]], + uniform string mtlximage3_framerange = "" + [[ + materialx::core::origin("NG_KingBlack/mtlximage3/framerange") + ]], + uniform int mtlximage3_frameoffset = 0 + [[ + materialx::core::origin("NG_KingBlack/mtlximage3/frameoffset") + ]], + uniform mx_addressmode_type mtlximage3_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KingBlack/mtlximage3/frameendaction") + ]], + uniform texture_2d mtlximage6_file = texture_2d("/chess_set/king_black_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KingBlack/mtlximage6/file") + ]], + uniform string mtlximage6_layer = "" + [[ + materialx::core::origin("NG_KingBlack/mtlximage6/layer") + ]], + float3 mtlximage6_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_KingBlack/mtlximage6/default") + ]], + uniform mx_addressmode_type mtlximage6_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingBlack/mtlximage6/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage6_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingBlack/mtlximage6/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage6_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KingBlack/mtlximage6/filtertype") + ]], + uniform string mtlximage6_framerange = "" + [[ + materialx::core::origin("NG_KingBlack/mtlximage6/framerange") + ]], + uniform int mtlximage6_frameoffset = 0 + [[ + materialx::core::origin("NG_KingBlack/mtlximage6/frameoffset") + ]], + uniform mx_addressmode_type mtlximage6_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KingBlack/mtlximage6/frameendaction") + ]], + float mtlxnormalmap1_scale = 1.000000 + [[ + materialx::core::origin("NG_KingBlack/mtlxnormalmap1/scale") + ]], + float King_B_base = 1.000000 + [[ + materialx::core::origin("King_B/base") + ]], + float King_B_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("King_B/diffuse_roughness") + ]], + float King_B_specular = 1.000000 + [[ + materialx::core::origin("King_B/specular") + ]], + color King_B_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("King_B/specular_color") + ]], + uniform float King_B_specular_IOR = 1.500000 + [[ + materialx::core::origin("King_B/specular_IOR") + ]], + float King_B_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("King_B/specular_anisotropy") + ]], + float King_B_specular_rotation = 0.000000 + [[ + materialx::core::origin("King_B/specular_rotation") + ]], + float King_B_transmission = 0.000000 + [[ + materialx::core::origin("King_B/transmission") + ]], + color King_B_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("King_B/transmission_color") + ]], + float King_B_transmission_depth = 0.000000 + [[ + materialx::core::origin("King_B/transmission_depth") + ]], + color King_B_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("King_B/transmission_scatter") + ]], + float King_B_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("King_B/transmission_scatter_anisotropy") + ]], + float King_B_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("King_B/transmission_dispersion") + ]], + float King_B_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("King_B/transmission_extra_roughness") + ]], + float King_B_subsurface_scale = 0.003000 + [[ + materialx::core::origin("King_B/subsurface_scale") + ]], + float King_B_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("King_B/subsurface_anisotropy") + ]], + float King_B_sheen = 0.000000 + [[ + materialx::core::origin("King_B/sheen") + ]], + color King_B_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("King_B/sheen_color") + ]], + float King_B_sheen_roughness = 0.300000 + [[ + materialx::core::origin("King_B/sheen_roughness") + ]], + float King_B_coat = 0.000000 + [[ + materialx::core::origin("King_B/coat") + ]], + color King_B_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("King_B/coat_color") + ]], + float King_B_coat_roughness = 0.100000 + [[ + materialx::core::origin("King_B/coat_roughness") + ]], + float King_B_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("King_B/coat_anisotropy") + ]], + float King_B_coat_rotation = 0.000000 + [[ + materialx::core::origin("King_B/coat_rotation") + ]], + uniform float King_B_coat_IOR = 1.500000 + [[ + materialx::core::origin("King_B/coat_IOR") + ]], + float King_B_coat_affect_color = 0.000000 + [[ + materialx::core::origin("King_B/coat_affect_color") + ]], + float King_B_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("King_B/coat_affect_roughness") + ]], + float King_B_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("King_B/thin_film_thickness") + ]], + float King_B_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("King_B/thin_film_IOR") + ]], + float King_B_emission = 0.000000 + [[ + materialx::core::origin("King_B/emission") + ]], + color King_B_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("King_B/emission_color") + ]], + color King_B_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("King_B/opacity") + ]], + bool King_B_thin_walled = false + [[ + materialx::core::origin("King_B/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color mtlximage1_out = materialx::stdlib_1_8::mx_image_color3(mtlximage1_file, mtlximage1_layer, mtlximage1_default, geomprop_UV0_out1, mtlximage1_uaddressmode, mtlximage1_vaddressmode, mtlximage1_filtertype, mtlximage1_framerange, mtlximage1_frameoffset, mtlximage1_frameendaction, mxp_flip_v:false); + float mtlximage2_out = materialx::stdlib_1_8::mx_image_float(mtlximage2_file, mtlximage2_layer, mtlximage2_default, geomprop_UV0_out1, mtlximage2_uaddressmode, mtlximage2_vaddressmode, mtlximage2_filtertype, mtlximage2_framerange, mtlximage2_frameoffset, mtlximage2_frameendaction, mxp_flip_v:false); + float mtlximage4_out = materialx::stdlib_1_8::mx_image_float(mtlximage4_file, mtlximage4_layer, mtlximage4_default, geomprop_UV0_out1, mtlximage4_uaddressmode, mtlximage4_vaddressmode, mtlximage4_filtertype, mtlximage4_framerange, mtlximage4_frameoffset, mtlximage4_frameendaction, mxp_flip_v:false); + float mtlximage3_out = materialx::stdlib_1_8::mx_image_float(mtlximage3_file, mtlximage3_layer, mtlximage3_default, geomprop_UV0_out1, mtlximage3_uaddressmode, mtlximage3_vaddressmode, mtlximage3_filtertype, mtlximage3_framerange, mtlximage3_frameoffset, mtlximage3_frameendaction, mxp_flip_v:false); + float3 mtlximage6_out = materialx::stdlib_1_8::mx_image_vector3(mtlximage6_file, mtlximage6_layer, mtlximage6_default, geomprop_UV0_out1, mtlximage6_uaddressmode, mtlximage6_vaddressmode, mtlximage6_filtertype, mtlximage6_framerange, mtlximage6_frameoffset, mtlximage6_frameendaction, mxp_flip_v:false); + color mtlximage1_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(mtlximage1_out); + float3 mtlxnormalmap1_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:mtlximage6_out, mxp_scale:mtlxnormalmap1_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material King_B_out = NG_standard_surface_surfaceshader_100(King_B_base, mtlximage1_out_cm_out, King_B_diffuse_roughness, mtlximage2_out, King_B_specular, King_B_specular_color, mtlximage4_out, King_B_specular_IOR, King_B_specular_anisotropy, King_B_specular_rotation, King_B_transmission, King_B_transmission_color, King_B_transmission_depth, King_B_transmission_scatter, King_B_transmission_scatter_anisotropy, King_B_transmission_dispersion, King_B_transmission_extra_roughness, mtlximage3_out, mtlximage1_out_cm_out, mtlximage1_out_cm_out, King_B_subsurface_scale, King_B_subsurface_anisotropy, King_B_sheen, King_B_sheen_color, King_B_sheen_roughness, King_B_coat, King_B_coat_color, King_B_coat_roughness, King_B_coat_anisotropy, King_B_coat_rotation, King_B_coat_IOR, geomprop_Nworld_out1, King_B_coat_affect_color, King_B_coat_affect_roughness, King_B_thin_film_thickness, King_B_thin_film_IOR, King_B_emission, King_B_emission_color, King_B_opacity, King_B_thin_walled, mtlxnormalmap1_out, geomprop_Tworld_out1); + material M_King_B_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: King_B_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_King_B_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_King_B.msl.frag b/Materials/Examples/StandardSurface/M_King_B.msl.frag new file mode 100644 index 0000000000..92a875b908 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_King_B.msl.frag @@ -0,0 +1,3049 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int mtlximage1_layer; + vec3 mtlximage1_default; + int mtlximage1_uaddressmode; + int mtlximage1_vaddressmode; + int mtlximage1_filtertype; + int mtlximage1_framerange; + int mtlximage1_frameoffset; + int mtlximage1_frameendaction; + vec2 mtlximage1_uv_scale; + vec2 mtlximage1_uv_offset; + int mtlximage2_layer; + float mtlximage2_default; + int mtlximage2_uaddressmode; + int mtlximage2_vaddressmode; + int mtlximage2_filtertype; + int mtlximage2_framerange; + int mtlximage2_frameoffset; + int mtlximage2_frameendaction; + vec2 mtlximage2_uv_scale; + vec2 mtlximage2_uv_offset; + int mtlximage4_layer; + float mtlximage4_default; + int mtlximage4_uaddressmode; + int mtlximage4_vaddressmode; + int mtlximage4_filtertype; + int mtlximage4_framerange; + int mtlximage4_frameoffset; + int mtlximage4_frameendaction; + vec2 mtlximage4_uv_scale; + vec2 mtlximage4_uv_offset; + int mtlximage3_layer; + float mtlximage3_default; + int mtlximage3_uaddressmode; + int mtlximage3_vaddressmode; + int mtlximage3_filtertype; + int mtlximage3_framerange; + int mtlximage3_frameoffset; + int mtlximage3_frameendaction; + vec2 mtlximage3_uv_scale; + vec2 mtlximage3_uv_offset; + int mtlximage6_layer; + vec3 mtlximage6_default; + int mtlximage6_uaddressmode; + int mtlximage6_vaddressmode; + int mtlximage6_filtertype; + int mtlximage6_framerange; + int mtlximage6_frameoffset; + int mtlximage6_frameendaction; + vec2 mtlximage6_uv_scale; + vec2 mtlximage6_uv_offset; + float mtlxnormalmap1_scale; + float King_B_base; + float King_B_diffuse_roughness; + float King_B_specular; + vec3 King_B_specular_color; + float King_B_specular_IOR; + float King_B_specular_anisotropy; + float King_B_specular_rotation; + float King_B_transmission; + vec3 King_B_transmission_color; + float King_B_transmission_depth; + vec3 King_B_transmission_scatter; + float King_B_transmission_scatter_anisotropy; + float King_B_transmission_dispersion; + float King_B_transmission_extra_roughness; + float King_B_subsurface_scale; + float King_B_subsurface_anisotropy; + float King_B_sheen; + vec3 King_B_sheen_color; + float King_B_sheen_roughness; + float King_B_coat; + vec3 King_B_coat_color; + float King_B_coat_roughness; + float King_B_coat_anisotropy; + float King_B_coat_rotation; + float King_B_coat_IOR; + float King_B_coat_affect_color; + float King_B_coat_affect_roughness; + float King_B_thin_film_thickness; + float King_B_thin_film_IOR; + float King_B_emission; + vec3 King_B_emission_color; + vec3 King_B_opacity; + bool King_B_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture mtlximage1_file , int mtlximage1_layer + + , vec3 mtlximage1_default + + , int mtlximage1_uaddressmode + + , int mtlximage1_vaddressmode + + , int mtlximage1_filtertype + + , int mtlximage1_framerange + + , int mtlximage1_frameoffset + + , int mtlximage1_frameendaction + + , vec2 mtlximage1_uv_scale + + , vec2 mtlximage1_uv_offset + +, MetalTexture mtlximage2_file , int mtlximage2_layer + + , float mtlximage2_default + + , int mtlximage2_uaddressmode + + , int mtlximage2_vaddressmode + + , int mtlximage2_filtertype + + , int mtlximage2_framerange + + , int mtlximage2_frameoffset + + , int mtlximage2_frameendaction + + , vec2 mtlximage2_uv_scale + + , vec2 mtlximage2_uv_offset + +, MetalTexture mtlximage4_file , int mtlximage4_layer + + , float mtlximage4_default + + , int mtlximage4_uaddressmode + + , int mtlximage4_vaddressmode + + , int mtlximage4_filtertype + + , int mtlximage4_framerange + + , int mtlximage4_frameoffset + + , int mtlximage4_frameendaction + + , vec2 mtlximage4_uv_scale + + , vec2 mtlximage4_uv_offset + +, MetalTexture mtlximage3_file , int mtlximage3_layer + + , float mtlximage3_default + + , int mtlximage3_uaddressmode + + , int mtlximage3_vaddressmode + + , int mtlximage3_filtertype + + , int mtlximage3_framerange + + , int mtlximage3_frameoffset + + , int mtlximage3_frameendaction + + , vec2 mtlximage3_uv_scale + + , vec2 mtlximage3_uv_offset + +, MetalTexture mtlximage6_file , int mtlximage6_layer + + , vec3 mtlximage6_default + + , int mtlximage6_uaddressmode + + , int mtlximage6_vaddressmode + + , int mtlximage6_filtertype + + , int mtlximage6_framerange + + , int mtlximage6_frameoffset + + , int mtlximage6_frameendaction + + , vec2 mtlximage6_uv_scale + + , vec2 mtlximage6_uv_offset + + , float mtlxnormalmap1_scale + + , float King_B_base + + , float King_B_diffuse_roughness + + , float King_B_specular + + , vec3 King_B_specular_color + + , float King_B_specular_IOR + + , float King_B_specular_anisotropy + + , float King_B_specular_rotation + + , float King_B_transmission + + , vec3 King_B_transmission_color + + , float King_B_transmission_depth + + , vec3 King_B_transmission_scatter + + , float King_B_transmission_scatter_anisotropy + + , float King_B_transmission_dispersion + + , float King_B_transmission_extra_roughness + + , float King_B_subsurface_scale + + , float King_B_subsurface_anisotropy + + , float King_B_sheen + + , vec3 King_B_sheen_color + + , float King_B_sheen_roughness + + , float King_B_coat + + , vec3 King_B_coat_color + + , float King_B_coat_roughness + + , float King_B_coat_anisotropy + + , float King_B_coat_rotation + + , float King_B_coat_IOR + + , float King_B_coat_affect_color + + , float King_B_coat_affect_roughness + + , float King_B_thin_film_thickness + + , float King_B_thin_film_IOR + + , float King_B_emission + + , vec3 King_B_emission_color + + , vec3 King_B_opacity + + , bool King_B_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, mtlximage1_file(mtlximage1_file) + , mtlximage1_layer(mtlximage1_layer) + + , mtlximage1_default(mtlximage1_default) + + , mtlximage1_uaddressmode(mtlximage1_uaddressmode) + + , mtlximage1_vaddressmode(mtlximage1_vaddressmode) + + , mtlximage1_filtertype(mtlximage1_filtertype) + + , mtlximage1_framerange(mtlximage1_framerange) + + , mtlximage1_frameoffset(mtlximage1_frameoffset) + + , mtlximage1_frameendaction(mtlximage1_frameendaction) + + , mtlximage1_uv_scale(mtlximage1_uv_scale) + + , mtlximage1_uv_offset(mtlximage1_uv_offset) + +, mtlximage2_file(mtlximage2_file) + , mtlximage2_layer(mtlximage2_layer) + + , mtlximage2_default(mtlximage2_default) + + , mtlximage2_uaddressmode(mtlximage2_uaddressmode) + + , mtlximage2_vaddressmode(mtlximage2_vaddressmode) + + , mtlximage2_filtertype(mtlximage2_filtertype) + + , mtlximage2_framerange(mtlximage2_framerange) + + , mtlximage2_frameoffset(mtlximage2_frameoffset) + + , mtlximage2_frameendaction(mtlximage2_frameendaction) + + , mtlximage2_uv_scale(mtlximage2_uv_scale) + + , mtlximage2_uv_offset(mtlximage2_uv_offset) + +, mtlximage4_file(mtlximage4_file) + , mtlximage4_layer(mtlximage4_layer) + + , mtlximage4_default(mtlximage4_default) + + , mtlximage4_uaddressmode(mtlximage4_uaddressmode) + + , mtlximage4_vaddressmode(mtlximage4_vaddressmode) + + , mtlximage4_filtertype(mtlximage4_filtertype) + + , mtlximage4_framerange(mtlximage4_framerange) + + , mtlximage4_frameoffset(mtlximage4_frameoffset) + + , mtlximage4_frameendaction(mtlximage4_frameendaction) + + , mtlximage4_uv_scale(mtlximage4_uv_scale) + + , mtlximage4_uv_offset(mtlximage4_uv_offset) + +, mtlximage3_file(mtlximage3_file) + , mtlximage3_layer(mtlximage3_layer) + + , mtlximage3_default(mtlximage3_default) + + , mtlximage3_uaddressmode(mtlximage3_uaddressmode) + + , mtlximage3_vaddressmode(mtlximage3_vaddressmode) + + , mtlximage3_filtertype(mtlximage3_filtertype) + + , mtlximage3_framerange(mtlximage3_framerange) + + , mtlximage3_frameoffset(mtlximage3_frameoffset) + + , mtlximage3_frameendaction(mtlximage3_frameendaction) + + , mtlximage3_uv_scale(mtlximage3_uv_scale) + + , mtlximage3_uv_offset(mtlximage3_uv_offset) + +, mtlximage6_file(mtlximage6_file) + , mtlximage6_layer(mtlximage6_layer) + + , mtlximage6_default(mtlximage6_default) + + , mtlximage6_uaddressmode(mtlximage6_uaddressmode) + + , mtlximage6_vaddressmode(mtlximage6_vaddressmode) + + , mtlximage6_filtertype(mtlximage6_filtertype) + + , mtlximage6_framerange(mtlximage6_framerange) + + , mtlximage6_frameoffset(mtlximage6_frameoffset) + + , mtlximage6_frameendaction(mtlximage6_frameendaction) + + , mtlximage6_uv_scale(mtlximage6_uv_scale) + + , mtlximage6_uv_offset(mtlximage6_uv_offset) + + , mtlxnormalmap1_scale(mtlxnormalmap1_scale) + + , King_B_base(King_B_base) + + , King_B_diffuse_roughness(King_B_diffuse_roughness) + + , King_B_specular(King_B_specular) + + , King_B_specular_color(King_B_specular_color) + + , King_B_specular_IOR(King_B_specular_IOR) + + , King_B_specular_anisotropy(King_B_specular_anisotropy) + + , King_B_specular_rotation(King_B_specular_rotation) + + , King_B_transmission(King_B_transmission) + + , King_B_transmission_color(King_B_transmission_color) + + , King_B_transmission_depth(King_B_transmission_depth) + + , King_B_transmission_scatter(King_B_transmission_scatter) + + , King_B_transmission_scatter_anisotropy(King_B_transmission_scatter_anisotropy) + + , King_B_transmission_dispersion(King_B_transmission_dispersion) + + , King_B_transmission_extra_roughness(King_B_transmission_extra_roughness) + + , King_B_subsurface_scale(King_B_subsurface_scale) + + , King_B_subsurface_anisotropy(King_B_subsurface_anisotropy) + + , King_B_sheen(King_B_sheen) + + , King_B_sheen_color(King_B_sheen_color) + + , King_B_sheen_roughness(King_B_sheen_roughness) + + , King_B_coat(King_B_coat) + + , King_B_coat_color(King_B_coat_color) + + , King_B_coat_roughness(King_B_coat_roughness) + + , King_B_coat_anisotropy(King_B_coat_anisotropy) + + , King_B_coat_rotation(King_B_coat_rotation) + + , King_B_coat_IOR(King_B_coat_IOR) + + , King_B_coat_affect_color(King_B_coat_affect_color) + + , King_B_coat_affect_roughness(King_B_coat_affect_roughness) + + , King_B_thin_film_thickness(King_B_thin_film_thickness) + + , King_B_thin_film_IOR(King_B_thin_film_IOR) + + , King_B_emission(King_B_emission) + + , King_B_emission_color(King_B_emission_color) + + , King_B_opacity(King_B_opacity) + + , King_B_thin_walled(King_B_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture mtlximage1_file; + int mtlximage1_layer; + + + vec3 mtlximage1_default; + + + int mtlximage1_uaddressmode; + + + int mtlximage1_vaddressmode; + + + int mtlximage1_filtertype; + + + int mtlximage1_framerange; + + + int mtlximage1_frameoffset; + + + int mtlximage1_frameendaction; + + + vec2 mtlximage1_uv_scale; + + + vec2 mtlximage1_uv_offset; + + +MetalTexture mtlximage2_file; + int mtlximage2_layer; + + + float mtlximage2_default; + + + int mtlximage2_uaddressmode; + + + int mtlximage2_vaddressmode; + + + int mtlximage2_filtertype; + + + int mtlximage2_framerange; + + + int mtlximage2_frameoffset; + + + int mtlximage2_frameendaction; + + + vec2 mtlximage2_uv_scale; + + + vec2 mtlximage2_uv_offset; + + +MetalTexture mtlximage4_file; + int mtlximage4_layer; + + + float mtlximage4_default; + + + int mtlximage4_uaddressmode; + + + int mtlximage4_vaddressmode; + + + int mtlximage4_filtertype; + + + int mtlximage4_framerange; + + + int mtlximage4_frameoffset; + + + int mtlximage4_frameendaction; + + + vec2 mtlximage4_uv_scale; + + + vec2 mtlximage4_uv_offset; + + +MetalTexture mtlximage3_file; + int mtlximage3_layer; + + + float mtlximage3_default; + + + int mtlximage3_uaddressmode; + + + int mtlximage3_vaddressmode; + + + int mtlximage3_filtertype; + + + int mtlximage3_framerange; + + + int mtlximage3_frameoffset; + + + int mtlximage3_frameendaction; + + + vec2 mtlximage3_uv_scale; + + + vec2 mtlximage3_uv_offset; + + +MetalTexture mtlximage6_file; + int mtlximage6_layer; + + + vec3 mtlximage6_default; + + + int mtlximage6_uaddressmode; + + + int mtlximage6_vaddressmode; + + + int mtlximage6_filtertype; + + + int mtlximage6_framerange; + + + int mtlximage6_frameoffset; + + + int mtlximage6_frameendaction; + + + vec2 mtlximage6_uv_scale; + + + vec2 mtlximage6_uv_offset; + + + float mtlxnormalmap1_scale; + + + float King_B_base; + + + float King_B_diffuse_roughness; + + + float King_B_specular; + + + vec3 King_B_specular_color; + + + float King_B_specular_IOR; + + + float King_B_specular_anisotropy; + + + float King_B_specular_rotation; + + + float King_B_transmission; + + + vec3 King_B_transmission_color; + + + float King_B_transmission_depth; + + + vec3 King_B_transmission_scatter; + + + float King_B_transmission_scatter_anisotropy; + + + float King_B_transmission_dispersion; + + + float King_B_transmission_extra_roughness; + + + float King_B_subsurface_scale; + + + float King_B_subsurface_anisotropy; + + + float King_B_sheen; + + + vec3 King_B_sheen_color; + + + float King_B_sheen_roughness; + + + float King_B_coat; + + + vec3 King_B_coat_color; + + + float King_B_coat_roughness; + + + float King_B_coat_anisotropy; + + + float King_B_coat_rotation; + + + float King_B_coat_IOR; + + + float King_B_coat_affect_color; + + + float King_B_coat_affect_roughness; + + + float King_B_thin_film_thickness; + + + float King_B_thin_film_IOR; + + + float King_B_emission; + + + vec3 King_B_emission_color; + + + vec3 King_B_opacity; + + + bool King_B_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 mtlximage1_out = vec3(0.0); + mx_image_color3(mtlximage1_file, mtlximage1_layer, mtlximage1_default, geomprop_UV0_out1, mtlximage1_uaddressmode, mtlximage1_vaddressmode, mtlximage1_filtertype, mtlximage1_framerange, mtlximage1_frameoffset, mtlximage1_frameendaction, mtlximage1_uv_scale, mtlximage1_uv_offset, mtlximage1_out); + float mtlximage2_out = 0.0; + mx_image_float(mtlximage2_file, mtlximage2_layer, mtlximage2_default, geomprop_UV0_out1, mtlximage2_uaddressmode, mtlximage2_vaddressmode, mtlximage2_filtertype, mtlximage2_framerange, mtlximage2_frameoffset, mtlximage2_frameendaction, mtlximage2_uv_scale, mtlximage2_uv_offset, mtlximage2_out); + float mtlximage4_out = 0.0; + mx_image_float(mtlximage4_file, mtlximage4_layer, mtlximage4_default, geomprop_UV0_out1, mtlximage4_uaddressmode, mtlximage4_vaddressmode, mtlximage4_filtertype, mtlximage4_framerange, mtlximage4_frameoffset, mtlximage4_frameendaction, mtlximage4_uv_scale, mtlximage4_uv_offset, mtlximage4_out); + float mtlximage3_out = 0.0; + mx_image_float(mtlximage3_file, mtlximage3_layer, mtlximage3_default, geomprop_UV0_out1, mtlximage3_uaddressmode, mtlximage3_vaddressmode, mtlximage3_filtertype, mtlximage3_framerange, mtlximage3_frameoffset, mtlximage3_frameendaction, mtlximage3_uv_scale, mtlximage3_uv_offset, mtlximage3_out); + vec3 mtlximage6_out = vec3(0.0); + mx_image_vector3(mtlximage6_file, mtlximage6_layer, mtlximage6_default, geomprop_UV0_out1, mtlximage6_uaddressmode, mtlximage6_vaddressmode, mtlximage6_filtertype, mtlximage6_framerange, mtlximage6_frameoffset, mtlximage6_frameendaction, mtlximage6_uv_scale, mtlximage6_uv_offset, mtlximage6_out); + vec3 mtlximage1_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(mtlximage1_out, mtlximage1_out_cm_out); + vec3 mtlxnormalmap1_out = vec3(0.0); + mx_normalmap_float(mtlximage6_out, mtlxnormalmap1_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap1_out); + surfaceshader King_B_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(King_B_base, mtlximage1_out_cm_out, King_B_diffuse_roughness, mtlximage2_out, King_B_specular, King_B_specular_color, mtlximage4_out, King_B_specular_IOR, King_B_specular_anisotropy, King_B_specular_rotation, King_B_transmission, King_B_transmission_color, King_B_transmission_depth, King_B_transmission_scatter, King_B_transmission_scatter_anisotropy, King_B_transmission_dispersion, King_B_transmission_extra_roughness, mtlximage3_out, mtlximage1_out_cm_out, mtlximage1_out_cm_out, King_B_subsurface_scale, King_B_subsurface_anisotropy, King_B_sheen, King_B_sheen_color, King_B_sheen_roughness, King_B_coat, King_B_coat_color, King_B_coat_roughness, King_B_coat_anisotropy, King_B_coat_rotation, King_B_coat_IOR, geomprop_Nworld_out1, King_B_coat_affect_color, King_B_coat_affect_roughness, King_B_thin_film_thickness, King_B_thin_film_IOR, King_B_emission, King_B_emission_color, King_B_opacity, King_B_thin_walled, mtlxnormalmap1_out, geomprop_Tworld_out1, King_B_out); + material M_King_B_out = King_B_out; + out1 = float4(M_King_B_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d mtlximage1_file_tex [[texture(0)]], sampler mtlximage1_file_sampler [[sampler(0)]] +, texture2d mtlximage2_file_tex [[texture(1)]], sampler mtlximage2_file_sampler [[sampler(1)]] +, texture2d mtlximage4_file_tex [[texture(2)]], sampler mtlximage4_file_sampler [[sampler(2)]] +, texture2d mtlximage3_file_tex [[texture(3)]], sampler mtlximage3_file_sampler [[sampler(3)]] +, texture2d mtlximage6_file_tex [[texture(4)]], sampler mtlximage6_file_sampler [[sampler(4)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(5)]], sampler u_envRadiance_sampler [[sampler(5)]] +, texture2d u_envIrradiance_tex [[texture(6)]], sampler u_envIrradiance_sampler [[sampler(6)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +mtlximage1_file_tex, mtlximage1_file_sampler } + , u_pub.mtlximage1_layer + , u_pub.mtlximage1_default + , u_pub.mtlximage1_uaddressmode + , u_pub.mtlximage1_vaddressmode + , u_pub.mtlximage1_filtertype + , u_pub.mtlximage1_framerange + , u_pub.mtlximage1_frameoffset + , u_pub.mtlximage1_frameendaction + , u_pub.mtlximage1_uv_scale + , u_pub.mtlximage1_uv_offset +, MetalTexture { +mtlximage2_file_tex, mtlximage2_file_sampler } + , u_pub.mtlximage2_layer + , u_pub.mtlximage2_default + , u_pub.mtlximage2_uaddressmode + , u_pub.mtlximage2_vaddressmode + , u_pub.mtlximage2_filtertype + , u_pub.mtlximage2_framerange + , u_pub.mtlximage2_frameoffset + , u_pub.mtlximage2_frameendaction + , u_pub.mtlximage2_uv_scale + , u_pub.mtlximage2_uv_offset +, MetalTexture { +mtlximage4_file_tex, mtlximage4_file_sampler } + , u_pub.mtlximage4_layer + , u_pub.mtlximage4_default + , u_pub.mtlximage4_uaddressmode + , u_pub.mtlximage4_vaddressmode + , u_pub.mtlximage4_filtertype + , u_pub.mtlximage4_framerange + , u_pub.mtlximage4_frameoffset + , u_pub.mtlximage4_frameendaction + , u_pub.mtlximage4_uv_scale + , u_pub.mtlximage4_uv_offset +, MetalTexture { +mtlximage3_file_tex, mtlximage3_file_sampler } + , u_pub.mtlximage3_layer + , u_pub.mtlximage3_default + , u_pub.mtlximage3_uaddressmode + , u_pub.mtlximage3_vaddressmode + , u_pub.mtlximage3_filtertype + , u_pub.mtlximage3_framerange + , u_pub.mtlximage3_frameoffset + , u_pub.mtlximage3_frameendaction + , u_pub.mtlximage3_uv_scale + , u_pub.mtlximage3_uv_offset +, MetalTexture { +mtlximage6_file_tex, mtlximage6_file_sampler } + , u_pub.mtlximage6_layer + , u_pub.mtlximage6_default + , u_pub.mtlximage6_uaddressmode + , u_pub.mtlximage6_vaddressmode + , u_pub.mtlximage6_filtertype + , u_pub.mtlximage6_framerange + , u_pub.mtlximage6_frameoffset + , u_pub.mtlximage6_frameendaction + , u_pub.mtlximage6_uv_scale + , u_pub.mtlximage6_uv_offset + , u_pub.mtlxnormalmap1_scale + , u_pub.King_B_base + , u_pub.King_B_diffuse_roughness + , u_pub.King_B_specular + , u_pub.King_B_specular_color + , u_pub.King_B_specular_IOR + , u_pub.King_B_specular_anisotropy + , u_pub.King_B_specular_rotation + , u_pub.King_B_transmission + , u_pub.King_B_transmission_color + , u_pub.King_B_transmission_depth + , u_pub.King_B_transmission_scatter + , u_pub.King_B_transmission_scatter_anisotropy + , u_pub.King_B_transmission_dispersion + , u_pub.King_B_transmission_extra_roughness + , u_pub.King_B_subsurface_scale + , u_pub.King_B_subsurface_anisotropy + , u_pub.King_B_sheen + , u_pub.King_B_sheen_color + , u_pub.King_B_sheen_roughness + , u_pub.King_B_coat + , u_pub.King_B_coat_color + , u_pub.King_B_coat_roughness + , u_pub.King_B_coat_anisotropy + , u_pub.King_B_coat_rotation + , u_pub.King_B_coat_IOR + , u_pub.King_B_coat_affect_color + , u_pub.King_B_coat_affect_roughness + , u_pub.King_B_thin_film_thickness + , u_pub.King_B_thin_film_IOR + , u_pub.King_B_emission + , u_pub.King_B_emission_color + , u_pub.King_B_opacity + , u_pub.King_B_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_King_B.msl.vert b/Materials/Examples/StandardSurface/M_King_B.msl.vert new file mode 100644 index 0000000000..ced98e6fe4 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_King_B.msl.vert @@ -0,0 +1,128 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'mtlximage1'. Function already called in this scope. + // Omitted node 'mtlximage2'. Function already called in this scope. + // Omitted node 'mtlximage4'. Function already called in this scope. + // Omitted node 'mtlximage3'. Function already called in this scope. + // Omitted node 'mtlximage6'. Function already called in this scope. + // Omitted node 'mtlximage1_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap1'. Function already called in this scope. + // Omitted node 'King_B'. Function already called in this scope. + // Omitted node 'M_King_B'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_King_B.osl b/Materials/Examples/StandardSurface/M_King_B.osl new file mode 100644 index 0000000000..d9d2268955 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_King_B.osl @@ -0,0 +1,699 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_King_B +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_King_B" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string mtlximage1_file = "chess_set/king_black_base_color.jpg" + [[ + string widget = "filename" + ]], + string mtlximage1_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage1_layer = "", + color mtlximage1_default = color(0.000000, 0.000000, 0.000000), + string mtlximage1_uaddressmode = "periodic", + string mtlximage1_vaddressmode = "periodic", + string mtlximage1_filtertype = "linear", + string mtlximage1_framerange = "", + int mtlximage1_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage1_frameendaction = "constant", + string mtlximage2_file = "chess_set/king_shared_metallic.jpg" + [[ + string widget = "filename" + ]], + string mtlximage2_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage2_layer = "", + float mtlximage2_default = 0.000000 + [[ + string widget = "number" + ]], + string mtlximage2_uaddressmode = "periodic", + string mtlximage2_vaddressmode = "periodic", + string mtlximage2_filtertype = "linear", + string mtlximage2_framerange = "", + int mtlximage2_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage2_frameendaction = "constant", + string mtlximage4_file = "chess_set/king_black_roughness.jpg" + [[ + string widget = "filename" + ]], + string mtlximage4_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage4_layer = "", + float mtlximage4_default = 0.000000 + [[ + string widget = "number" + ]], + string mtlximage4_uaddressmode = "periodic", + string mtlximage4_vaddressmode = "periodic", + string mtlximage4_filtertype = "linear", + string mtlximage4_framerange = "", + int mtlximage4_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage4_frameendaction = "constant", + string mtlximage3_file = "chess_set/king_shared_scattering.jpg" + [[ + string widget = "filename" + ]], + string mtlximage3_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage3_layer = "", + float mtlximage3_default = 0.000000 + [[ + string widget = "number" + ]], + string mtlximage3_uaddressmode = "periodic", + string mtlximage3_vaddressmode = "periodic", + string mtlximage3_filtertype = "linear", + string mtlximage3_framerange = "", + int mtlximage3_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage3_frameendaction = "constant", + string mtlximage6_file = "chess_set/king_black_normal.jpg" + [[ + string widget = "filename" + ]], + string mtlximage6_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage6_layer = "", + vector mtlximage6_default = vector(0.000000, 0.000000, 0.000000), + string mtlximage6_uaddressmode = "periodic", + string mtlximage6_vaddressmode = "periodic", + string mtlximage6_filtertype = "linear", + string mtlximage6_framerange = "", + int mtlximage6_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage6_frameendaction = "constant", + float mtlxnormalmap1_scale = 1.000000 + [[ + string widget = "number" + ]], + float King_B_base = 1.000000 + [[ + string widget = "number" + ]], + float King_B_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float King_B_specular = 1.000000 + [[ + string widget = "number" + ]], + color King_B_specular_color = color(1.000000, 1.000000, 1.000000), + float King_B_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float King_B_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float King_B_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float King_B_transmission = 0.000000 + [[ + string widget = "number" + ]], + color King_B_transmission_color = color(1.000000, 1.000000, 1.000000), + float King_B_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color King_B_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float King_B_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float King_B_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float King_B_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float King_B_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float King_B_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float King_B_sheen = 0.000000 + [[ + string widget = "number" + ]], + color King_B_sheen_color = color(1.000000, 1.000000, 1.000000), + float King_B_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float King_B_coat = 0.000000 + [[ + string widget = "number" + ]], + color King_B_coat_color = color(1.000000, 1.000000, 1.000000), + float King_B_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float King_B_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float King_B_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float King_B_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float King_B_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float King_B_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float King_B_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float King_B_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float King_B_emission = 0.000000 + [[ + string widget = "number" + ]], + color King_B_emission_color = color(1.000000, 1.000000, 1.000000), + color King_B_opacity = color(1.000000, 1.000000, 1.000000), + int King_B_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource mtlximage1_file_ = {mtlximage1_file, mtlximage1_file_colorspace}; + textureresource mtlximage2_file_ = {mtlximage2_file, mtlximage2_file_colorspace}; + textureresource mtlximage4_file_ = {mtlximage4_file, mtlximage4_file_colorspace}; + textureresource mtlximage3_file_ = {mtlximage3_file, mtlximage3_file_colorspace}; + textureresource mtlximage6_file_ = {mtlximage6_file, mtlximage6_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color mtlximage1_out = color(0.0); + mx_image_color3(mtlximage1_file_, mtlximage1_layer, mtlximage1_default, geomprop_UV0_out1, mtlximage1_uaddressmode, mtlximage1_vaddressmode, mtlximage1_filtertype, mtlximage1_framerange, mtlximage1_frameoffset, mtlximage1_frameendaction, mtlximage1_out); + float mtlximage2_out = 0.0; + mx_image_float(mtlximage2_file_, mtlximage2_layer, mtlximage2_default, geomprop_UV0_out1, mtlximage2_uaddressmode, mtlximage2_vaddressmode, mtlximage2_filtertype, mtlximage2_framerange, mtlximage2_frameoffset, mtlximage2_frameendaction, mtlximage2_out); + float mtlximage4_out = 0.0; + mx_image_float(mtlximage4_file_, mtlximage4_layer, mtlximage4_default, geomprop_UV0_out1, mtlximage4_uaddressmode, mtlximage4_vaddressmode, mtlximage4_filtertype, mtlximage4_framerange, mtlximage4_frameoffset, mtlximage4_frameendaction, mtlximage4_out); + float mtlximage3_out = 0.0; + mx_image_float(mtlximage3_file_, mtlximage3_layer, mtlximage3_default, geomprop_UV0_out1, mtlximage3_uaddressmode, mtlximage3_vaddressmode, mtlximage3_filtertype, mtlximage3_framerange, mtlximage3_frameoffset, mtlximage3_frameendaction, mtlximage3_out); + vector mtlximage6_out = vector(0.0); + mx_image_vector3(mtlximage6_file_, mtlximage6_layer, mtlximage6_default, geomprop_UV0_out1, mtlximage6_uaddressmode, mtlximage6_vaddressmode, mtlximage6_filtertype, mtlximage6_framerange, mtlximage6_frameoffset, mtlximage6_frameendaction, mtlximage6_out); + color mtlximage1_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(mtlximage1_out, mtlximage1_out_cm_out); + vector mtlxnormalmap1_out = vector(0.0); + mx_normalmap_float(mtlximage6_out, mtlxnormalmap1_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap1_out); + surfaceshader King_B_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(King_B_base, mtlximage1_out_cm_out, King_B_diffuse_roughness, mtlximage2_out, King_B_specular, King_B_specular_color, mtlximage4_out, King_B_specular_IOR, King_B_specular_anisotropy, King_B_specular_rotation, King_B_transmission, King_B_transmission_color, King_B_transmission_depth, King_B_transmission_scatter, King_B_transmission_scatter_anisotropy, King_B_transmission_dispersion, King_B_transmission_extra_roughness, mtlximage3_out, mtlximage1_out_cm_out, mtlximage1_out_cm_out, King_B_subsurface_scale, King_B_subsurface_anisotropy, King_B_sheen, King_B_sheen_color, King_B_sheen_roughness, King_B_coat, King_B_coat_color, King_B_coat_roughness, King_B_coat_anisotropy, King_B_coat_rotation, King_B_coat_IOR, geomprop_Nworld_out1, King_B_coat_affect_color, King_B_coat_affect_roughness, King_B_thin_film_thickness, King_B_thin_film_IOR, King_B_emission, King_B_emission_color, King_B_opacity, King_B_thin_walled, mtlxnormalmap1_out, geomprop_Tworld_out1, King_B_out); + MATERIAL M_King_B_out = mx_surfacematerial(King_B_out, backsurfaceshader, displacementshader1); + out = M_King_B_out; +} + diff --git a/Materials/Examples/StandardSurface/M_King_W.glsl.frag b/Materials/Examples/StandardSurface/M_King_W.glsl.frag new file mode 100644 index 0000000000..4060c203c6 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_King_W.glsl.frag @@ -0,0 +1,2025 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D mtlximage7_file; +uniform int mtlximage7_layer = 0; +uniform vec3 mtlximage7_default = vec3(0.000000, 0.000000, 0.000000); +uniform int mtlximage7_uaddressmode = 2; +uniform int mtlximage7_vaddressmode = 2; +uniform int mtlximage7_filtertype = 1; +uniform int mtlximage7_framerange = 0; +uniform int mtlximage7_frameoffset = 0; +uniform int mtlximage7_frameendaction = 0; +uniform vec2 mtlximage7_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage7_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage10_file; +uniform int mtlximage10_layer = 0; +uniform float mtlximage10_default = 0.000000; +uniform int mtlximage10_uaddressmode = 2; +uniform int mtlximage10_vaddressmode = 2; +uniform int mtlximage10_filtertype = 1; +uniform int mtlximage10_framerange = 0; +uniform int mtlximage10_frameoffset = 0; +uniform int mtlximage10_frameendaction = 0; +uniform vec2 mtlximage10_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage10_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage11_file; +uniform int mtlximage11_layer = 0; +uniform float mtlximage11_default = 0.000000; +uniform int mtlximage11_uaddressmode = 2; +uniform int mtlximage11_vaddressmode = 2; +uniform int mtlximage11_filtertype = 1; +uniform int mtlximage11_framerange = 0; +uniform int mtlximage11_frameoffset = 0; +uniform int mtlximage11_frameendaction = 0; +uniform vec2 mtlximage11_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage11_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage8_file; +uniform int mtlximage8_layer = 0; +uniform float mtlximage8_default = 0.000000; +uniform int mtlximage8_uaddressmode = 2; +uniform int mtlximage8_vaddressmode = 2; +uniform int mtlximage8_filtertype = 1; +uniform int mtlximage8_framerange = 0; +uniform int mtlximage8_frameoffset = 0; +uniform int mtlximage8_frameendaction = 0; +uniform vec2 mtlximage8_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage8_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage9_file; +uniform int mtlximage9_layer = 0; +uniform vec3 mtlximage9_default = vec3(0.000000, 0.000000, 0.000000); +uniform int mtlximage9_uaddressmode = 2; +uniform int mtlximage9_vaddressmode = 2; +uniform int mtlximage9_filtertype = 1; +uniform int mtlximage9_framerange = 0; +uniform int mtlximage9_frameoffset = 0; +uniform int mtlximage9_frameendaction = 0; +uniform vec2 mtlximage9_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage9_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap11_scale = 1.000000; +uniform float King_W_base = 1.000000; +uniform float King_W_diffuse_roughness = 0.000000; +uniform float King_W_specular = 1.000000; +uniform vec3 King_W_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float King_W_specular_IOR = 1.500000; +uniform float King_W_specular_anisotropy = 0.000000; +uniform float King_W_specular_rotation = 0.000000; +uniform float King_W_transmission = 0.000000; +uniform vec3 King_W_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float King_W_transmission_depth = 0.000000; +uniform vec3 King_W_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float King_W_transmission_scatter_anisotropy = 0.000000; +uniform float King_W_transmission_dispersion = 0.000000; +uniform float King_W_transmission_extra_roughness = 0.000000; +uniform float King_W_subsurface_scale = 0.003000; +uniform float King_W_subsurface_anisotropy = 0.000000; +uniform float King_W_sheen = 0.000000; +uniform vec3 King_W_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float King_W_sheen_roughness = 0.300000; +uniform float King_W_coat = 0.000000; +uniform vec3 King_W_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float King_W_coat_roughness = 0.100000; +uniform float King_W_coat_anisotropy = 0.000000; +uniform float King_W_coat_rotation = 0.000000; +uniform float King_W_coat_IOR = 1.500000; +uniform float King_W_coat_affect_color = 0.000000; +uniform float King_W_coat_affect_roughness = 0.000000; +uniform float King_W_thin_film_thickness = 0.000000; +uniform float King_W_thin_film_IOR = 1.500000; +uniform float King_W_emission = 0.000000; +uniform vec3 King_W_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 King_W_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool King_W_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 mtlximage7_out = vec3(0.0); + mx_image_color3(mtlximage7_file, mtlximage7_layer, mtlximage7_default, geomprop_UV0_out1, mtlximage7_uaddressmode, mtlximage7_vaddressmode, mtlximage7_filtertype, mtlximage7_framerange, mtlximage7_frameoffset, mtlximage7_frameendaction, mtlximage7_uv_scale, mtlximage7_uv_offset, mtlximage7_out); + float mtlximage10_out = 0.0; + mx_image_float(mtlximage10_file, mtlximage10_layer, mtlximage10_default, geomprop_UV0_out1, mtlximage10_uaddressmode, mtlximage10_vaddressmode, mtlximage10_filtertype, mtlximage10_framerange, mtlximage10_frameoffset, mtlximage10_frameendaction, mtlximage10_uv_scale, mtlximage10_uv_offset, mtlximage10_out); + float mtlximage11_out = 0.0; + mx_image_float(mtlximage11_file, mtlximage11_layer, mtlximage11_default, geomprop_UV0_out1, mtlximage11_uaddressmode, mtlximage11_vaddressmode, mtlximage11_filtertype, mtlximage11_framerange, mtlximage11_frameoffset, mtlximage11_frameendaction, mtlximage11_uv_scale, mtlximage11_uv_offset, mtlximage11_out); + float mtlximage8_out = 0.0; + mx_image_float(mtlximage8_file, mtlximage8_layer, mtlximage8_default, geomprop_UV0_out1, mtlximage8_uaddressmode, mtlximage8_vaddressmode, mtlximage8_filtertype, mtlximage8_framerange, mtlximage8_frameoffset, mtlximage8_frameendaction, mtlximage8_uv_scale, mtlximage8_uv_offset, mtlximage8_out); + vec3 mtlximage9_out = vec3(0.0); + mx_image_vector3(mtlximage9_file, mtlximage9_layer, mtlximage9_default, geomprop_UV0_out1, mtlximage9_uaddressmode, mtlximage9_vaddressmode, mtlximage9_filtertype, mtlximage9_framerange, mtlximage9_frameoffset, mtlximage9_frameendaction, mtlximage9_uv_scale, mtlximage9_uv_offset, mtlximage9_out); + vec3 mtlximage7_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(mtlximage7_out, mtlximage7_out_cm_out); + vec3 mtlxnormalmap11_out = vec3(0.0); + mx_normalmap_float(mtlximage9_out, mtlxnormalmap11_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap11_out); + surfaceshader King_W_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(King_W_base, mtlximage7_out_cm_out, King_W_diffuse_roughness, mtlximage10_out, King_W_specular, King_W_specular_color, mtlximage11_out, King_W_specular_IOR, King_W_specular_anisotropy, King_W_specular_rotation, King_W_transmission, King_W_transmission_color, King_W_transmission_depth, King_W_transmission_scatter, King_W_transmission_scatter_anisotropy, King_W_transmission_dispersion, King_W_transmission_extra_roughness, mtlximage8_out, mtlximage7_out_cm_out, mtlximage7_out_cm_out, King_W_subsurface_scale, King_W_subsurface_anisotropy, King_W_sheen, King_W_sheen_color, King_W_sheen_roughness, King_W_coat, King_W_coat_color, King_W_coat_roughness, King_W_coat_anisotropy, King_W_coat_rotation, King_W_coat_IOR, geomprop_Nworld_out1, King_W_coat_affect_color, King_W_coat_affect_roughness, King_W_thin_film_thickness, King_W_thin_film_IOR, King_W_emission, King_W_emission_color, King_W_opacity, King_W_thin_walled, mtlxnormalmap11_out, geomprop_Tworld_out1, King_W_out); + material M_King_W_out = King_W_out; + out1 = vec4(M_King_W_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_King_W.glsl.vert b/Materials/Examples/StandardSurface/M_King_W.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_King_W.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_King_W.mdl b/Materials/Examples/StandardSurface/M_King_W.mdl new file mode 100644 index 0000000000..28cee20351 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_King_W.mdl @@ -0,0 +1,539 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_King_W +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d mtlximage7_file = texture_2d("/chess_set/king_white_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KingWhite/mtlximage7/file") + ]], + uniform string mtlximage7_layer = "" + [[ + materialx::core::origin("NG_KingWhite/mtlximage7/layer") + ]], + color mtlximage7_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_KingWhite/mtlximage7/default") + ]], + uniform mx_addressmode_type mtlximage7_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingWhite/mtlximage7/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage7_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingWhite/mtlximage7/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage7_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KingWhite/mtlximage7/filtertype") + ]], + uniform string mtlximage7_framerange = "" + [[ + materialx::core::origin("NG_KingWhite/mtlximage7/framerange") + ]], + uniform int mtlximage7_frameoffset = 0 + [[ + materialx::core::origin("NG_KingWhite/mtlximage7/frameoffset") + ]], + uniform mx_addressmode_type mtlximage7_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KingWhite/mtlximage7/frameendaction") + ]], + uniform texture_2d mtlximage10_file = texture_2d("/chess_set/king_shared_metallic.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KingWhite/mtlximage10/file") + ]], + uniform string mtlximage10_layer = "" + [[ + materialx::core::origin("NG_KingWhite/mtlximage10/layer") + ]], + float mtlximage10_default = 0.000000 + [[ + materialx::core::origin("NG_KingWhite/mtlximage10/default") + ]], + uniform mx_addressmode_type mtlximage10_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingWhite/mtlximage10/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage10_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingWhite/mtlximage10/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage10_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KingWhite/mtlximage10/filtertype") + ]], + uniform string mtlximage10_framerange = "" + [[ + materialx::core::origin("NG_KingWhite/mtlximage10/framerange") + ]], + uniform int mtlximage10_frameoffset = 0 + [[ + materialx::core::origin("NG_KingWhite/mtlximage10/frameoffset") + ]], + uniform mx_addressmode_type mtlximage10_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KingWhite/mtlximage10/frameendaction") + ]], + uniform texture_2d mtlximage11_file = texture_2d("/chess_set/king_white_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KingWhite/mtlximage11/file") + ]], + uniform string mtlximage11_layer = "" + [[ + materialx::core::origin("NG_KingWhite/mtlximage11/layer") + ]], + float mtlximage11_default = 0.000000 + [[ + materialx::core::origin("NG_KingWhite/mtlximage11/default") + ]], + uniform mx_addressmode_type mtlximage11_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingWhite/mtlximage11/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage11_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingWhite/mtlximage11/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage11_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KingWhite/mtlximage11/filtertype") + ]], + uniform string mtlximage11_framerange = "" + [[ + materialx::core::origin("NG_KingWhite/mtlximage11/framerange") + ]], + uniform int mtlximage11_frameoffset = 0 + [[ + materialx::core::origin("NG_KingWhite/mtlximage11/frameoffset") + ]], + uniform mx_addressmode_type mtlximage11_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KingWhite/mtlximage11/frameendaction") + ]], + uniform texture_2d mtlximage8_file = texture_2d("/chess_set/king_shared_scattering.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KingWhite/mtlximage8/file") + ]], + uniform string mtlximage8_layer = "" + [[ + materialx::core::origin("NG_KingWhite/mtlximage8/layer") + ]], + float mtlximage8_default = 0.000000 + [[ + materialx::core::origin("NG_KingWhite/mtlximage8/default") + ]], + uniform mx_addressmode_type mtlximage8_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingWhite/mtlximage8/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage8_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingWhite/mtlximage8/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage8_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KingWhite/mtlximage8/filtertype") + ]], + uniform string mtlximage8_framerange = "" + [[ + materialx::core::origin("NG_KingWhite/mtlximage8/framerange") + ]], + uniform int mtlximage8_frameoffset = 0 + [[ + materialx::core::origin("NG_KingWhite/mtlximage8/frameoffset") + ]], + uniform mx_addressmode_type mtlximage8_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KingWhite/mtlximage8/frameendaction") + ]], + uniform texture_2d mtlximage9_file = texture_2d("/chess_set/king_white_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KingWhite/mtlximage9/file") + ]], + uniform string mtlximage9_layer = "" + [[ + materialx::core::origin("NG_KingWhite/mtlximage9/layer") + ]], + float3 mtlximage9_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_KingWhite/mtlximage9/default") + ]], + uniform mx_addressmode_type mtlximage9_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingWhite/mtlximage9/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage9_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KingWhite/mtlximage9/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage9_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KingWhite/mtlximage9/filtertype") + ]], + uniform string mtlximage9_framerange = "" + [[ + materialx::core::origin("NG_KingWhite/mtlximage9/framerange") + ]], + uniform int mtlximage9_frameoffset = 0 + [[ + materialx::core::origin("NG_KingWhite/mtlximage9/frameoffset") + ]], + uniform mx_addressmode_type mtlximage9_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KingWhite/mtlximage9/frameendaction") + ]], + float mtlxnormalmap11_scale = 1.000000 + [[ + materialx::core::origin("NG_KingWhite/mtlxnormalmap11/scale") + ]], + float King_W_base = 1.000000 + [[ + materialx::core::origin("King_W/base") + ]], + float King_W_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("King_W/diffuse_roughness") + ]], + float King_W_specular = 1.000000 + [[ + materialx::core::origin("King_W/specular") + ]], + color King_W_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("King_W/specular_color") + ]], + uniform float King_W_specular_IOR = 1.500000 + [[ + materialx::core::origin("King_W/specular_IOR") + ]], + float King_W_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("King_W/specular_anisotropy") + ]], + float King_W_specular_rotation = 0.000000 + [[ + materialx::core::origin("King_W/specular_rotation") + ]], + float King_W_transmission = 0.000000 + [[ + materialx::core::origin("King_W/transmission") + ]], + color King_W_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("King_W/transmission_color") + ]], + float King_W_transmission_depth = 0.000000 + [[ + materialx::core::origin("King_W/transmission_depth") + ]], + color King_W_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("King_W/transmission_scatter") + ]], + float King_W_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("King_W/transmission_scatter_anisotropy") + ]], + float King_W_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("King_W/transmission_dispersion") + ]], + float King_W_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("King_W/transmission_extra_roughness") + ]], + float King_W_subsurface_scale = 0.003000 + [[ + materialx::core::origin("King_W/subsurface_scale") + ]], + float King_W_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("King_W/subsurface_anisotropy") + ]], + float King_W_sheen = 0.000000 + [[ + materialx::core::origin("King_W/sheen") + ]], + color King_W_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("King_W/sheen_color") + ]], + float King_W_sheen_roughness = 0.300000 + [[ + materialx::core::origin("King_W/sheen_roughness") + ]], + float King_W_coat = 0.000000 + [[ + materialx::core::origin("King_W/coat") + ]], + color King_W_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("King_W/coat_color") + ]], + float King_W_coat_roughness = 0.100000 + [[ + materialx::core::origin("King_W/coat_roughness") + ]], + float King_W_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("King_W/coat_anisotropy") + ]], + float King_W_coat_rotation = 0.000000 + [[ + materialx::core::origin("King_W/coat_rotation") + ]], + uniform float King_W_coat_IOR = 1.500000 + [[ + materialx::core::origin("King_W/coat_IOR") + ]], + float King_W_coat_affect_color = 0.000000 + [[ + materialx::core::origin("King_W/coat_affect_color") + ]], + float King_W_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("King_W/coat_affect_roughness") + ]], + float King_W_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("King_W/thin_film_thickness") + ]], + float King_W_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("King_W/thin_film_IOR") + ]], + float King_W_emission = 0.000000 + [[ + materialx::core::origin("King_W/emission") + ]], + color King_W_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("King_W/emission_color") + ]], + color King_W_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("King_W/opacity") + ]], + bool King_W_thin_walled = false + [[ + materialx::core::origin("King_W/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color mtlximage7_out = materialx::stdlib_1_8::mx_image_color3(mtlximage7_file, mtlximage7_layer, mtlximage7_default, geomprop_UV0_out1, mtlximage7_uaddressmode, mtlximage7_vaddressmode, mtlximage7_filtertype, mtlximage7_framerange, mtlximage7_frameoffset, mtlximage7_frameendaction, mxp_flip_v:false); + float mtlximage10_out = materialx::stdlib_1_8::mx_image_float(mtlximage10_file, mtlximage10_layer, mtlximage10_default, geomprop_UV0_out1, mtlximage10_uaddressmode, mtlximage10_vaddressmode, mtlximage10_filtertype, mtlximage10_framerange, mtlximage10_frameoffset, mtlximage10_frameendaction, mxp_flip_v:false); + float mtlximage11_out = materialx::stdlib_1_8::mx_image_float(mtlximage11_file, mtlximage11_layer, mtlximage11_default, geomprop_UV0_out1, mtlximage11_uaddressmode, mtlximage11_vaddressmode, mtlximage11_filtertype, mtlximage11_framerange, mtlximage11_frameoffset, mtlximage11_frameendaction, mxp_flip_v:false); + float mtlximage8_out = materialx::stdlib_1_8::mx_image_float(mtlximage8_file, mtlximage8_layer, mtlximage8_default, geomprop_UV0_out1, mtlximage8_uaddressmode, mtlximage8_vaddressmode, mtlximage8_filtertype, mtlximage8_framerange, mtlximage8_frameoffset, mtlximage8_frameendaction, mxp_flip_v:false); + float3 mtlximage9_out = materialx::stdlib_1_8::mx_image_vector3(mtlximage9_file, mtlximage9_layer, mtlximage9_default, geomprop_UV0_out1, mtlximage9_uaddressmode, mtlximage9_vaddressmode, mtlximage9_filtertype, mtlximage9_framerange, mtlximage9_frameoffset, mtlximage9_frameendaction, mxp_flip_v:false); + color mtlximage7_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(mtlximage7_out); + float3 mtlxnormalmap11_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:mtlximage9_out, mxp_scale:mtlxnormalmap11_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material King_W_out = NG_standard_surface_surfaceshader_100(King_W_base, mtlximage7_out_cm_out, King_W_diffuse_roughness, mtlximage10_out, King_W_specular, King_W_specular_color, mtlximage11_out, King_W_specular_IOR, King_W_specular_anisotropy, King_W_specular_rotation, King_W_transmission, King_W_transmission_color, King_W_transmission_depth, King_W_transmission_scatter, King_W_transmission_scatter_anisotropy, King_W_transmission_dispersion, King_W_transmission_extra_roughness, mtlximage8_out, mtlximage7_out_cm_out, mtlximage7_out_cm_out, King_W_subsurface_scale, King_W_subsurface_anisotropy, King_W_sheen, King_W_sheen_color, King_W_sheen_roughness, King_W_coat, King_W_coat_color, King_W_coat_roughness, King_W_coat_anisotropy, King_W_coat_rotation, King_W_coat_IOR, geomprop_Nworld_out1, King_W_coat_affect_color, King_W_coat_affect_roughness, King_W_thin_film_thickness, King_W_thin_film_IOR, King_W_emission, King_W_emission_color, King_W_opacity, King_W_thin_walled, mtlxnormalmap11_out, geomprop_Tworld_out1); + material M_King_W_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: King_W_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_King_W_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_King_W.msl.frag b/Materials/Examples/StandardSurface/M_King_W.msl.frag new file mode 100644 index 0000000000..ee9ea26f72 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_King_W.msl.frag @@ -0,0 +1,3049 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int mtlximage7_layer; + vec3 mtlximage7_default; + int mtlximage7_uaddressmode; + int mtlximage7_vaddressmode; + int mtlximage7_filtertype; + int mtlximage7_framerange; + int mtlximage7_frameoffset; + int mtlximage7_frameendaction; + vec2 mtlximage7_uv_scale; + vec2 mtlximage7_uv_offset; + int mtlximage10_layer; + float mtlximage10_default; + int mtlximage10_uaddressmode; + int mtlximage10_vaddressmode; + int mtlximage10_filtertype; + int mtlximage10_framerange; + int mtlximage10_frameoffset; + int mtlximage10_frameendaction; + vec2 mtlximage10_uv_scale; + vec2 mtlximage10_uv_offset; + int mtlximage11_layer; + float mtlximage11_default; + int mtlximage11_uaddressmode; + int mtlximage11_vaddressmode; + int mtlximage11_filtertype; + int mtlximage11_framerange; + int mtlximage11_frameoffset; + int mtlximage11_frameendaction; + vec2 mtlximage11_uv_scale; + vec2 mtlximage11_uv_offset; + int mtlximage8_layer; + float mtlximage8_default; + int mtlximage8_uaddressmode; + int mtlximage8_vaddressmode; + int mtlximage8_filtertype; + int mtlximage8_framerange; + int mtlximage8_frameoffset; + int mtlximage8_frameendaction; + vec2 mtlximage8_uv_scale; + vec2 mtlximage8_uv_offset; + int mtlximage9_layer; + vec3 mtlximage9_default; + int mtlximage9_uaddressmode; + int mtlximage9_vaddressmode; + int mtlximage9_filtertype; + int mtlximage9_framerange; + int mtlximage9_frameoffset; + int mtlximage9_frameendaction; + vec2 mtlximage9_uv_scale; + vec2 mtlximage9_uv_offset; + float mtlxnormalmap11_scale; + float King_W_base; + float King_W_diffuse_roughness; + float King_W_specular; + vec3 King_W_specular_color; + float King_W_specular_IOR; + float King_W_specular_anisotropy; + float King_W_specular_rotation; + float King_W_transmission; + vec3 King_W_transmission_color; + float King_W_transmission_depth; + vec3 King_W_transmission_scatter; + float King_W_transmission_scatter_anisotropy; + float King_W_transmission_dispersion; + float King_W_transmission_extra_roughness; + float King_W_subsurface_scale; + float King_W_subsurface_anisotropy; + float King_W_sheen; + vec3 King_W_sheen_color; + float King_W_sheen_roughness; + float King_W_coat; + vec3 King_W_coat_color; + float King_W_coat_roughness; + float King_W_coat_anisotropy; + float King_W_coat_rotation; + float King_W_coat_IOR; + float King_W_coat_affect_color; + float King_W_coat_affect_roughness; + float King_W_thin_film_thickness; + float King_W_thin_film_IOR; + float King_W_emission; + vec3 King_W_emission_color; + vec3 King_W_opacity; + bool King_W_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture mtlximage7_file , int mtlximage7_layer + + , vec3 mtlximage7_default + + , int mtlximage7_uaddressmode + + , int mtlximage7_vaddressmode + + , int mtlximage7_filtertype + + , int mtlximage7_framerange + + , int mtlximage7_frameoffset + + , int mtlximage7_frameendaction + + , vec2 mtlximage7_uv_scale + + , vec2 mtlximage7_uv_offset + +, MetalTexture mtlximage10_file , int mtlximage10_layer + + , float mtlximage10_default + + , int mtlximage10_uaddressmode + + , int mtlximage10_vaddressmode + + , int mtlximage10_filtertype + + , int mtlximage10_framerange + + , int mtlximage10_frameoffset + + , int mtlximage10_frameendaction + + , vec2 mtlximage10_uv_scale + + , vec2 mtlximage10_uv_offset + +, MetalTexture mtlximage11_file , int mtlximage11_layer + + , float mtlximage11_default + + , int mtlximage11_uaddressmode + + , int mtlximage11_vaddressmode + + , int mtlximage11_filtertype + + , int mtlximage11_framerange + + , int mtlximage11_frameoffset + + , int mtlximage11_frameendaction + + , vec2 mtlximage11_uv_scale + + , vec2 mtlximage11_uv_offset + +, MetalTexture mtlximage8_file , int mtlximage8_layer + + , float mtlximage8_default + + , int mtlximage8_uaddressmode + + , int mtlximage8_vaddressmode + + , int mtlximage8_filtertype + + , int mtlximage8_framerange + + , int mtlximage8_frameoffset + + , int mtlximage8_frameendaction + + , vec2 mtlximage8_uv_scale + + , vec2 mtlximage8_uv_offset + +, MetalTexture mtlximage9_file , int mtlximage9_layer + + , vec3 mtlximage9_default + + , int mtlximage9_uaddressmode + + , int mtlximage9_vaddressmode + + , int mtlximage9_filtertype + + , int mtlximage9_framerange + + , int mtlximage9_frameoffset + + , int mtlximage9_frameendaction + + , vec2 mtlximage9_uv_scale + + , vec2 mtlximage9_uv_offset + + , float mtlxnormalmap11_scale + + , float King_W_base + + , float King_W_diffuse_roughness + + , float King_W_specular + + , vec3 King_W_specular_color + + , float King_W_specular_IOR + + , float King_W_specular_anisotropy + + , float King_W_specular_rotation + + , float King_W_transmission + + , vec3 King_W_transmission_color + + , float King_W_transmission_depth + + , vec3 King_W_transmission_scatter + + , float King_W_transmission_scatter_anisotropy + + , float King_W_transmission_dispersion + + , float King_W_transmission_extra_roughness + + , float King_W_subsurface_scale + + , float King_W_subsurface_anisotropy + + , float King_W_sheen + + , vec3 King_W_sheen_color + + , float King_W_sheen_roughness + + , float King_W_coat + + , vec3 King_W_coat_color + + , float King_W_coat_roughness + + , float King_W_coat_anisotropy + + , float King_W_coat_rotation + + , float King_W_coat_IOR + + , float King_W_coat_affect_color + + , float King_W_coat_affect_roughness + + , float King_W_thin_film_thickness + + , float King_W_thin_film_IOR + + , float King_W_emission + + , vec3 King_W_emission_color + + , vec3 King_W_opacity + + , bool King_W_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, mtlximage7_file(mtlximage7_file) + , mtlximage7_layer(mtlximage7_layer) + + , mtlximage7_default(mtlximage7_default) + + , mtlximage7_uaddressmode(mtlximage7_uaddressmode) + + , mtlximage7_vaddressmode(mtlximage7_vaddressmode) + + , mtlximage7_filtertype(mtlximage7_filtertype) + + , mtlximage7_framerange(mtlximage7_framerange) + + , mtlximage7_frameoffset(mtlximage7_frameoffset) + + , mtlximage7_frameendaction(mtlximage7_frameendaction) + + , mtlximage7_uv_scale(mtlximage7_uv_scale) + + , mtlximage7_uv_offset(mtlximage7_uv_offset) + +, mtlximage10_file(mtlximage10_file) + , mtlximage10_layer(mtlximage10_layer) + + , mtlximage10_default(mtlximage10_default) + + , mtlximage10_uaddressmode(mtlximage10_uaddressmode) + + , mtlximage10_vaddressmode(mtlximage10_vaddressmode) + + , mtlximage10_filtertype(mtlximage10_filtertype) + + , mtlximage10_framerange(mtlximage10_framerange) + + , mtlximage10_frameoffset(mtlximage10_frameoffset) + + , mtlximage10_frameendaction(mtlximage10_frameendaction) + + , mtlximage10_uv_scale(mtlximage10_uv_scale) + + , mtlximage10_uv_offset(mtlximage10_uv_offset) + +, mtlximage11_file(mtlximage11_file) + , mtlximage11_layer(mtlximage11_layer) + + , mtlximage11_default(mtlximage11_default) + + , mtlximage11_uaddressmode(mtlximage11_uaddressmode) + + , mtlximage11_vaddressmode(mtlximage11_vaddressmode) + + , mtlximage11_filtertype(mtlximage11_filtertype) + + , mtlximage11_framerange(mtlximage11_framerange) + + , mtlximage11_frameoffset(mtlximage11_frameoffset) + + , mtlximage11_frameendaction(mtlximage11_frameendaction) + + , mtlximage11_uv_scale(mtlximage11_uv_scale) + + , mtlximage11_uv_offset(mtlximage11_uv_offset) + +, mtlximage8_file(mtlximage8_file) + , mtlximage8_layer(mtlximage8_layer) + + , mtlximage8_default(mtlximage8_default) + + , mtlximage8_uaddressmode(mtlximage8_uaddressmode) + + , mtlximage8_vaddressmode(mtlximage8_vaddressmode) + + , mtlximage8_filtertype(mtlximage8_filtertype) + + , mtlximage8_framerange(mtlximage8_framerange) + + , mtlximage8_frameoffset(mtlximage8_frameoffset) + + , mtlximage8_frameendaction(mtlximage8_frameendaction) + + , mtlximage8_uv_scale(mtlximage8_uv_scale) + + , mtlximage8_uv_offset(mtlximage8_uv_offset) + +, mtlximage9_file(mtlximage9_file) + , mtlximage9_layer(mtlximage9_layer) + + , mtlximage9_default(mtlximage9_default) + + , mtlximage9_uaddressmode(mtlximage9_uaddressmode) + + , mtlximage9_vaddressmode(mtlximage9_vaddressmode) + + , mtlximage9_filtertype(mtlximage9_filtertype) + + , mtlximage9_framerange(mtlximage9_framerange) + + , mtlximage9_frameoffset(mtlximage9_frameoffset) + + , mtlximage9_frameendaction(mtlximage9_frameendaction) + + , mtlximage9_uv_scale(mtlximage9_uv_scale) + + , mtlximage9_uv_offset(mtlximage9_uv_offset) + + , mtlxnormalmap11_scale(mtlxnormalmap11_scale) + + , King_W_base(King_W_base) + + , King_W_diffuse_roughness(King_W_diffuse_roughness) + + , King_W_specular(King_W_specular) + + , King_W_specular_color(King_W_specular_color) + + , King_W_specular_IOR(King_W_specular_IOR) + + , King_W_specular_anisotropy(King_W_specular_anisotropy) + + , King_W_specular_rotation(King_W_specular_rotation) + + , King_W_transmission(King_W_transmission) + + , King_W_transmission_color(King_W_transmission_color) + + , King_W_transmission_depth(King_W_transmission_depth) + + , King_W_transmission_scatter(King_W_transmission_scatter) + + , King_W_transmission_scatter_anisotropy(King_W_transmission_scatter_anisotropy) + + , King_W_transmission_dispersion(King_W_transmission_dispersion) + + , King_W_transmission_extra_roughness(King_W_transmission_extra_roughness) + + , King_W_subsurface_scale(King_W_subsurface_scale) + + , King_W_subsurface_anisotropy(King_W_subsurface_anisotropy) + + , King_W_sheen(King_W_sheen) + + , King_W_sheen_color(King_W_sheen_color) + + , King_W_sheen_roughness(King_W_sheen_roughness) + + , King_W_coat(King_W_coat) + + , King_W_coat_color(King_W_coat_color) + + , King_W_coat_roughness(King_W_coat_roughness) + + , King_W_coat_anisotropy(King_W_coat_anisotropy) + + , King_W_coat_rotation(King_W_coat_rotation) + + , King_W_coat_IOR(King_W_coat_IOR) + + , King_W_coat_affect_color(King_W_coat_affect_color) + + , King_W_coat_affect_roughness(King_W_coat_affect_roughness) + + , King_W_thin_film_thickness(King_W_thin_film_thickness) + + , King_W_thin_film_IOR(King_W_thin_film_IOR) + + , King_W_emission(King_W_emission) + + , King_W_emission_color(King_W_emission_color) + + , King_W_opacity(King_W_opacity) + + , King_W_thin_walled(King_W_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture mtlximage7_file; + int mtlximage7_layer; + + + vec3 mtlximage7_default; + + + int mtlximage7_uaddressmode; + + + int mtlximage7_vaddressmode; + + + int mtlximage7_filtertype; + + + int mtlximage7_framerange; + + + int mtlximage7_frameoffset; + + + int mtlximage7_frameendaction; + + + vec2 mtlximage7_uv_scale; + + + vec2 mtlximage7_uv_offset; + + +MetalTexture mtlximage10_file; + int mtlximage10_layer; + + + float mtlximage10_default; + + + int mtlximage10_uaddressmode; + + + int mtlximage10_vaddressmode; + + + int mtlximage10_filtertype; + + + int mtlximage10_framerange; + + + int mtlximage10_frameoffset; + + + int mtlximage10_frameendaction; + + + vec2 mtlximage10_uv_scale; + + + vec2 mtlximage10_uv_offset; + + +MetalTexture mtlximage11_file; + int mtlximage11_layer; + + + float mtlximage11_default; + + + int mtlximage11_uaddressmode; + + + int mtlximage11_vaddressmode; + + + int mtlximage11_filtertype; + + + int mtlximage11_framerange; + + + int mtlximage11_frameoffset; + + + int mtlximage11_frameendaction; + + + vec2 mtlximage11_uv_scale; + + + vec2 mtlximage11_uv_offset; + + +MetalTexture mtlximage8_file; + int mtlximage8_layer; + + + float mtlximage8_default; + + + int mtlximage8_uaddressmode; + + + int mtlximage8_vaddressmode; + + + int mtlximage8_filtertype; + + + int mtlximage8_framerange; + + + int mtlximage8_frameoffset; + + + int mtlximage8_frameendaction; + + + vec2 mtlximage8_uv_scale; + + + vec2 mtlximage8_uv_offset; + + +MetalTexture mtlximage9_file; + int mtlximage9_layer; + + + vec3 mtlximage9_default; + + + int mtlximage9_uaddressmode; + + + int mtlximage9_vaddressmode; + + + int mtlximage9_filtertype; + + + int mtlximage9_framerange; + + + int mtlximage9_frameoffset; + + + int mtlximage9_frameendaction; + + + vec2 mtlximage9_uv_scale; + + + vec2 mtlximage9_uv_offset; + + + float mtlxnormalmap11_scale; + + + float King_W_base; + + + float King_W_diffuse_roughness; + + + float King_W_specular; + + + vec3 King_W_specular_color; + + + float King_W_specular_IOR; + + + float King_W_specular_anisotropy; + + + float King_W_specular_rotation; + + + float King_W_transmission; + + + vec3 King_W_transmission_color; + + + float King_W_transmission_depth; + + + vec3 King_W_transmission_scatter; + + + float King_W_transmission_scatter_anisotropy; + + + float King_W_transmission_dispersion; + + + float King_W_transmission_extra_roughness; + + + float King_W_subsurface_scale; + + + float King_W_subsurface_anisotropy; + + + float King_W_sheen; + + + vec3 King_W_sheen_color; + + + float King_W_sheen_roughness; + + + float King_W_coat; + + + vec3 King_W_coat_color; + + + float King_W_coat_roughness; + + + float King_W_coat_anisotropy; + + + float King_W_coat_rotation; + + + float King_W_coat_IOR; + + + float King_W_coat_affect_color; + + + float King_W_coat_affect_roughness; + + + float King_W_thin_film_thickness; + + + float King_W_thin_film_IOR; + + + float King_W_emission; + + + vec3 King_W_emission_color; + + + vec3 King_W_opacity; + + + bool King_W_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 mtlximage7_out = vec3(0.0); + mx_image_color3(mtlximage7_file, mtlximage7_layer, mtlximage7_default, geomprop_UV0_out1, mtlximage7_uaddressmode, mtlximage7_vaddressmode, mtlximage7_filtertype, mtlximage7_framerange, mtlximage7_frameoffset, mtlximage7_frameendaction, mtlximage7_uv_scale, mtlximage7_uv_offset, mtlximage7_out); + float mtlximage10_out = 0.0; + mx_image_float(mtlximage10_file, mtlximage10_layer, mtlximage10_default, geomprop_UV0_out1, mtlximage10_uaddressmode, mtlximage10_vaddressmode, mtlximage10_filtertype, mtlximage10_framerange, mtlximage10_frameoffset, mtlximage10_frameendaction, mtlximage10_uv_scale, mtlximage10_uv_offset, mtlximage10_out); + float mtlximage11_out = 0.0; + mx_image_float(mtlximage11_file, mtlximage11_layer, mtlximage11_default, geomprop_UV0_out1, mtlximage11_uaddressmode, mtlximage11_vaddressmode, mtlximage11_filtertype, mtlximage11_framerange, mtlximage11_frameoffset, mtlximage11_frameendaction, mtlximage11_uv_scale, mtlximage11_uv_offset, mtlximage11_out); + float mtlximage8_out = 0.0; + mx_image_float(mtlximage8_file, mtlximage8_layer, mtlximage8_default, geomprop_UV0_out1, mtlximage8_uaddressmode, mtlximage8_vaddressmode, mtlximage8_filtertype, mtlximage8_framerange, mtlximage8_frameoffset, mtlximage8_frameendaction, mtlximage8_uv_scale, mtlximage8_uv_offset, mtlximage8_out); + vec3 mtlximage9_out = vec3(0.0); + mx_image_vector3(mtlximage9_file, mtlximage9_layer, mtlximage9_default, geomprop_UV0_out1, mtlximage9_uaddressmode, mtlximage9_vaddressmode, mtlximage9_filtertype, mtlximage9_framerange, mtlximage9_frameoffset, mtlximage9_frameendaction, mtlximage9_uv_scale, mtlximage9_uv_offset, mtlximage9_out); + vec3 mtlximage7_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(mtlximage7_out, mtlximage7_out_cm_out); + vec3 mtlxnormalmap11_out = vec3(0.0); + mx_normalmap_float(mtlximage9_out, mtlxnormalmap11_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap11_out); + surfaceshader King_W_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(King_W_base, mtlximage7_out_cm_out, King_W_diffuse_roughness, mtlximage10_out, King_W_specular, King_W_specular_color, mtlximage11_out, King_W_specular_IOR, King_W_specular_anisotropy, King_W_specular_rotation, King_W_transmission, King_W_transmission_color, King_W_transmission_depth, King_W_transmission_scatter, King_W_transmission_scatter_anisotropy, King_W_transmission_dispersion, King_W_transmission_extra_roughness, mtlximage8_out, mtlximage7_out_cm_out, mtlximage7_out_cm_out, King_W_subsurface_scale, King_W_subsurface_anisotropy, King_W_sheen, King_W_sheen_color, King_W_sheen_roughness, King_W_coat, King_W_coat_color, King_W_coat_roughness, King_W_coat_anisotropy, King_W_coat_rotation, King_W_coat_IOR, geomprop_Nworld_out1, King_W_coat_affect_color, King_W_coat_affect_roughness, King_W_thin_film_thickness, King_W_thin_film_IOR, King_W_emission, King_W_emission_color, King_W_opacity, King_W_thin_walled, mtlxnormalmap11_out, geomprop_Tworld_out1, King_W_out); + material M_King_W_out = King_W_out; + out1 = float4(M_King_W_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d mtlximage7_file_tex [[texture(0)]], sampler mtlximage7_file_sampler [[sampler(0)]] +, texture2d mtlximage10_file_tex [[texture(1)]], sampler mtlximage10_file_sampler [[sampler(1)]] +, texture2d mtlximage11_file_tex [[texture(2)]], sampler mtlximage11_file_sampler [[sampler(2)]] +, texture2d mtlximage8_file_tex [[texture(3)]], sampler mtlximage8_file_sampler [[sampler(3)]] +, texture2d mtlximage9_file_tex [[texture(4)]], sampler mtlximage9_file_sampler [[sampler(4)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(5)]], sampler u_envRadiance_sampler [[sampler(5)]] +, texture2d u_envIrradiance_tex [[texture(6)]], sampler u_envIrradiance_sampler [[sampler(6)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +mtlximage7_file_tex, mtlximage7_file_sampler } + , u_pub.mtlximage7_layer + , u_pub.mtlximage7_default + , u_pub.mtlximage7_uaddressmode + , u_pub.mtlximage7_vaddressmode + , u_pub.mtlximage7_filtertype + , u_pub.mtlximage7_framerange + , u_pub.mtlximage7_frameoffset + , u_pub.mtlximage7_frameendaction + , u_pub.mtlximage7_uv_scale + , u_pub.mtlximage7_uv_offset +, MetalTexture { +mtlximage10_file_tex, mtlximage10_file_sampler } + , u_pub.mtlximage10_layer + , u_pub.mtlximage10_default + , u_pub.mtlximage10_uaddressmode + , u_pub.mtlximage10_vaddressmode + , u_pub.mtlximage10_filtertype + , u_pub.mtlximage10_framerange + , u_pub.mtlximage10_frameoffset + , u_pub.mtlximage10_frameendaction + , u_pub.mtlximage10_uv_scale + , u_pub.mtlximage10_uv_offset +, MetalTexture { +mtlximage11_file_tex, mtlximage11_file_sampler } + , u_pub.mtlximage11_layer + , u_pub.mtlximage11_default + , u_pub.mtlximage11_uaddressmode + , u_pub.mtlximage11_vaddressmode + , u_pub.mtlximage11_filtertype + , u_pub.mtlximage11_framerange + , u_pub.mtlximage11_frameoffset + , u_pub.mtlximage11_frameendaction + , u_pub.mtlximage11_uv_scale + , u_pub.mtlximage11_uv_offset +, MetalTexture { +mtlximage8_file_tex, mtlximage8_file_sampler } + , u_pub.mtlximage8_layer + , u_pub.mtlximage8_default + , u_pub.mtlximage8_uaddressmode + , u_pub.mtlximage8_vaddressmode + , u_pub.mtlximage8_filtertype + , u_pub.mtlximage8_framerange + , u_pub.mtlximage8_frameoffset + , u_pub.mtlximage8_frameendaction + , u_pub.mtlximage8_uv_scale + , u_pub.mtlximage8_uv_offset +, MetalTexture { +mtlximage9_file_tex, mtlximage9_file_sampler } + , u_pub.mtlximage9_layer + , u_pub.mtlximage9_default + , u_pub.mtlximage9_uaddressmode + , u_pub.mtlximage9_vaddressmode + , u_pub.mtlximage9_filtertype + , u_pub.mtlximage9_framerange + , u_pub.mtlximage9_frameoffset + , u_pub.mtlximage9_frameendaction + , u_pub.mtlximage9_uv_scale + , u_pub.mtlximage9_uv_offset + , u_pub.mtlxnormalmap11_scale + , u_pub.King_W_base + , u_pub.King_W_diffuse_roughness + , u_pub.King_W_specular + , u_pub.King_W_specular_color + , u_pub.King_W_specular_IOR + , u_pub.King_W_specular_anisotropy + , u_pub.King_W_specular_rotation + , u_pub.King_W_transmission + , u_pub.King_W_transmission_color + , u_pub.King_W_transmission_depth + , u_pub.King_W_transmission_scatter + , u_pub.King_W_transmission_scatter_anisotropy + , u_pub.King_W_transmission_dispersion + , u_pub.King_W_transmission_extra_roughness + , u_pub.King_W_subsurface_scale + , u_pub.King_W_subsurface_anisotropy + , u_pub.King_W_sheen + , u_pub.King_W_sheen_color + , u_pub.King_W_sheen_roughness + , u_pub.King_W_coat + , u_pub.King_W_coat_color + , u_pub.King_W_coat_roughness + , u_pub.King_W_coat_anisotropy + , u_pub.King_W_coat_rotation + , u_pub.King_W_coat_IOR + , u_pub.King_W_coat_affect_color + , u_pub.King_W_coat_affect_roughness + , u_pub.King_W_thin_film_thickness + , u_pub.King_W_thin_film_IOR + , u_pub.King_W_emission + , u_pub.King_W_emission_color + , u_pub.King_W_opacity + , u_pub.King_W_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_King_W.msl.vert b/Materials/Examples/StandardSurface/M_King_W.msl.vert new file mode 100644 index 0000000000..3840ac1e37 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_King_W.msl.vert @@ -0,0 +1,128 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'mtlximage7'. Function already called in this scope. + // Omitted node 'mtlximage10'. Function already called in this scope. + // Omitted node 'mtlximage11'. Function already called in this scope. + // Omitted node 'mtlximage8'. Function already called in this scope. + // Omitted node 'mtlximage9'. Function already called in this scope. + // Omitted node 'mtlximage7_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap11'. Function already called in this scope. + // Omitted node 'King_W'. Function already called in this scope. + // Omitted node 'M_King_W'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_King_W.osl b/Materials/Examples/StandardSurface/M_King_W.osl new file mode 100644 index 0000000000..6e5ece2fe6 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_King_W.osl @@ -0,0 +1,699 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_King_W +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_King_W" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string mtlximage7_file = "chess_set/king_white_base_color.jpg" + [[ + string widget = "filename" + ]], + string mtlximage7_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage7_layer = "", + color mtlximage7_default = color(0.000000, 0.000000, 0.000000), + string mtlximage7_uaddressmode = "periodic", + string mtlximage7_vaddressmode = "periodic", + string mtlximage7_filtertype = "linear", + string mtlximage7_framerange = "", + int mtlximage7_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage7_frameendaction = "constant", + string mtlximage10_file = "chess_set/king_shared_metallic.jpg" + [[ + string widget = "filename" + ]], + string mtlximage10_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage10_layer = "", + float mtlximage10_default = 0.000000 + [[ + string widget = "number" + ]], + string mtlximage10_uaddressmode = "periodic", + string mtlximage10_vaddressmode = "periodic", + string mtlximage10_filtertype = "linear", + string mtlximage10_framerange = "", + int mtlximage10_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage10_frameendaction = "constant", + string mtlximage11_file = "chess_set/king_white_roughness.jpg" + [[ + string widget = "filename" + ]], + string mtlximage11_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage11_layer = "", + float mtlximage11_default = 0.000000 + [[ + string widget = "number" + ]], + string mtlximage11_uaddressmode = "periodic", + string mtlximage11_vaddressmode = "periodic", + string mtlximage11_filtertype = "linear", + string mtlximage11_framerange = "", + int mtlximage11_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage11_frameendaction = "constant", + string mtlximage8_file = "chess_set/king_shared_scattering.jpg" + [[ + string widget = "filename" + ]], + string mtlximage8_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage8_layer = "", + float mtlximage8_default = 0.000000 + [[ + string widget = "number" + ]], + string mtlximage8_uaddressmode = "periodic", + string mtlximage8_vaddressmode = "periodic", + string mtlximage8_filtertype = "linear", + string mtlximage8_framerange = "", + int mtlximage8_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage8_frameendaction = "constant", + string mtlximage9_file = "chess_set/king_white_normal.jpg" + [[ + string widget = "filename" + ]], + string mtlximage9_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage9_layer = "", + vector mtlximage9_default = vector(0.000000, 0.000000, 0.000000), + string mtlximage9_uaddressmode = "periodic", + string mtlximage9_vaddressmode = "periodic", + string mtlximage9_filtertype = "linear", + string mtlximage9_framerange = "", + int mtlximage9_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage9_frameendaction = "constant", + float mtlxnormalmap11_scale = 1.000000 + [[ + string widget = "number" + ]], + float King_W_base = 1.000000 + [[ + string widget = "number" + ]], + float King_W_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float King_W_specular = 1.000000 + [[ + string widget = "number" + ]], + color King_W_specular_color = color(1.000000, 1.000000, 1.000000), + float King_W_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float King_W_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float King_W_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float King_W_transmission = 0.000000 + [[ + string widget = "number" + ]], + color King_W_transmission_color = color(1.000000, 1.000000, 1.000000), + float King_W_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color King_W_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float King_W_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float King_W_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float King_W_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float King_W_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float King_W_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float King_W_sheen = 0.000000 + [[ + string widget = "number" + ]], + color King_W_sheen_color = color(1.000000, 1.000000, 1.000000), + float King_W_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float King_W_coat = 0.000000 + [[ + string widget = "number" + ]], + color King_W_coat_color = color(1.000000, 1.000000, 1.000000), + float King_W_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float King_W_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float King_W_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float King_W_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float King_W_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float King_W_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float King_W_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float King_W_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float King_W_emission = 0.000000 + [[ + string widget = "number" + ]], + color King_W_emission_color = color(1.000000, 1.000000, 1.000000), + color King_W_opacity = color(1.000000, 1.000000, 1.000000), + int King_W_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource mtlximage7_file_ = {mtlximage7_file, mtlximage7_file_colorspace}; + textureresource mtlximage10_file_ = {mtlximage10_file, mtlximage10_file_colorspace}; + textureresource mtlximage11_file_ = {mtlximage11_file, mtlximage11_file_colorspace}; + textureresource mtlximage8_file_ = {mtlximage8_file, mtlximage8_file_colorspace}; + textureresource mtlximage9_file_ = {mtlximage9_file, mtlximage9_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color mtlximage7_out = color(0.0); + mx_image_color3(mtlximage7_file_, mtlximage7_layer, mtlximage7_default, geomprop_UV0_out1, mtlximage7_uaddressmode, mtlximage7_vaddressmode, mtlximage7_filtertype, mtlximage7_framerange, mtlximage7_frameoffset, mtlximage7_frameendaction, mtlximage7_out); + float mtlximage10_out = 0.0; + mx_image_float(mtlximage10_file_, mtlximage10_layer, mtlximage10_default, geomprop_UV0_out1, mtlximage10_uaddressmode, mtlximage10_vaddressmode, mtlximage10_filtertype, mtlximage10_framerange, mtlximage10_frameoffset, mtlximage10_frameendaction, mtlximage10_out); + float mtlximage11_out = 0.0; + mx_image_float(mtlximage11_file_, mtlximage11_layer, mtlximage11_default, geomprop_UV0_out1, mtlximage11_uaddressmode, mtlximage11_vaddressmode, mtlximage11_filtertype, mtlximage11_framerange, mtlximage11_frameoffset, mtlximage11_frameendaction, mtlximage11_out); + float mtlximage8_out = 0.0; + mx_image_float(mtlximage8_file_, mtlximage8_layer, mtlximage8_default, geomprop_UV0_out1, mtlximage8_uaddressmode, mtlximage8_vaddressmode, mtlximage8_filtertype, mtlximage8_framerange, mtlximage8_frameoffset, mtlximage8_frameendaction, mtlximage8_out); + vector mtlximage9_out = vector(0.0); + mx_image_vector3(mtlximage9_file_, mtlximage9_layer, mtlximage9_default, geomprop_UV0_out1, mtlximage9_uaddressmode, mtlximage9_vaddressmode, mtlximage9_filtertype, mtlximage9_framerange, mtlximage9_frameoffset, mtlximage9_frameendaction, mtlximage9_out); + color mtlximage7_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(mtlximage7_out, mtlximage7_out_cm_out); + vector mtlxnormalmap11_out = vector(0.0); + mx_normalmap_float(mtlximage9_out, mtlxnormalmap11_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap11_out); + surfaceshader King_W_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(King_W_base, mtlximage7_out_cm_out, King_W_diffuse_roughness, mtlximage10_out, King_W_specular, King_W_specular_color, mtlximage11_out, King_W_specular_IOR, King_W_specular_anisotropy, King_W_specular_rotation, King_W_transmission, King_W_transmission_color, King_W_transmission_depth, King_W_transmission_scatter, King_W_transmission_scatter_anisotropy, King_W_transmission_dispersion, King_W_transmission_extra_roughness, mtlximage8_out, mtlximage7_out_cm_out, mtlximage7_out_cm_out, King_W_subsurface_scale, King_W_subsurface_anisotropy, King_W_sheen, King_W_sheen_color, King_W_sheen_roughness, King_W_coat, King_W_coat_color, King_W_coat_roughness, King_W_coat_anisotropy, King_W_coat_rotation, King_W_coat_IOR, geomprop_Nworld_out1, King_W_coat_affect_color, King_W_coat_affect_roughness, King_W_thin_film_thickness, King_W_thin_film_IOR, King_W_emission, King_W_emission_color, King_W_opacity, King_W_thin_walled, mtlxnormalmap11_out, geomprop_Tworld_out1, King_W_out); + MATERIAL M_King_W_out = mx_surfacematerial(King_W_out, backsurfaceshader, displacementshader1); + out = M_King_W_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Knight_B.glsl.frag b/Materials/Examples/StandardSurface/M_Knight_B.glsl.frag new file mode 100644 index 0000000000..b1d0425011 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Knight_B.glsl.frag @@ -0,0 +1,2001 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D diffuse4_file; +uniform int diffuse4_layer = 0; +uniform vec3 diffuse4_default = vec3(0.000000, 0.000000, 0.000000); +uniform int diffuse4_uaddressmode = 2; +uniform int diffuse4_vaddressmode = 2; +uniform int diffuse4_filtertype = 1; +uniform int diffuse4_framerange = 0; +uniform int diffuse4_frameoffset = 0; +uniform int diffuse4_frameendaction = 0; +uniform vec2 diffuse4_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 diffuse4_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D roughness4_file; +uniform int roughness4_layer = 0; +uniform float roughness4_default = 0.000000; +uniform int roughness4_uaddressmode = 2; +uniform int roughness4_vaddressmode = 2; +uniform int roughness4_filtertype = 1; +uniform int roughness4_framerange = 0; +uniform int roughness4_frameoffset = 0; +uniform int roughness4_frameendaction = 0; +uniform vec2 roughness4_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 roughness4_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D normal4_file; +uniform int normal4_layer = 0; +uniform vec3 normal4_default = vec3(0.000000, 0.000000, 0.000000); +uniform int normal4_uaddressmode = 2; +uniform int normal4_vaddressmode = 2; +uniform int normal4_filtertype = 1; +uniform int normal4_framerange = 0; +uniform int normal4_frameoffset = 0; +uniform int normal4_frameendaction = 0; +uniform vec2 normal4_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 normal4_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap6_scale = 1.000000; +uniform float Knight_B_base = 1.000000; +uniform float Knight_B_diffuse_roughness = 0.000000; +uniform float Knight_B_metalness = 0.000000; +uniform float Knight_B_specular = 1.000000; +uniform vec3 Knight_B_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Knight_B_specular_IOR = 1.500000; +uniform float Knight_B_specular_anisotropy = 0.000000; +uniform float Knight_B_specular_rotation = 0.000000; +uniform float Knight_B_transmission = 0.000000; +uniform vec3 Knight_B_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Knight_B_transmission_depth = 0.000000; +uniform vec3 Knight_B_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Knight_B_transmission_scatter_anisotropy = 0.000000; +uniform float Knight_B_transmission_dispersion = 0.000000; +uniform float Knight_B_transmission_extra_roughness = 0.000000; +uniform float Knight_B_subsurface = 0.000000; +uniform float Knight_B_subsurface_scale = 0.003000; +uniform float Knight_B_subsurface_anisotropy = 0.000000; +uniform float Knight_B_sheen = 0.000000; +uniform vec3 Knight_B_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Knight_B_sheen_roughness = 0.300000; +uniform float Knight_B_coat = 0.000000; +uniform vec3 Knight_B_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Knight_B_coat_roughness = 0.100000; +uniform float Knight_B_coat_anisotropy = 0.000000; +uniform float Knight_B_coat_rotation = 0.000000; +uniform float Knight_B_coat_IOR = 1.500000; +uniform float Knight_B_coat_affect_color = 0.000000; +uniform float Knight_B_coat_affect_roughness = 0.000000; +uniform float Knight_B_thin_film_thickness = 0.000000; +uniform float Knight_B_thin_film_IOR = 1.500000; +uniform float Knight_B_emission = 0.000000; +uniform vec3 Knight_B_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Knight_B_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Knight_B_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse4_out = vec3(0.0); + mx_image_color3(diffuse4_file, diffuse4_layer, diffuse4_default, geomprop_UV0_out1, diffuse4_uaddressmode, diffuse4_vaddressmode, diffuse4_filtertype, diffuse4_framerange, diffuse4_frameoffset, diffuse4_frameendaction, diffuse4_uv_scale, diffuse4_uv_offset, diffuse4_out); + float roughness4_out = 0.0; + mx_image_float(roughness4_file, roughness4_layer, roughness4_default, geomprop_UV0_out1, roughness4_uaddressmode, roughness4_vaddressmode, roughness4_filtertype, roughness4_framerange, roughness4_frameoffset, roughness4_frameendaction, roughness4_uv_scale, roughness4_uv_offset, roughness4_out); + vec3 normal4_out = vec3(0.0); + mx_image_vector3(normal4_file, normal4_layer, normal4_default, geomprop_UV0_out1, normal4_uaddressmode, normal4_vaddressmode, normal4_filtertype, normal4_framerange, normal4_frameoffset, normal4_frameendaction, normal4_uv_scale, normal4_uv_offset, normal4_out); + vec3 diffuse4_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse4_out, diffuse4_out_cm_out); + vec3 mtlxnormalmap6_out = vec3(0.0); + mx_normalmap_float(normal4_out, mtlxnormalmap6_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap6_out); + surfaceshader Knight_B_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Knight_B_base, diffuse4_out_cm_out, Knight_B_diffuse_roughness, Knight_B_metalness, Knight_B_specular, Knight_B_specular_color, roughness4_out, Knight_B_specular_IOR, Knight_B_specular_anisotropy, Knight_B_specular_rotation, Knight_B_transmission, Knight_B_transmission_color, Knight_B_transmission_depth, Knight_B_transmission_scatter, Knight_B_transmission_scatter_anisotropy, Knight_B_transmission_dispersion, Knight_B_transmission_extra_roughness, Knight_B_subsurface, diffuse4_out_cm_out, diffuse4_out_cm_out, Knight_B_subsurface_scale, Knight_B_subsurface_anisotropy, Knight_B_sheen, Knight_B_sheen_color, Knight_B_sheen_roughness, Knight_B_coat, Knight_B_coat_color, Knight_B_coat_roughness, Knight_B_coat_anisotropy, Knight_B_coat_rotation, Knight_B_coat_IOR, geomprop_Nworld_out1, Knight_B_coat_affect_color, Knight_B_coat_affect_roughness, Knight_B_thin_film_thickness, Knight_B_thin_film_IOR, Knight_B_emission, Knight_B_emission_color, Knight_B_opacity, Knight_B_thin_walled, mtlxnormalmap6_out, geomprop_Tworld_out1, Knight_B_out); + material M_Knight_B_out = Knight_B_out; + out1 = vec4(M_Knight_B_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Knight_B.glsl.vert b/Materials/Examples/StandardSurface/M_Knight_B.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Knight_B.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Knight_B.mdl b/Materials/Examples/StandardSurface/M_Knight_B.mdl new file mode 100644 index 0000000000..49bc1a3106 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Knight_B.mdl @@ -0,0 +1,473 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Knight_B +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d diffuse4_file = texture_2d("/chess_set/knight_black_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KnightBlack/diffuse4/file") + ]], + uniform string diffuse4_layer = "" + [[ + materialx::core::origin("NG_KnightBlack/diffuse4/layer") + ]], + color diffuse4_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_KnightBlack/diffuse4/default") + ]], + uniform mx_addressmode_type diffuse4_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KnightBlack/diffuse4/uaddressmode") + ]], + uniform mx_addressmode_type diffuse4_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KnightBlack/diffuse4/vaddressmode") + ]], + uniform mx_filterlookup_type diffuse4_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KnightBlack/diffuse4/filtertype") + ]], + uniform string diffuse4_framerange = "" + [[ + materialx::core::origin("NG_KnightBlack/diffuse4/framerange") + ]], + uniform int diffuse4_frameoffset = 0 + [[ + materialx::core::origin("NG_KnightBlack/diffuse4/frameoffset") + ]], + uniform mx_addressmode_type diffuse4_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KnightBlack/diffuse4/frameendaction") + ]], + uniform texture_2d roughness4_file = texture_2d("/chess_set/knight_black_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KnightBlack/roughness4/file") + ]], + uniform string roughness4_layer = "" + [[ + materialx::core::origin("NG_KnightBlack/roughness4/layer") + ]], + float roughness4_default = 0.000000 + [[ + materialx::core::origin("NG_KnightBlack/roughness4/default") + ]], + uniform mx_addressmode_type roughness4_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KnightBlack/roughness4/uaddressmode") + ]], + uniform mx_addressmode_type roughness4_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KnightBlack/roughness4/vaddressmode") + ]], + uniform mx_filterlookup_type roughness4_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KnightBlack/roughness4/filtertype") + ]], + uniform string roughness4_framerange = "" + [[ + materialx::core::origin("NG_KnightBlack/roughness4/framerange") + ]], + uniform int roughness4_frameoffset = 0 + [[ + materialx::core::origin("NG_KnightBlack/roughness4/frameoffset") + ]], + uniform mx_addressmode_type roughness4_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KnightBlack/roughness4/frameendaction") + ]], + uniform texture_2d normal4_file = texture_2d("/chess_set/knight_black_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KnightBlack/normal4/file") + ]], + uniform string normal4_layer = "" + [[ + materialx::core::origin("NG_KnightBlack/normal4/layer") + ]], + float3 normal4_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_KnightBlack/normal4/default") + ]], + uniform mx_addressmode_type normal4_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KnightBlack/normal4/uaddressmode") + ]], + uniform mx_addressmode_type normal4_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KnightBlack/normal4/vaddressmode") + ]], + uniform mx_filterlookup_type normal4_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KnightBlack/normal4/filtertype") + ]], + uniform string normal4_framerange = "" + [[ + materialx::core::origin("NG_KnightBlack/normal4/framerange") + ]], + uniform int normal4_frameoffset = 0 + [[ + materialx::core::origin("NG_KnightBlack/normal4/frameoffset") + ]], + uniform mx_addressmode_type normal4_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KnightBlack/normal4/frameendaction") + ]], + float mtlxnormalmap6_scale = 1.000000 + [[ + materialx::core::origin("NG_KnightBlack/mtlxnormalmap6/scale") + ]], + float Knight_B_base = 1.000000 + [[ + materialx::core::origin("Knight_B/base") + ]], + float Knight_B_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Knight_B/diffuse_roughness") + ]], + float Knight_B_metalness = 0.000000 + [[ + materialx::core::origin("Knight_B/metalness") + ]], + float Knight_B_specular = 1.000000 + [[ + materialx::core::origin("Knight_B/specular") + ]], + color Knight_B_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Knight_B/specular_color") + ]], + uniform float Knight_B_specular_IOR = 1.500000 + [[ + materialx::core::origin("Knight_B/specular_IOR") + ]], + float Knight_B_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Knight_B/specular_anisotropy") + ]], + float Knight_B_specular_rotation = 0.000000 + [[ + materialx::core::origin("Knight_B/specular_rotation") + ]], + float Knight_B_transmission = 0.000000 + [[ + materialx::core::origin("Knight_B/transmission") + ]], + color Knight_B_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Knight_B/transmission_color") + ]], + float Knight_B_transmission_depth = 0.000000 + [[ + materialx::core::origin("Knight_B/transmission_depth") + ]], + color Knight_B_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Knight_B/transmission_scatter") + ]], + float Knight_B_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Knight_B/transmission_scatter_anisotropy") + ]], + float Knight_B_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Knight_B/transmission_dispersion") + ]], + float Knight_B_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Knight_B/transmission_extra_roughness") + ]], + float Knight_B_subsurface = 0.000000 + [[ + materialx::core::origin("Knight_B/subsurface") + ]], + float Knight_B_subsurface_scale = 0.003000 + [[ + materialx::core::origin("Knight_B/subsurface_scale") + ]], + float Knight_B_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Knight_B/subsurface_anisotropy") + ]], + float Knight_B_sheen = 0.000000 + [[ + materialx::core::origin("Knight_B/sheen") + ]], + color Knight_B_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Knight_B/sheen_color") + ]], + float Knight_B_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Knight_B/sheen_roughness") + ]], + float Knight_B_coat = 0.000000 + [[ + materialx::core::origin("Knight_B/coat") + ]], + color Knight_B_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Knight_B/coat_color") + ]], + float Knight_B_coat_roughness = 0.100000 + [[ + materialx::core::origin("Knight_B/coat_roughness") + ]], + float Knight_B_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Knight_B/coat_anisotropy") + ]], + float Knight_B_coat_rotation = 0.000000 + [[ + materialx::core::origin("Knight_B/coat_rotation") + ]], + uniform float Knight_B_coat_IOR = 1.500000 + [[ + materialx::core::origin("Knight_B/coat_IOR") + ]], + float Knight_B_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Knight_B/coat_affect_color") + ]], + float Knight_B_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Knight_B/coat_affect_roughness") + ]], + float Knight_B_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Knight_B/thin_film_thickness") + ]], + float Knight_B_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Knight_B/thin_film_IOR") + ]], + float Knight_B_emission = 0.000000 + [[ + materialx::core::origin("Knight_B/emission") + ]], + color Knight_B_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Knight_B/emission_color") + ]], + color Knight_B_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Knight_B/opacity") + ]], + bool Knight_B_thin_walled = false + [[ + materialx::core::origin("Knight_B/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color diffuse4_out = materialx::stdlib_1_8::mx_image_color3(diffuse4_file, diffuse4_layer, diffuse4_default, geomprop_UV0_out1, diffuse4_uaddressmode, diffuse4_vaddressmode, diffuse4_filtertype, diffuse4_framerange, diffuse4_frameoffset, diffuse4_frameendaction, mxp_flip_v:false); + float roughness4_out = materialx::stdlib_1_8::mx_image_float(roughness4_file, roughness4_layer, roughness4_default, geomprop_UV0_out1, roughness4_uaddressmode, roughness4_vaddressmode, roughness4_filtertype, roughness4_framerange, roughness4_frameoffset, roughness4_frameendaction, mxp_flip_v:false); + float3 normal4_out = materialx::stdlib_1_8::mx_image_vector3(normal4_file, normal4_layer, normal4_default, geomprop_UV0_out1, normal4_uaddressmode, normal4_vaddressmode, normal4_filtertype, normal4_framerange, normal4_frameoffset, normal4_frameendaction, mxp_flip_v:false); + color diffuse4_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(diffuse4_out); + float3 mtlxnormalmap6_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:normal4_out, mxp_scale:mtlxnormalmap6_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Knight_B_out = NG_standard_surface_surfaceshader_100(Knight_B_base, diffuse4_out_cm_out, Knight_B_diffuse_roughness, Knight_B_metalness, Knight_B_specular, Knight_B_specular_color, roughness4_out, Knight_B_specular_IOR, Knight_B_specular_anisotropy, Knight_B_specular_rotation, Knight_B_transmission, Knight_B_transmission_color, Knight_B_transmission_depth, Knight_B_transmission_scatter, Knight_B_transmission_scatter_anisotropy, Knight_B_transmission_dispersion, Knight_B_transmission_extra_roughness, Knight_B_subsurface, diffuse4_out_cm_out, diffuse4_out_cm_out, Knight_B_subsurface_scale, Knight_B_subsurface_anisotropy, Knight_B_sheen, Knight_B_sheen_color, Knight_B_sheen_roughness, Knight_B_coat, Knight_B_coat_color, Knight_B_coat_roughness, Knight_B_coat_anisotropy, Knight_B_coat_rotation, Knight_B_coat_IOR, geomprop_Nworld_out1, Knight_B_coat_affect_color, Knight_B_coat_affect_roughness, Knight_B_thin_film_thickness, Knight_B_thin_film_IOR, Knight_B_emission, Knight_B_emission_color, Knight_B_opacity, Knight_B_thin_walled, mtlxnormalmap6_out, geomprop_Tworld_out1); + material M_Knight_B_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Knight_B_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Knight_B_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Knight_B.msl.frag b/Materials/Examples/StandardSurface/M_Knight_B.msl.frag new file mode 100644 index 0000000000..f18726df81 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Knight_B.msl.frag @@ -0,0 +1,2873 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int diffuse4_layer; + vec3 diffuse4_default; + int diffuse4_uaddressmode; + int diffuse4_vaddressmode; + int diffuse4_filtertype; + int diffuse4_framerange; + int diffuse4_frameoffset; + int diffuse4_frameendaction; + vec2 diffuse4_uv_scale; + vec2 diffuse4_uv_offset; + int roughness4_layer; + float roughness4_default; + int roughness4_uaddressmode; + int roughness4_vaddressmode; + int roughness4_filtertype; + int roughness4_framerange; + int roughness4_frameoffset; + int roughness4_frameendaction; + vec2 roughness4_uv_scale; + vec2 roughness4_uv_offset; + int normal4_layer; + vec3 normal4_default; + int normal4_uaddressmode; + int normal4_vaddressmode; + int normal4_filtertype; + int normal4_framerange; + int normal4_frameoffset; + int normal4_frameendaction; + vec2 normal4_uv_scale; + vec2 normal4_uv_offset; + float mtlxnormalmap6_scale; + float Knight_B_base; + float Knight_B_diffuse_roughness; + float Knight_B_metalness; + float Knight_B_specular; + vec3 Knight_B_specular_color; + float Knight_B_specular_IOR; + float Knight_B_specular_anisotropy; + float Knight_B_specular_rotation; + float Knight_B_transmission; + vec3 Knight_B_transmission_color; + float Knight_B_transmission_depth; + vec3 Knight_B_transmission_scatter; + float Knight_B_transmission_scatter_anisotropy; + float Knight_B_transmission_dispersion; + float Knight_B_transmission_extra_roughness; + float Knight_B_subsurface; + float Knight_B_subsurface_scale; + float Knight_B_subsurface_anisotropy; + float Knight_B_sheen; + vec3 Knight_B_sheen_color; + float Knight_B_sheen_roughness; + float Knight_B_coat; + vec3 Knight_B_coat_color; + float Knight_B_coat_roughness; + float Knight_B_coat_anisotropy; + float Knight_B_coat_rotation; + float Knight_B_coat_IOR; + float Knight_B_coat_affect_color; + float Knight_B_coat_affect_roughness; + float Knight_B_thin_film_thickness; + float Knight_B_thin_film_IOR; + float Knight_B_emission; + vec3 Knight_B_emission_color; + vec3 Knight_B_opacity; + bool Knight_B_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture diffuse4_file , int diffuse4_layer + + , vec3 diffuse4_default + + , int diffuse4_uaddressmode + + , int diffuse4_vaddressmode + + , int diffuse4_filtertype + + , int diffuse4_framerange + + , int diffuse4_frameoffset + + , int diffuse4_frameendaction + + , vec2 diffuse4_uv_scale + + , vec2 diffuse4_uv_offset + +, MetalTexture roughness4_file , int roughness4_layer + + , float roughness4_default + + , int roughness4_uaddressmode + + , int roughness4_vaddressmode + + , int roughness4_filtertype + + , int roughness4_framerange + + , int roughness4_frameoffset + + , int roughness4_frameendaction + + , vec2 roughness4_uv_scale + + , vec2 roughness4_uv_offset + +, MetalTexture normal4_file , int normal4_layer + + , vec3 normal4_default + + , int normal4_uaddressmode + + , int normal4_vaddressmode + + , int normal4_filtertype + + , int normal4_framerange + + , int normal4_frameoffset + + , int normal4_frameendaction + + , vec2 normal4_uv_scale + + , vec2 normal4_uv_offset + + , float mtlxnormalmap6_scale + + , float Knight_B_base + + , float Knight_B_diffuse_roughness + + , float Knight_B_metalness + + , float Knight_B_specular + + , vec3 Knight_B_specular_color + + , float Knight_B_specular_IOR + + , float Knight_B_specular_anisotropy + + , float Knight_B_specular_rotation + + , float Knight_B_transmission + + , vec3 Knight_B_transmission_color + + , float Knight_B_transmission_depth + + , vec3 Knight_B_transmission_scatter + + , float Knight_B_transmission_scatter_anisotropy + + , float Knight_B_transmission_dispersion + + , float Knight_B_transmission_extra_roughness + + , float Knight_B_subsurface + + , float Knight_B_subsurface_scale + + , float Knight_B_subsurface_anisotropy + + , float Knight_B_sheen + + , vec3 Knight_B_sheen_color + + , float Knight_B_sheen_roughness + + , float Knight_B_coat + + , vec3 Knight_B_coat_color + + , float Knight_B_coat_roughness + + , float Knight_B_coat_anisotropy + + , float Knight_B_coat_rotation + + , float Knight_B_coat_IOR + + , float Knight_B_coat_affect_color + + , float Knight_B_coat_affect_roughness + + , float Knight_B_thin_film_thickness + + , float Knight_B_thin_film_IOR + + , float Knight_B_emission + + , vec3 Knight_B_emission_color + + , vec3 Knight_B_opacity + + , bool Knight_B_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, diffuse4_file(diffuse4_file) + , diffuse4_layer(diffuse4_layer) + + , diffuse4_default(diffuse4_default) + + , diffuse4_uaddressmode(diffuse4_uaddressmode) + + , diffuse4_vaddressmode(diffuse4_vaddressmode) + + , diffuse4_filtertype(diffuse4_filtertype) + + , diffuse4_framerange(diffuse4_framerange) + + , diffuse4_frameoffset(diffuse4_frameoffset) + + , diffuse4_frameendaction(diffuse4_frameendaction) + + , diffuse4_uv_scale(diffuse4_uv_scale) + + , diffuse4_uv_offset(diffuse4_uv_offset) + +, roughness4_file(roughness4_file) + , roughness4_layer(roughness4_layer) + + , roughness4_default(roughness4_default) + + , roughness4_uaddressmode(roughness4_uaddressmode) + + , roughness4_vaddressmode(roughness4_vaddressmode) + + , roughness4_filtertype(roughness4_filtertype) + + , roughness4_framerange(roughness4_framerange) + + , roughness4_frameoffset(roughness4_frameoffset) + + , roughness4_frameendaction(roughness4_frameendaction) + + , roughness4_uv_scale(roughness4_uv_scale) + + , roughness4_uv_offset(roughness4_uv_offset) + +, normal4_file(normal4_file) + , normal4_layer(normal4_layer) + + , normal4_default(normal4_default) + + , normal4_uaddressmode(normal4_uaddressmode) + + , normal4_vaddressmode(normal4_vaddressmode) + + , normal4_filtertype(normal4_filtertype) + + , normal4_framerange(normal4_framerange) + + , normal4_frameoffset(normal4_frameoffset) + + , normal4_frameendaction(normal4_frameendaction) + + , normal4_uv_scale(normal4_uv_scale) + + , normal4_uv_offset(normal4_uv_offset) + + , mtlxnormalmap6_scale(mtlxnormalmap6_scale) + + , Knight_B_base(Knight_B_base) + + , Knight_B_diffuse_roughness(Knight_B_diffuse_roughness) + + , Knight_B_metalness(Knight_B_metalness) + + , Knight_B_specular(Knight_B_specular) + + , Knight_B_specular_color(Knight_B_specular_color) + + , Knight_B_specular_IOR(Knight_B_specular_IOR) + + , Knight_B_specular_anisotropy(Knight_B_specular_anisotropy) + + , Knight_B_specular_rotation(Knight_B_specular_rotation) + + , Knight_B_transmission(Knight_B_transmission) + + , Knight_B_transmission_color(Knight_B_transmission_color) + + , Knight_B_transmission_depth(Knight_B_transmission_depth) + + , Knight_B_transmission_scatter(Knight_B_transmission_scatter) + + , Knight_B_transmission_scatter_anisotropy(Knight_B_transmission_scatter_anisotropy) + + , Knight_B_transmission_dispersion(Knight_B_transmission_dispersion) + + , Knight_B_transmission_extra_roughness(Knight_B_transmission_extra_roughness) + + , Knight_B_subsurface(Knight_B_subsurface) + + , Knight_B_subsurface_scale(Knight_B_subsurface_scale) + + , Knight_B_subsurface_anisotropy(Knight_B_subsurface_anisotropy) + + , Knight_B_sheen(Knight_B_sheen) + + , Knight_B_sheen_color(Knight_B_sheen_color) + + , Knight_B_sheen_roughness(Knight_B_sheen_roughness) + + , Knight_B_coat(Knight_B_coat) + + , Knight_B_coat_color(Knight_B_coat_color) + + , Knight_B_coat_roughness(Knight_B_coat_roughness) + + , Knight_B_coat_anisotropy(Knight_B_coat_anisotropy) + + , Knight_B_coat_rotation(Knight_B_coat_rotation) + + , Knight_B_coat_IOR(Knight_B_coat_IOR) + + , Knight_B_coat_affect_color(Knight_B_coat_affect_color) + + , Knight_B_coat_affect_roughness(Knight_B_coat_affect_roughness) + + , Knight_B_thin_film_thickness(Knight_B_thin_film_thickness) + + , Knight_B_thin_film_IOR(Knight_B_thin_film_IOR) + + , Knight_B_emission(Knight_B_emission) + + , Knight_B_emission_color(Knight_B_emission_color) + + , Knight_B_opacity(Knight_B_opacity) + + , Knight_B_thin_walled(Knight_B_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture diffuse4_file; + int diffuse4_layer; + + + vec3 diffuse4_default; + + + int diffuse4_uaddressmode; + + + int diffuse4_vaddressmode; + + + int diffuse4_filtertype; + + + int diffuse4_framerange; + + + int diffuse4_frameoffset; + + + int diffuse4_frameendaction; + + + vec2 diffuse4_uv_scale; + + + vec2 diffuse4_uv_offset; + + +MetalTexture roughness4_file; + int roughness4_layer; + + + float roughness4_default; + + + int roughness4_uaddressmode; + + + int roughness4_vaddressmode; + + + int roughness4_filtertype; + + + int roughness4_framerange; + + + int roughness4_frameoffset; + + + int roughness4_frameendaction; + + + vec2 roughness4_uv_scale; + + + vec2 roughness4_uv_offset; + + +MetalTexture normal4_file; + int normal4_layer; + + + vec3 normal4_default; + + + int normal4_uaddressmode; + + + int normal4_vaddressmode; + + + int normal4_filtertype; + + + int normal4_framerange; + + + int normal4_frameoffset; + + + int normal4_frameendaction; + + + vec2 normal4_uv_scale; + + + vec2 normal4_uv_offset; + + + float mtlxnormalmap6_scale; + + + float Knight_B_base; + + + float Knight_B_diffuse_roughness; + + + float Knight_B_metalness; + + + float Knight_B_specular; + + + vec3 Knight_B_specular_color; + + + float Knight_B_specular_IOR; + + + float Knight_B_specular_anisotropy; + + + float Knight_B_specular_rotation; + + + float Knight_B_transmission; + + + vec3 Knight_B_transmission_color; + + + float Knight_B_transmission_depth; + + + vec3 Knight_B_transmission_scatter; + + + float Knight_B_transmission_scatter_anisotropy; + + + float Knight_B_transmission_dispersion; + + + float Knight_B_transmission_extra_roughness; + + + float Knight_B_subsurface; + + + float Knight_B_subsurface_scale; + + + float Knight_B_subsurface_anisotropy; + + + float Knight_B_sheen; + + + vec3 Knight_B_sheen_color; + + + float Knight_B_sheen_roughness; + + + float Knight_B_coat; + + + vec3 Knight_B_coat_color; + + + float Knight_B_coat_roughness; + + + float Knight_B_coat_anisotropy; + + + float Knight_B_coat_rotation; + + + float Knight_B_coat_IOR; + + + float Knight_B_coat_affect_color; + + + float Knight_B_coat_affect_roughness; + + + float Knight_B_thin_film_thickness; + + + float Knight_B_thin_film_IOR; + + + float Knight_B_emission; + + + vec3 Knight_B_emission_color; + + + vec3 Knight_B_opacity; + + + bool Knight_B_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse4_out = vec3(0.0); + mx_image_color3(diffuse4_file, diffuse4_layer, diffuse4_default, geomprop_UV0_out1, diffuse4_uaddressmode, diffuse4_vaddressmode, diffuse4_filtertype, diffuse4_framerange, diffuse4_frameoffset, diffuse4_frameendaction, diffuse4_uv_scale, diffuse4_uv_offset, diffuse4_out); + float roughness4_out = 0.0; + mx_image_float(roughness4_file, roughness4_layer, roughness4_default, geomprop_UV0_out1, roughness4_uaddressmode, roughness4_vaddressmode, roughness4_filtertype, roughness4_framerange, roughness4_frameoffset, roughness4_frameendaction, roughness4_uv_scale, roughness4_uv_offset, roughness4_out); + vec3 normal4_out = vec3(0.0); + mx_image_vector3(normal4_file, normal4_layer, normal4_default, geomprop_UV0_out1, normal4_uaddressmode, normal4_vaddressmode, normal4_filtertype, normal4_framerange, normal4_frameoffset, normal4_frameendaction, normal4_uv_scale, normal4_uv_offset, normal4_out); + vec3 diffuse4_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse4_out, diffuse4_out_cm_out); + vec3 mtlxnormalmap6_out = vec3(0.0); + mx_normalmap_float(normal4_out, mtlxnormalmap6_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap6_out); + surfaceshader Knight_B_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Knight_B_base, diffuse4_out_cm_out, Knight_B_diffuse_roughness, Knight_B_metalness, Knight_B_specular, Knight_B_specular_color, roughness4_out, Knight_B_specular_IOR, Knight_B_specular_anisotropy, Knight_B_specular_rotation, Knight_B_transmission, Knight_B_transmission_color, Knight_B_transmission_depth, Knight_B_transmission_scatter, Knight_B_transmission_scatter_anisotropy, Knight_B_transmission_dispersion, Knight_B_transmission_extra_roughness, Knight_B_subsurface, diffuse4_out_cm_out, diffuse4_out_cm_out, Knight_B_subsurface_scale, Knight_B_subsurface_anisotropy, Knight_B_sheen, Knight_B_sheen_color, Knight_B_sheen_roughness, Knight_B_coat, Knight_B_coat_color, Knight_B_coat_roughness, Knight_B_coat_anisotropy, Knight_B_coat_rotation, Knight_B_coat_IOR, geomprop_Nworld_out1, Knight_B_coat_affect_color, Knight_B_coat_affect_roughness, Knight_B_thin_film_thickness, Knight_B_thin_film_IOR, Knight_B_emission, Knight_B_emission_color, Knight_B_opacity, Knight_B_thin_walled, mtlxnormalmap6_out, geomprop_Tworld_out1, Knight_B_out); + material M_Knight_B_out = Knight_B_out; + out1 = float4(M_Knight_B_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d diffuse4_file_tex [[texture(0)]], sampler diffuse4_file_sampler [[sampler(0)]] +, texture2d roughness4_file_tex [[texture(1)]], sampler roughness4_file_sampler [[sampler(1)]] +, texture2d normal4_file_tex [[texture(2)]], sampler normal4_file_sampler [[sampler(2)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(3)]], sampler u_envRadiance_sampler [[sampler(3)]] +, texture2d u_envIrradiance_tex [[texture(4)]], sampler u_envIrradiance_sampler [[sampler(4)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +diffuse4_file_tex, diffuse4_file_sampler } + , u_pub.diffuse4_layer + , u_pub.diffuse4_default + , u_pub.diffuse4_uaddressmode + , u_pub.diffuse4_vaddressmode + , u_pub.diffuse4_filtertype + , u_pub.diffuse4_framerange + , u_pub.diffuse4_frameoffset + , u_pub.diffuse4_frameendaction + , u_pub.diffuse4_uv_scale + , u_pub.diffuse4_uv_offset +, MetalTexture { +roughness4_file_tex, roughness4_file_sampler } + , u_pub.roughness4_layer + , u_pub.roughness4_default + , u_pub.roughness4_uaddressmode + , u_pub.roughness4_vaddressmode + , u_pub.roughness4_filtertype + , u_pub.roughness4_framerange + , u_pub.roughness4_frameoffset + , u_pub.roughness4_frameendaction + , u_pub.roughness4_uv_scale + , u_pub.roughness4_uv_offset +, MetalTexture { +normal4_file_tex, normal4_file_sampler } + , u_pub.normal4_layer + , u_pub.normal4_default + , u_pub.normal4_uaddressmode + , u_pub.normal4_vaddressmode + , u_pub.normal4_filtertype + , u_pub.normal4_framerange + , u_pub.normal4_frameoffset + , u_pub.normal4_frameendaction + , u_pub.normal4_uv_scale + , u_pub.normal4_uv_offset + , u_pub.mtlxnormalmap6_scale + , u_pub.Knight_B_base + , u_pub.Knight_B_diffuse_roughness + , u_pub.Knight_B_metalness + , u_pub.Knight_B_specular + , u_pub.Knight_B_specular_color + , u_pub.Knight_B_specular_IOR + , u_pub.Knight_B_specular_anisotropy + , u_pub.Knight_B_specular_rotation + , u_pub.Knight_B_transmission + , u_pub.Knight_B_transmission_color + , u_pub.Knight_B_transmission_depth + , u_pub.Knight_B_transmission_scatter + , u_pub.Knight_B_transmission_scatter_anisotropy + , u_pub.Knight_B_transmission_dispersion + , u_pub.Knight_B_transmission_extra_roughness + , u_pub.Knight_B_subsurface + , u_pub.Knight_B_subsurface_scale + , u_pub.Knight_B_subsurface_anisotropy + , u_pub.Knight_B_sheen + , u_pub.Knight_B_sheen_color + , u_pub.Knight_B_sheen_roughness + , u_pub.Knight_B_coat + , u_pub.Knight_B_coat_color + , u_pub.Knight_B_coat_roughness + , u_pub.Knight_B_coat_anisotropy + , u_pub.Knight_B_coat_rotation + , u_pub.Knight_B_coat_IOR + , u_pub.Knight_B_coat_affect_color + , u_pub.Knight_B_coat_affect_roughness + , u_pub.Knight_B_thin_film_thickness + , u_pub.Knight_B_thin_film_IOR + , u_pub.Knight_B_emission + , u_pub.Knight_B_emission_color + , u_pub.Knight_B_opacity + , u_pub.Knight_B_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Knight_B.msl.vert b/Materials/Examples/StandardSurface/M_Knight_B.msl.vert new file mode 100644 index 0000000000..369c37498c --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Knight_B.msl.vert @@ -0,0 +1,126 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'diffuse4'. Function already called in this scope. + // Omitted node 'roughness4'. Function already called in this scope. + // Omitted node 'normal4'. Function already called in this scope. + // Omitted node 'diffuse4_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap6'. Function already called in this scope. + // Omitted node 'Knight_B'. Function already called in this scope. + // Omitted node 'M_Knight_B'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Knight_B.osl b/Materials/Examples/StandardSurface/M_Knight_B.osl new file mode 100644 index 0000000000..d04e16bf16 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Knight_B.osl @@ -0,0 +1,657 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Knight_B +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Knight_B" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string diffuse4_file = "chess_set/knight_black_base_color.jpg" + [[ + string widget = "filename" + ]], + string diffuse4_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string diffuse4_layer = "", + color diffuse4_default = color(0.000000, 0.000000, 0.000000), + string diffuse4_uaddressmode = "periodic", + string diffuse4_vaddressmode = "periodic", + string diffuse4_filtertype = "linear", + string diffuse4_framerange = "", + int diffuse4_frameoffset = 0 + [[ + string widget = "number" + ]], + string diffuse4_frameendaction = "constant", + string roughness4_file = "chess_set/knight_black_roughness.jpg" + [[ + string widget = "filename" + ]], + string roughness4_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string roughness4_layer = "", + float roughness4_default = 0.000000 + [[ + string widget = "number" + ]], + string roughness4_uaddressmode = "periodic", + string roughness4_vaddressmode = "periodic", + string roughness4_filtertype = "linear", + string roughness4_framerange = "", + int roughness4_frameoffset = 0 + [[ + string widget = "number" + ]], + string roughness4_frameendaction = "constant", + string normal4_file = "chess_set/knight_black_normal.jpg" + [[ + string widget = "filename" + ]], + string normal4_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string normal4_layer = "", + vector normal4_default = vector(0.000000, 0.000000, 0.000000), + string normal4_uaddressmode = "periodic", + string normal4_vaddressmode = "periodic", + string normal4_filtertype = "linear", + string normal4_framerange = "", + int normal4_frameoffset = 0 + [[ + string widget = "number" + ]], + string normal4_frameendaction = "constant", + float mtlxnormalmap6_scale = 1.000000 + [[ + string widget = "number" + ]], + float Knight_B_base = 1.000000 + [[ + string widget = "number" + ]], + float Knight_B_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_metalness = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_specular = 1.000000 + [[ + string widget = "number" + ]], + color Knight_B_specular_color = color(1.000000, 1.000000, 1.000000), + float Knight_B_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Knight_B_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_transmission = 0.000000 + [[ + string widget = "number" + ]], + color Knight_B_transmission_color = color(1.000000, 1.000000, 1.000000), + float Knight_B_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Knight_B_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Knight_B_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_subsurface = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float Knight_B_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Knight_B_sheen_color = color(1.000000, 1.000000, 1.000000), + float Knight_B_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Knight_B_coat = 0.000000 + [[ + string widget = "number" + ]], + color Knight_B_coat_color = color(1.000000, 1.000000, 1.000000), + float Knight_B_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Knight_B_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Knight_B_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Knight_B_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Knight_B_emission = 0.000000 + [[ + string widget = "number" + ]], + color Knight_B_emission_color = color(1.000000, 1.000000, 1.000000), + color Knight_B_opacity = color(1.000000, 1.000000, 1.000000), + int Knight_B_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource diffuse4_file_ = {diffuse4_file, diffuse4_file_colorspace}; + textureresource roughness4_file_ = {roughness4_file, roughness4_file_colorspace}; + textureresource normal4_file_ = {normal4_file, normal4_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color diffuse4_out = color(0.0); + mx_image_color3(diffuse4_file_, diffuse4_layer, diffuse4_default, geomprop_UV0_out1, diffuse4_uaddressmode, diffuse4_vaddressmode, diffuse4_filtertype, diffuse4_framerange, diffuse4_frameoffset, diffuse4_frameendaction, diffuse4_out); + float roughness4_out = 0.0; + mx_image_float(roughness4_file_, roughness4_layer, roughness4_default, geomprop_UV0_out1, roughness4_uaddressmode, roughness4_vaddressmode, roughness4_filtertype, roughness4_framerange, roughness4_frameoffset, roughness4_frameendaction, roughness4_out); + vector normal4_out = vector(0.0); + mx_image_vector3(normal4_file_, normal4_layer, normal4_default, geomprop_UV0_out1, normal4_uaddressmode, normal4_vaddressmode, normal4_filtertype, normal4_framerange, normal4_frameoffset, normal4_frameendaction, normal4_out); + color diffuse4_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse4_out, diffuse4_out_cm_out); + vector mtlxnormalmap6_out = vector(0.0); + mx_normalmap_float(normal4_out, mtlxnormalmap6_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap6_out); + surfaceshader Knight_B_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Knight_B_base, diffuse4_out_cm_out, Knight_B_diffuse_roughness, Knight_B_metalness, Knight_B_specular, Knight_B_specular_color, roughness4_out, Knight_B_specular_IOR, Knight_B_specular_anisotropy, Knight_B_specular_rotation, Knight_B_transmission, Knight_B_transmission_color, Knight_B_transmission_depth, Knight_B_transmission_scatter, Knight_B_transmission_scatter_anisotropy, Knight_B_transmission_dispersion, Knight_B_transmission_extra_roughness, Knight_B_subsurface, diffuse4_out_cm_out, diffuse4_out_cm_out, Knight_B_subsurface_scale, Knight_B_subsurface_anisotropy, Knight_B_sheen, Knight_B_sheen_color, Knight_B_sheen_roughness, Knight_B_coat, Knight_B_coat_color, Knight_B_coat_roughness, Knight_B_coat_anisotropy, Knight_B_coat_rotation, Knight_B_coat_IOR, geomprop_Nworld_out1, Knight_B_coat_affect_color, Knight_B_coat_affect_roughness, Knight_B_thin_film_thickness, Knight_B_thin_film_IOR, Knight_B_emission, Knight_B_emission_color, Knight_B_opacity, Knight_B_thin_walled, mtlxnormalmap6_out, geomprop_Tworld_out1, Knight_B_out); + MATERIAL M_Knight_B_out = mx_surfacematerial(Knight_B_out, backsurfaceshader, displacementshader1); + out = M_Knight_B_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Knight_W.glsl.frag b/Materials/Examples/StandardSurface/M_Knight_W.glsl.frag new file mode 100644 index 0000000000..595f2de435 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Knight_W.glsl.frag @@ -0,0 +1,2001 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D diffuse5_file; +uniform int diffuse5_layer = 0; +uniform vec3 diffuse5_default = vec3(0.000000, 0.000000, 0.000000); +uniform int diffuse5_uaddressmode = 2; +uniform int diffuse5_vaddressmode = 2; +uniform int diffuse5_filtertype = 1; +uniform int diffuse5_framerange = 0; +uniform int diffuse5_frameoffset = 0; +uniform int diffuse5_frameendaction = 0; +uniform vec2 diffuse5_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 diffuse5_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D roughness5_file; +uniform int roughness5_layer = 0; +uniform float roughness5_default = 0.000000; +uniform int roughness5_uaddressmode = 2; +uniform int roughness5_vaddressmode = 2; +uniform int roughness5_filtertype = 1; +uniform int roughness5_framerange = 0; +uniform int roughness5_frameoffset = 0; +uniform int roughness5_frameendaction = 0; +uniform vec2 roughness5_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 roughness5_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D normal5_file; +uniform int normal5_layer = 0; +uniform vec3 normal5_default = vec3(0.000000, 0.000000, 0.000000); +uniform int normal5_uaddressmode = 2; +uniform int normal5_vaddressmode = 2; +uniform int normal5_filtertype = 1; +uniform int normal5_framerange = 0; +uniform int normal5_frameoffset = 0; +uniform int normal5_frameendaction = 0; +uniform vec2 normal5_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 normal5_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap7_scale = 1.000000; +uniform float Knight_W_base = 1.000000; +uniform float Knight_W_diffuse_roughness = 0.000000; +uniform float Knight_W_metalness = 0.000000; +uniform float Knight_W_specular = 1.000000; +uniform vec3 Knight_W_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Knight_W_specular_IOR = 1.500000; +uniform float Knight_W_specular_anisotropy = 0.000000; +uniform float Knight_W_specular_rotation = 0.000000; +uniform float Knight_W_transmission = 0.000000; +uniform vec3 Knight_W_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Knight_W_transmission_depth = 0.000000; +uniform vec3 Knight_W_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Knight_W_transmission_scatter_anisotropy = 0.000000; +uniform float Knight_W_transmission_dispersion = 0.000000; +uniform float Knight_W_transmission_extra_roughness = 0.000000; +uniform float Knight_W_subsurface = 0.000000; +uniform float Knight_W_subsurface_scale = 0.003000; +uniform float Knight_W_subsurface_anisotropy = 0.000000; +uniform float Knight_W_sheen = 0.000000; +uniform vec3 Knight_W_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Knight_W_sheen_roughness = 0.300000; +uniform float Knight_W_coat = 0.000000; +uniform vec3 Knight_W_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Knight_W_coat_roughness = 0.100000; +uniform float Knight_W_coat_anisotropy = 0.000000; +uniform float Knight_W_coat_rotation = 0.000000; +uniform float Knight_W_coat_IOR = 1.500000; +uniform float Knight_W_coat_affect_color = 0.000000; +uniform float Knight_W_coat_affect_roughness = 0.000000; +uniform float Knight_W_thin_film_thickness = 0.000000; +uniform float Knight_W_thin_film_IOR = 1.500000; +uniform float Knight_W_emission = 0.000000; +uniform vec3 Knight_W_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Knight_W_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Knight_W_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse5_out = vec3(0.0); + mx_image_color3(diffuse5_file, diffuse5_layer, diffuse5_default, geomprop_UV0_out1, diffuse5_uaddressmode, diffuse5_vaddressmode, diffuse5_filtertype, diffuse5_framerange, diffuse5_frameoffset, diffuse5_frameendaction, diffuse5_uv_scale, diffuse5_uv_offset, diffuse5_out); + float roughness5_out = 0.0; + mx_image_float(roughness5_file, roughness5_layer, roughness5_default, geomprop_UV0_out1, roughness5_uaddressmode, roughness5_vaddressmode, roughness5_filtertype, roughness5_framerange, roughness5_frameoffset, roughness5_frameendaction, roughness5_uv_scale, roughness5_uv_offset, roughness5_out); + vec3 normal5_out = vec3(0.0); + mx_image_vector3(normal5_file, normal5_layer, normal5_default, geomprop_UV0_out1, normal5_uaddressmode, normal5_vaddressmode, normal5_filtertype, normal5_framerange, normal5_frameoffset, normal5_frameendaction, normal5_uv_scale, normal5_uv_offset, normal5_out); + vec3 diffuse5_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse5_out, diffuse5_out_cm_out); + vec3 mtlxnormalmap7_out = vec3(0.0); + mx_normalmap_float(normal5_out, mtlxnormalmap7_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap7_out); + surfaceshader Knight_W_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Knight_W_base, diffuse5_out_cm_out, Knight_W_diffuse_roughness, Knight_W_metalness, Knight_W_specular, Knight_W_specular_color, roughness5_out, Knight_W_specular_IOR, Knight_W_specular_anisotropy, Knight_W_specular_rotation, Knight_W_transmission, Knight_W_transmission_color, Knight_W_transmission_depth, Knight_W_transmission_scatter, Knight_W_transmission_scatter_anisotropy, Knight_W_transmission_dispersion, Knight_W_transmission_extra_roughness, Knight_W_subsurface, diffuse5_out_cm_out, diffuse5_out_cm_out, Knight_W_subsurface_scale, Knight_W_subsurface_anisotropy, Knight_W_sheen, Knight_W_sheen_color, Knight_W_sheen_roughness, Knight_W_coat, Knight_W_coat_color, Knight_W_coat_roughness, Knight_W_coat_anisotropy, Knight_W_coat_rotation, Knight_W_coat_IOR, geomprop_Nworld_out1, Knight_W_coat_affect_color, Knight_W_coat_affect_roughness, Knight_W_thin_film_thickness, Knight_W_thin_film_IOR, Knight_W_emission, Knight_W_emission_color, Knight_W_opacity, Knight_W_thin_walled, mtlxnormalmap7_out, geomprop_Tworld_out1, Knight_W_out); + material M_Knight_W_out = Knight_W_out; + out1 = vec4(M_Knight_W_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Knight_W.glsl.vert b/Materials/Examples/StandardSurface/M_Knight_W.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Knight_W.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Knight_W.mdl b/Materials/Examples/StandardSurface/M_Knight_W.mdl new file mode 100644 index 0000000000..d932d6e556 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Knight_W.mdl @@ -0,0 +1,473 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Knight_W +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d diffuse5_file = texture_2d("/chess_set/knight_white_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KnightWhite/diffuse5/file") + ]], + uniform string diffuse5_layer = "" + [[ + materialx::core::origin("NG_KnightWhite/diffuse5/layer") + ]], + color diffuse5_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_KnightWhite/diffuse5/default") + ]], + uniform mx_addressmode_type diffuse5_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KnightWhite/diffuse5/uaddressmode") + ]], + uniform mx_addressmode_type diffuse5_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KnightWhite/diffuse5/vaddressmode") + ]], + uniform mx_filterlookup_type diffuse5_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KnightWhite/diffuse5/filtertype") + ]], + uniform string diffuse5_framerange = "" + [[ + materialx::core::origin("NG_KnightWhite/diffuse5/framerange") + ]], + uniform int diffuse5_frameoffset = 0 + [[ + materialx::core::origin("NG_KnightWhite/diffuse5/frameoffset") + ]], + uniform mx_addressmode_type diffuse5_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KnightWhite/diffuse5/frameendaction") + ]], + uniform texture_2d roughness5_file = texture_2d("/chess_set/knight_white_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KnightWhite/roughness5/file") + ]], + uniform string roughness5_layer = "" + [[ + materialx::core::origin("NG_KnightWhite/roughness5/layer") + ]], + float roughness5_default = 0.000000 + [[ + materialx::core::origin("NG_KnightWhite/roughness5/default") + ]], + uniform mx_addressmode_type roughness5_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KnightWhite/roughness5/uaddressmode") + ]], + uniform mx_addressmode_type roughness5_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KnightWhite/roughness5/vaddressmode") + ]], + uniform mx_filterlookup_type roughness5_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KnightWhite/roughness5/filtertype") + ]], + uniform string roughness5_framerange = "" + [[ + materialx::core::origin("NG_KnightWhite/roughness5/framerange") + ]], + uniform int roughness5_frameoffset = 0 + [[ + materialx::core::origin("NG_KnightWhite/roughness5/frameoffset") + ]], + uniform mx_addressmode_type roughness5_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KnightWhite/roughness5/frameendaction") + ]], + uniform texture_2d normal5_file = texture_2d("/chess_set/knight_white_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_KnightWhite/normal5/file") + ]], + uniform string normal5_layer = "" + [[ + materialx::core::origin("NG_KnightWhite/normal5/layer") + ]], + float3 normal5_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_KnightWhite/normal5/default") + ]], + uniform mx_addressmode_type normal5_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KnightWhite/normal5/uaddressmode") + ]], + uniform mx_addressmode_type normal5_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_KnightWhite/normal5/vaddressmode") + ]], + uniform mx_filterlookup_type normal5_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_KnightWhite/normal5/filtertype") + ]], + uniform string normal5_framerange = "" + [[ + materialx::core::origin("NG_KnightWhite/normal5/framerange") + ]], + uniform int normal5_frameoffset = 0 + [[ + materialx::core::origin("NG_KnightWhite/normal5/frameoffset") + ]], + uniform mx_addressmode_type normal5_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_KnightWhite/normal5/frameendaction") + ]], + float mtlxnormalmap7_scale = 1.000000 + [[ + materialx::core::origin("NG_KnightWhite/mtlxnormalmap7/scale") + ]], + float Knight_W_base = 1.000000 + [[ + materialx::core::origin("Knight_W/base") + ]], + float Knight_W_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Knight_W/diffuse_roughness") + ]], + float Knight_W_metalness = 0.000000 + [[ + materialx::core::origin("Knight_W/metalness") + ]], + float Knight_W_specular = 1.000000 + [[ + materialx::core::origin("Knight_W/specular") + ]], + color Knight_W_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Knight_W/specular_color") + ]], + uniform float Knight_W_specular_IOR = 1.500000 + [[ + materialx::core::origin("Knight_W/specular_IOR") + ]], + float Knight_W_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Knight_W/specular_anisotropy") + ]], + float Knight_W_specular_rotation = 0.000000 + [[ + materialx::core::origin("Knight_W/specular_rotation") + ]], + float Knight_W_transmission = 0.000000 + [[ + materialx::core::origin("Knight_W/transmission") + ]], + color Knight_W_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Knight_W/transmission_color") + ]], + float Knight_W_transmission_depth = 0.000000 + [[ + materialx::core::origin("Knight_W/transmission_depth") + ]], + color Knight_W_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Knight_W/transmission_scatter") + ]], + float Knight_W_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Knight_W/transmission_scatter_anisotropy") + ]], + float Knight_W_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Knight_W/transmission_dispersion") + ]], + float Knight_W_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Knight_W/transmission_extra_roughness") + ]], + float Knight_W_subsurface = 0.000000 + [[ + materialx::core::origin("Knight_W/subsurface") + ]], + float Knight_W_subsurface_scale = 0.003000 + [[ + materialx::core::origin("Knight_W/subsurface_scale") + ]], + float Knight_W_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Knight_W/subsurface_anisotropy") + ]], + float Knight_W_sheen = 0.000000 + [[ + materialx::core::origin("Knight_W/sheen") + ]], + color Knight_W_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Knight_W/sheen_color") + ]], + float Knight_W_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Knight_W/sheen_roughness") + ]], + float Knight_W_coat = 0.000000 + [[ + materialx::core::origin("Knight_W/coat") + ]], + color Knight_W_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Knight_W/coat_color") + ]], + float Knight_W_coat_roughness = 0.100000 + [[ + materialx::core::origin("Knight_W/coat_roughness") + ]], + float Knight_W_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Knight_W/coat_anisotropy") + ]], + float Knight_W_coat_rotation = 0.000000 + [[ + materialx::core::origin("Knight_W/coat_rotation") + ]], + uniform float Knight_W_coat_IOR = 1.500000 + [[ + materialx::core::origin("Knight_W/coat_IOR") + ]], + float Knight_W_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Knight_W/coat_affect_color") + ]], + float Knight_W_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Knight_W/coat_affect_roughness") + ]], + float Knight_W_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Knight_W/thin_film_thickness") + ]], + float Knight_W_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Knight_W/thin_film_IOR") + ]], + float Knight_W_emission = 0.000000 + [[ + materialx::core::origin("Knight_W/emission") + ]], + color Knight_W_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Knight_W/emission_color") + ]], + color Knight_W_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Knight_W/opacity") + ]], + bool Knight_W_thin_walled = false + [[ + materialx::core::origin("Knight_W/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color diffuse5_out = materialx::stdlib_1_8::mx_image_color3(diffuse5_file, diffuse5_layer, diffuse5_default, geomprop_UV0_out1, diffuse5_uaddressmode, diffuse5_vaddressmode, diffuse5_filtertype, diffuse5_framerange, diffuse5_frameoffset, diffuse5_frameendaction, mxp_flip_v:false); + float roughness5_out = materialx::stdlib_1_8::mx_image_float(roughness5_file, roughness5_layer, roughness5_default, geomprop_UV0_out1, roughness5_uaddressmode, roughness5_vaddressmode, roughness5_filtertype, roughness5_framerange, roughness5_frameoffset, roughness5_frameendaction, mxp_flip_v:false); + float3 normal5_out = materialx::stdlib_1_8::mx_image_vector3(normal5_file, normal5_layer, normal5_default, geomprop_UV0_out1, normal5_uaddressmode, normal5_vaddressmode, normal5_filtertype, normal5_framerange, normal5_frameoffset, normal5_frameendaction, mxp_flip_v:false); + color diffuse5_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(diffuse5_out); + float3 mtlxnormalmap7_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:normal5_out, mxp_scale:mtlxnormalmap7_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Knight_W_out = NG_standard_surface_surfaceshader_100(Knight_W_base, diffuse5_out_cm_out, Knight_W_diffuse_roughness, Knight_W_metalness, Knight_W_specular, Knight_W_specular_color, roughness5_out, Knight_W_specular_IOR, Knight_W_specular_anisotropy, Knight_W_specular_rotation, Knight_W_transmission, Knight_W_transmission_color, Knight_W_transmission_depth, Knight_W_transmission_scatter, Knight_W_transmission_scatter_anisotropy, Knight_W_transmission_dispersion, Knight_W_transmission_extra_roughness, Knight_W_subsurface, diffuse5_out_cm_out, diffuse5_out_cm_out, Knight_W_subsurface_scale, Knight_W_subsurface_anisotropy, Knight_W_sheen, Knight_W_sheen_color, Knight_W_sheen_roughness, Knight_W_coat, Knight_W_coat_color, Knight_W_coat_roughness, Knight_W_coat_anisotropy, Knight_W_coat_rotation, Knight_W_coat_IOR, geomprop_Nworld_out1, Knight_W_coat_affect_color, Knight_W_coat_affect_roughness, Knight_W_thin_film_thickness, Knight_W_thin_film_IOR, Knight_W_emission, Knight_W_emission_color, Knight_W_opacity, Knight_W_thin_walled, mtlxnormalmap7_out, geomprop_Tworld_out1); + material M_Knight_W_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Knight_W_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Knight_W_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Knight_W.msl.frag b/Materials/Examples/StandardSurface/M_Knight_W.msl.frag new file mode 100644 index 0000000000..9c37325f3d --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Knight_W.msl.frag @@ -0,0 +1,2873 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int diffuse5_layer; + vec3 diffuse5_default; + int diffuse5_uaddressmode; + int diffuse5_vaddressmode; + int diffuse5_filtertype; + int diffuse5_framerange; + int diffuse5_frameoffset; + int diffuse5_frameendaction; + vec2 diffuse5_uv_scale; + vec2 diffuse5_uv_offset; + int roughness5_layer; + float roughness5_default; + int roughness5_uaddressmode; + int roughness5_vaddressmode; + int roughness5_filtertype; + int roughness5_framerange; + int roughness5_frameoffset; + int roughness5_frameendaction; + vec2 roughness5_uv_scale; + vec2 roughness5_uv_offset; + int normal5_layer; + vec3 normal5_default; + int normal5_uaddressmode; + int normal5_vaddressmode; + int normal5_filtertype; + int normal5_framerange; + int normal5_frameoffset; + int normal5_frameendaction; + vec2 normal5_uv_scale; + vec2 normal5_uv_offset; + float mtlxnormalmap7_scale; + float Knight_W_base; + float Knight_W_diffuse_roughness; + float Knight_W_metalness; + float Knight_W_specular; + vec3 Knight_W_specular_color; + float Knight_W_specular_IOR; + float Knight_W_specular_anisotropy; + float Knight_W_specular_rotation; + float Knight_W_transmission; + vec3 Knight_W_transmission_color; + float Knight_W_transmission_depth; + vec3 Knight_W_transmission_scatter; + float Knight_W_transmission_scatter_anisotropy; + float Knight_W_transmission_dispersion; + float Knight_W_transmission_extra_roughness; + float Knight_W_subsurface; + float Knight_W_subsurface_scale; + float Knight_W_subsurface_anisotropy; + float Knight_W_sheen; + vec3 Knight_W_sheen_color; + float Knight_W_sheen_roughness; + float Knight_W_coat; + vec3 Knight_W_coat_color; + float Knight_W_coat_roughness; + float Knight_W_coat_anisotropy; + float Knight_W_coat_rotation; + float Knight_W_coat_IOR; + float Knight_W_coat_affect_color; + float Knight_W_coat_affect_roughness; + float Knight_W_thin_film_thickness; + float Knight_W_thin_film_IOR; + float Knight_W_emission; + vec3 Knight_W_emission_color; + vec3 Knight_W_opacity; + bool Knight_W_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture diffuse5_file , int diffuse5_layer + + , vec3 diffuse5_default + + , int diffuse5_uaddressmode + + , int diffuse5_vaddressmode + + , int diffuse5_filtertype + + , int diffuse5_framerange + + , int diffuse5_frameoffset + + , int diffuse5_frameendaction + + , vec2 diffuse5_uv_scale + + , vec2 diffuse5_uv_offset + +, MetalTexture roughness5_file , int roughness5_layer + + , float roughness5_default + + , int roughness5_uaddressmode + + , int roughness5_vaddressmode + + , int roughness5_filtertype + + , int roughness5_framerange + + , int roughness5_frameoffset + + , int roughness5_frameendaction + + , vec2 roughness5_uv_scale + + , vec2 roughness5_uv_offset + +, MetalTexture normal5_file , int normal5_layer + + , vec3 normal5_default + + , int normal5_uaddressmode + + , int normal5_vaddressmode + + , int normal5_filtertype + + , int normal5_framerange + + , int normal5_frameoffset + + , int normal5_frameendaction + + , vec2 normal5_uv_scale + + , vec2 normal5_uv_offset + + , float mtlxnormalmap7_scale + + , float Knight_W_base + + , float Knight_W_diffuse_roughness + + , float Knight_W_metalness + + , float Knight_W_specular + + , vec3 Knight_W_specular_color + + , float Knight_W_specular_IOR + + , float Knight_W_specular_anisotropy + + , float Knight_W_specular_rotation + + , float Knight_W_transmission + + , vec3 Knight_W_transmission_color + + , float Knight_W_transmission_depth + + , vec3 Knight_W_transmission_scatter + + , float Knight_W_transmission_scatter_anisotropy + + , float Knight_W_transmission_dispersion + + , float Knight_W_transmission_extra_roughness + + , float Knight_W_subsurface + + , float Knight_W_subsurface_scale + + , float Knight_W_subsurface_anisotropy + + , float Knight_W_sheen + + , vec3 Knight_W_sheen_color + + , float Knight_W_sheen_roughness + + , float Knight_W_coat + + , vec3 Knight_W_coat_color + + , float Knight_W_coat_roughness + + , float Knight_W_coat_anisotropy + + , float Knight_W_coat_rotation + + , float Knight_W_coat_IOR + + , float Knight_W_coat_affect_color + + , float Knight_W_coat_affect_roughness + + , float Knight_W_thin_film_thickness + + , float Knight_W_thin_film_IOR + + , float Knight_W_emission + + , vec3 Knight_W_emission_color + + , vec3 Knight_W_opacity + + , bool Knight_W_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, diffuse5_file(diffuse5_file) + , diffuse5_layer(diffuse5_layer) + + , diffuse5_default(diffuse5_default) + + , diffuse5_uaddressmode(diffuse5_uaddressmode) + + , diffuse5_vaddressmode(diffuse5_vaddressmode) + + , diffuse5_filtertype(diffuse5_filtertype) + + , diffuse5_framerange(diffuse5_framerange) + + , diffuse5_frameoffset(diffuse5_frameoffset) + + , diffuse5_frameendaction(diffuse5_frameendaction) + + , diffuse5_uv_scale(diffuse5_uv_scale) + + , diffuse5_uv_offset(diffuse5_uv_offset) + +, roughness5_file(roughness5_file) + , roughness5_layer(roughness5_layer) + + , roughness5_default(roughness5_default) + + , roughness5_uaddressmode(roughness5_uaddressmode) + + , roughness5_vaddressmode(roughness5_vaddressmode) + + , roughness5_filtertype(roughness5_filtertype) + + , roughness5_framerange(roughness5_framerange) + + , roughness5_frameoffset(roughness5_frameoffset) + + , roughness5_frameendaction(roughness5_frameendaction) + + , roughness5_uv_scale(roughness5_uv_scale) + + , roughness5_uv_offset(roughness5_uv_offset) + +, normal5_file(normal5_file) + , normal5_layer(normal5_layer) + + , normal5_default(normal5_default) + + , normal5_uaddressmode(normal5_uaddressmode) + + , normal5_vaddressmode(normal5_vaddressmode) + + , normal5_filtertype(normal5_filtertype) + + , normal5_framerange(normal5_framerange) + + , normal5_frameoffset(normal5_frameoffset) + + , normal5_frameendaction(normal5_frameendaction) + + , normal5_uv_scale(normal5_uv_scale) + + , normal5_uv_offset(normal5_uv_offset) + + , mtlxnormalmap7_scale(mtlxnormalmap7_scale) + + , Knight_W_base(Knight_W_base) + + , Knight_W_diffuse_roughness(Knight_W_diffuse_roughness) + + , Knight_W_metalness(Knight_W_metalness) + + , Knight_W_specular(Knight_W_specular) + + , Knight_W_specular_color(Knight_W_specular_color) + + , Knight_W_specular_IOR(Knight_W_specular_IOR) + + , Knight_W_specular_anisotropy(Knight_W_specular_anisotropy) + + , Knight_W_specular_rotation(Knight_W_specular_rotation) + + , Knight_W_transmission(Knight_W_transmission) + + , Knight_W_transmission_color(Knight_W_transmission_color) + + , Knight_W_transmission_depth(Knight_W_transmission_depth) + + , Knight_W_transmission_scatter(Knight_W_transmission_scatter) + + , Knight_W_transmission_scatter_anisotropy(Knight_W_transmission_scatter_anisotropy) + + , Knight_W_transmission_dispersion(Knight_W_transmission_dispersion) + + , Knight_W_transmission_extra_roughness(Knight_W_transmission_extra_roughness) + + , Knight_W_subsurface(Knight_W_subsurface) + + , Knight_W_subsurface_scale(Knight_W_subsurface_scale) + + , Knight_W_subsurface_anisotropy(Knight_W_subsurface_anisotropy) + + , Knight_W_sheen(Knight_W_sheen) + + , Knight_W_sheen_color(Knight_W_sheen_color) + + , Knight_W_sheen_roughness(Knight_W_sheen_roughness) + + , Knight_W_coat(Knight_W_coat) + + , Knight_W_coat_color(Knight_W_coat_color) + + , Knight_W_coat_roughness(Knight_W_coat_roughness) + + , Knight_W_coat_anisotropy(Knight_W_coat_anisotropy) + + , Knight_W_coat_rotation(Knight_W_coat_rotation) + + , Knight_W_coat_IOR(Knight_W_coat_IOR) + + , Knight_W_coat_affect_color(Knight_W_coat_affect_color) + + , Knight_W_coat_affect_roughness(Knight_W_coat_affect_roughness) + + , Knight_W_thin_film_thickness(Knight_W_thin_film_thickness) + + , Knight_W_thin_film_IOR(Knight_W_thin_film_IOR) + + , Knight_W_emission(Knight_W_emission) + + , Knight_W_emission_color(Knight_W_emission_color) + + , Knight_W_opacity(Knight_W_opacity) + + , Knight_W_thin_walled(Knight_W_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture diffuse5_file; + int diffuse5_layer; + + + vec3 diffuse5_default; + + + int diffuse5_uaddressmode; + + + int diffuse5_vaddressmode; + + + int diffuse5_filtertype; + + + int diffuse5_framerange; + + + int diffuse5_frameoffset; + + + int diffuse5_frameendaction; + + + vec2 diffuse5_uv_scale; + + + vec2 diffuse5_uv_offset; + + +MetalTexture roughness5_file; + int roughness5_layer; + + + float roughness5_default; + + + int roughness5_uaddressmode; + + + int roughness5_vaddressmode; + + + int roughness5_filtertype; + + + int roughness5_framerange; + + + int roughness5_frameoffset; + + + int roughness5_frameendaction; + + + vec2 roughness5_uv_scale; + + + vec2 roughness5_uv_offset; + + +MetalTexture normal5_file; + int normal5_layer; + + + vec3 normal5_default; + + + int normal5_uaddressmode; + + + int normal5_vaddressmode; + + + int normal5_filtertype; + + + int normal5_framerange; + + + int normal5_frameoffset; + + + int normal5_frameendaction; + + + vec2 normal5_uv_scale; + + + vec2 normal5_uv_offset; + + + float mtlxnormalmap7_scale; + + + float Knight_W_base; + + + float Knight_W_diffuse_roughness; + + + float Knight_W_metalness; + + + float Knight_W_specular; + + + vec3 Knight_W_specular_color; + + + float Knight_W_specular_IOR; + + + float Knight_W_specular_anisotropy; + + + float Knight_W_specular_rotation; + + + float Knight_W_transmission; + + + vec3 Knight_W_transmission_color; + + + float Knight_W_transmission_depth; + + + vec3 Knight_W_transmission_scatter; + + + float Knight_W_transmission_scatter_anisotropy; + + + float Knight_W_transmission_dispersion; + + + float Knight_W_transmission_extra_roughness; + + + float Knight_W_subsurface; + + + float Knight_W_subsurface_scale; + + + float Knight_W_subsurface_anisotropy; + + + float Knight_W_sheen; + + + vec3 Knight_W_sheen_color; + + + float Knight_W_sheen_roughness; + + + float Knight_W_coat; + + + vec3 Knight_W_coat_color; + + + float Knight_W_coat_roughness; + + + float Knight_W_coat_anisotropy; + + + float Knight_W_coat_rotation; + + + float Knight_W_coat_IOR; + + + float Knight_W_coat_affect_color; + + + float Knight_W_coat_affect_roughness; + + + float Knight_W_thin_film_thickness; + + + float Knight_W_thin_film_IOR; + + + float Knight_W_emission; + + + vec3 Knight_W_emission_color; + + + vec3 Knight_W_opacity; + + + bool Knight_W_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse5_out = vec3(0.0); + mx_image_color3(diffuse5_file, diffuse5_layer, diffuse5_default, geomprop_UV0_out1, diffuse5_uaddressmode, diffuse5_vaddressmode, diffuse5_filtertype, diffuse5_framerange, diffuse5_frameoffset, diffuse5_frameendaction, diffuse5_uv_scale, diffuse5_uv_offset, diffuse5_out); + float roughness5_out = 0.0; + mx_image_float(roughness5_file, roughness5_layer, roughness5_default, geomprop_UV0_out1, roughness5_uaddressmode, roughness5_vaddressmode, roughness5_filtertype, roughness5_framerange, roughness5_frameoffset, roughness5_frameendaction, roughness5_uv_scale, roughness5_uv_offset, roughness5_out); + vec3 normal5_out = vec3(0.0); + mx_image_vector3(normal5_file, normal5_layer, normal5_default, geomprop_UV0_out1, normal5_uaddressmode, normal5_vaddressmode, normal5_filtertype, normal5_framerange, normal5_frameoffset, normal5_frameendaction, normal5_uv_scale, normal5_uv_offset, normal5_out); + vec3 diffuse5_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse5_out, diffuse5_out_cm_out); + vec3 mtlxnormalmap7_out = vec3(0.0); + mx_normalmap_float(normal5_out, mtlxnormalmap7_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap7_out); + surfaceshader Knight_W_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Knight_W_base, diffuse5_out_cm_out, Knight_W_diffuse_roughness, Knight_W_metalness, Knight_W_specular, Knight_W_specular_color, roughness5_out, Knight_W_specular_IOR, Knight_W_specular_anisotropy, Knight_W_specular_rotation, Knight_W_transmission, Knight_W_transmission_color, Knight_W_transmission_depth, Knight_W_transmission_scatter, Knight_W_transmission_scatter_anisotropy, Knight_W_transmission_dispersion, Knight_W_transmission_extra_roughness, Knight_W_subsurface, diffuse5_out_cm_out, diffuse5_out_cm_out, Knight_W_subsurface_scale, Knight_W_subsurface_anisotropy, Knight_W_sheen, Knight_W_sheen_color, Knight_W_sheen_roughness, Knight_W_coat, Knight_W_coat_color, Knight_W_coat_roughness, Knight_W_coat_anisotropy, Knight_W_coat_rotation, Knight_W_coat_IOR, geomprop_Nworld_out1, Knight_W_coat_affect_color, Knight_W_coat_affect_roughness, Knight_W_thin_film_thickness, Knight_W_thin_film_IOR, Knight_W_emission, Knight_W_emission_color, Knight_W_opacity, Knight_W_thin_walled, mtlxnormalmap7_out, geomprop_Tworld_out1, Knight_W_out); + material M_Knight_W_out = Knight_W_out; + out1 = float4(M_Knight_W_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d diffuse5_file_tex [[texture(0)]], sampler diffuse5_file_sampler [[sampler(0)]] +, texture2d roughness5_file_tex [[texture(1)]], sampler roughness5_file_sampler [[sampler(1)]] +, texture2d normal5_file_tex [[texture(2)]], sampler normal5_file_sampler [[sampler(2)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(3)]], sampler u_envRadiance_sampler [[sampler(3)]] +, texture2d u_envIrradiance_tex [[texture(4)]], sampler u_envIrradiance_sampler [[sampler(4)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +diffuse5_file_tex, diffuse5_file_sampler } + , u_pub.diffuse5_layer + , u_pub.diffuse5_default + , u_pub.diffuse5_uaddressmode + , u_pub.diffuse5_vaddressmode + , u_pub.diffuse5_filtertype + , u_pub.diffuse5_framerange + , u_pub.diffuse5_frameoffset + , u_pub.diffuse5_frameendaction + , u_pub.diffuse5_uv_scale + , u_pub.diffuse5_uv_offset +, MetalTexture { +roughness5_file_tex, roughness5_file_sampler } + , u_pub.roughness5_layer + , u_pub.roughness5_default + , u_pub.roughness5_uaddressmode + , u_pub.roughness5_vaddressmode + , u_pub.roughness5_filtertype + , u_pub.roughness5_framerange + , u_pub.roughness5_frameoffset + , u_pub.roughness5_frameendaction + , u_pub.roughness5_uv_scale + , u_pub.roughness5_uv_offset +, MetalTexture { +normal5_file_tex, normal5_file_sampler } + , u_pub.normal5_layer + , u_pub.normal5_default + , u_pub.normal5_uaddressmode + , u_pub.normal5_vaddressmode + , u_pub.normal5_filtertype + , u_pub.normal5_framerange + , u_pub.normal5_frameoffset + , u_pub.normal5_frameendaction + , u_pub.normal5_uv_scale + , u_pub.normal5_uv_offset + , u_pub.mtlxnormalmap7_scale + , u_pub.Knight_W_base + , u_pub.Knight_W_diffuse_roughness + , u_pub.Knight_W_metalness + , u_pub.Knight_W_specular + , u_pub.Knight_W_specular_color + , u_pub.Knight_W_specular_IOR + , u_pub.Knight_W_specular_anisotropy + , u_pub.Knight_W_specular_rotation + , u_pub.Knight_W_transmission + , u_pub.Knight_W_transmission_color + , u_pub.Knight_W_transmission_depth + , u_pub.Knight_W_transmission_scatter + , u_pub.Knight_W_transmission_scatter_anisotropy + , u_pub.Knight_W_transmission_dispersion + , u_pub.Knight_W_transmission_extra_roughness + , u_pub.Knight_W_subsurface + , u_pub.Knight_W_subsurface_scale + , u_pub.Knight_W_subsurface_anisotropy + , u_pub.Knight_W_sheen + , u_pub.Knight_W_sheen_color + , u_pub.Knight_W_sheen_roughness + , u_pub.Knight_W_coat + , u_pub.Knight_W_coat_color + , u_pub.Knight_W_coat_roughness + , u_pub.Knight_W_coat_anisotropy + , u_pub.Knight_W_coat_rotation + , u_pub.Knight_W_coat_IOR + , u_pub.Knight_W_coat_affect_color + , u_pub.Knight_W_coat_affect_roughness + , u_pub.Knight_W_thin_film_thickness + , u_pub.Knight_W_thin_film_IOR + , u_pub.Knight_W_emission + , u_pub.Knight_W_emission_color + , u_pub.Knight_W_opacity + , u_pub.Knight_W_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Knight_W.msl.vert b/Materials/Examples/StandardSurface/M_Knight_W.msl.vert new file mode 100644 index 0000000000..37c17c020b --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Knight_W.msl.vert @@ -0,0 +1,126 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'diffuse5'. Function already called in this scope. + // Omitted node 'roughness5'. Function already called in this scope. + // Omitted node 'normal5'. Function already called in this scope. + // Omitted node 'diffuse5_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap7'. Function already called in this scope. + // Omitted node 'Knight_W'. Function already called in this scope. + // Omitted node 'M_Knight_W'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Knight_W.osl b/Materials/Examples/StandardSurface/M_Knight_W.osl new file mode 100644 index 0000000000..03aba49de3 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Knight_W.osl @@ -0,0 +1,657 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Knight_W +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Knight_W" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string diffuse5_file = "chess_set/knight_white_base_color.jpg" + [[ + string widget = "filename" + ]], + string diffuse5_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string diffuse5_layer = "", + color diffuse5_default = color(0.000000, 0.000000, 0.000000), + string diffuse5_uaddressmode = "periodic", + string diffuse5_vaddressmode = "periodic", + string diffuse5_filtertype = "linear", + string diffuse5_framerange = "", + int diffuse5_frameoffset = 0 + [[ + string widget = "number" + ]], + string diffuse5_frameendaction = "constant", + string roughness5_file = "chess_set/knight_white_roughness.jpg" + [[ + string widget = "filename" + ]], + string roughness5_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string roughness5_layer = "", + float roughness5_default = 0.000000 + [[ + string widget = "number" + ]], + string roughness5_uaddressmode = "periodic", + string roughness5_vaddressmode = "periodic", + string roughness5_filtertype = "linear", + string roughness5_framerange = "", + int roughness5_frameoffset = 0 + [[ + string widget = "number" + ]], + string roughness5_frameendaction = "constant", + string normal5_file = "chess_set/knight_white_normal.jpg" + [[ + string widget = "filename" + ]], + string normal5_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string normal5_layer = "", + vector normal5_default = vector(0.000000, 0.000000, 0.000000), + string normal5_uaddressmode = "periodic", + string normal5_vaddressmode = "periodic", + string normal5_filtertype = "linear", + string normal5_framerange = "", + int normal5_frameoffset = 0 + [[ + string widget = "number" + ]], + string normal5_frameendaction = "constant", + float mtlxnormalmap7_scale = 1.000000 + [[ + string widget = "number" + ]], + float Knight_W_base = 1.000000 + [[ + string widget = "number" + ]], + float Knight_W_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_metalness = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_specular = 1.000000 + [[ + string widget = "number" + ]], + color Knight_W_specular_color = color(1.000000, 1.000000, 1.000000), + float Knight_W_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Knight_W_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_transmission = 0.000000 + [[ + string widget = "number" + ]], + color Knight_W_transmission_color = color(1.000000, 1.000000, 1.000000), + float Knight_W_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Knight_W_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Knight_W_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_subsurface = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float Knight_W_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Knight_W_sheen_color = color(1.000000, 1.000000, 1.000000), + float Knight_W_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Knight_W_coat = 0.000000 + [[ + string widget = "number" + ]], + color Knight_W_coat_color = color(1.000000, 1.000000, 1.000000), + float Knight_W_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Knight_W_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Knight_W_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Knight_W_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Knight_W_emission = 0.000000 + [[ + string widget = "number" + ]], + color Knight_W_emission_color = color(1.000000, 1.000000, 1.000000), + color Knight_W_opacity = color(1.000000, 1.000000, 1.000000), + int Knight_W_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource diffuse5_file_ = {diffuse5_file, diffuse5_file_colorspace}; + textureresource roughness5_file_ = {roughness5_file, roughness5_file_colorspace}; + textureresource normal5_file_ = {normal5_file, normal5_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color diffuse5_out = color(0.0); + mx_image_color3(diffuse5_file_, diffuse5_layer, diffuse5_default, geomprop_UV0_out1, diffuse5_uaddressmode, diffuse5_vaddressmode, diffuse5_filtertype, diffuse5_framerange, diffuse5_frameoffset, diffuse5_frameendaction, diffuse5_out); + float roughness5_out = 0.0; + mx_image_float(roughness5_file_, roughness5_layer, roughness5_default, geomprop_UV0_out1, roughness5_uaddressmode, roughness5_vaddressmode, roughness5_filtertype, roughness5_framerange, roughness5_frameoffset, roughness5_frameendaction, roughness5_out); + vector normal5_out = vector(0.0); + mx_image_vector3(normal5_file_, normal5_layer, normal5_default, geomprop_UV0_out1, normal5_uaddressmode, normal5_vaddressmode, normal5_filtertype, normal5_framerange, normal5_frameoffset, normal5_frameendaction, normal5_out); + color diffuse5_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse5_out, diffuse5_out_cm_out); + vector mtlxnormalmap7_out = vector(0.0); + mx_normalmap_float(normal5_out, mtlxnormalmap7_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap7_out); + surfaceshader Knight_W_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Knight_W_base, diffuse5_out_cm_out, Knight_W_diffuse_roughness, Knight_W_metalness, Knight_W_specular, Knight_W_specular_color, roughness5_out, Knight_W_specular_IOR, Knight_W_specular_anisotropy, Knight_W_specular_rotation, Knight_W_transmission, Knight_W_transmission_color, Knight_W_transmission_depth, Knight_W_transmission_scatter, Knight_W_transmission_scatter_anisotropy, Knight_W_transmission_dispersion, Knight_W_transmission_extra_roughness, Knight_W_subsurface, diffuse5_out_cm_out, diffuse5_out_cm_out, Knight_W_subsurface_scale, Knight_W_subsurface_anisotropy, Knight_W_sheen, Knight_W_sheen_color, Knight_W_sheen_roughness, Knight_W_coat, Knight_W_coat_color, Knight_W_coat_roughness, Knight_W_coat_anisotropy, Knight_W_coat_rotation, Knight_W_coat_IOR, geomprop_Nworld_out1, Knight_W_coat_affect_color, Knight_W_coat_affect_roughness, Knight_W_thin_film_thickness, Knight_W_thin_film_IOR, Knight_W_emission, Knight_W_emission_color, Knight_W_opacity, Knight_W_thin_walled, mtlxnormalmap7_out, geomprop_Tworld_out1, Knight_W_out); + MATERIAL M_Knight_W_out = mx_surfacematerial(Knight_W_out, backsurfaceshader, displacementshader1); + out = M_Knight_W_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Body_B.glsl.frag b/Materials/Examples/StandardSurface/M_Pawn_Body_B.glsl.frag new file mode 100644 index 0000000000..aaa8a00ef1 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Body_B.glsl.frag @@ -0,0 +1,2013 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D diffuse9_file; +uniform int diffuse9_layer = 0; +uniform vec3 diffuse9_default = vec3(0.000000, 0.000000, 0.000000); +uniform int diffuse9_uaddressmode = 2; +uniform int diffuse9_vaddressmode = 2; +uniform int diffuse9_filtertype = 1; +uniform int diffuse9_framerange = 0; +uniform int diffuse9_frameoffset = 0; +uniform int diffuse9_frameendaction = 0; +uniform vec2 diffuse9_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 diffuse9_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D metallic9_file; +uniform int metallic9_layer = 0; +uniform float metallic9_default = 0.000000; +uniform int metallic9_uaddressmode = 2; +uniform int metallic9_vaddressmode = 2; +uniform int metallic9_filtertype = 1; +uniform int metallic9_framerange = 0; +uniform int metallic9_frameoffset = 0; +uniform int metallic9_frameendaction = 0; +uniform vec2 metallic9_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 metallic9_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D roughness9_file; +uniform int roughness9_layer = 0; +uniform float roughness9_default = 0.000000; +uniform int roughness9_uaddressmode = 2; +uniform int roughness9_vaddressmode = 2; +uniform int roughness9_filtertype = 1; +uniform int roughness9_framerange = 0; +uniform int roughness9_frameoffset = 0; +uniform int roughness9_frameendaction = 0; +uniform vec2 roughness9_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 roughness9_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D normal9_file; +uniform int normal9_layer = 0; +uniform vec3 normal9_default = vec3(0.000000, 0.000000, 0.000000); +uniform int normal9_uaddressmode = 2; +uniform int normal9_vaddressmode = 2; +uniform int normal9_filtertype = 1; +uniform int normal9_framerange = 0; +uniform int normal9_frameoffset = 0; +uniform int normal9_frameendaction = 0; +uniform vec2 normal9_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 normal9_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap13_scale = 1.000000; +uniform float Pawn_Body_B_base = 1.000000; +uniform float Pawn_Body_B_diffuse_roughness = 0.000000; +uniform float Pawn_Body_B_specular = 1.000000; +uniform vec3 Pawn_Body_B_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Body_B_specular_IOR = 1.500000; +uniform float Pawn_Body_B_specular_anisotropy = 0.000000; +uniform float Pawn_Body_B_specular_rotation = 0.000000; +uniform float Pawn_Body_B_transmission = 0.000000; +uniform vec3 Pawn_Body_B_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Body_B_transmission_depth = 0.000000; +uniform vec3 Pawn_Body_B_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Pawn_Body_B_transmission_scatter_anisotropy = 0.000000; +uniform float Pawn_Body_B_transmission_dispersion = 0.000000; +uniform float Pawn_Body_B_transmission_extra_roughness = 0.000000; +uniform float Pawn_Body_B_subsurface = 0.000000; +uniform float Pawn_Body_B_subsurface_scale = 0.003000; +uniform float Pawn_Body_B_subsurface_anisotropy = 0.000000; +uniform float Pawn_Body_B_sheen = 0.000000; +uniform vec3 Pawn_Body_B_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Body_B_sheen_roughness = 0.300000; +uniform float Pawn_Body_B_coat = 0.000000; +uniform vec3 Pawn_Body_B_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Body_B_coat_roughness = 0.100000; +uniform float Pawn_Body_B_coat_anisotropy = 0.000000; +uniform float Pawn_Body_B_coat_rotation = 0.000000; +uniform float Pawn_Body_B_coat_IOR = 1.500000; +uniform float Pawn_Body_B_coat_affect_color = 0.000000; +uniform float Pawn_Body_B_coat_affect_roughness = 0.000000; +uniform float Pawn_Body_B_thin_film_thickness = 0.000000; +uniform float Pawn_Body_B_thin_film_IOR = 1.500000; +uniform float Pawn_Body_B_emission = 0.000000; +uniform vec3 Pawn_Body_B_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Pawn_Body_B_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Pawn_Body_B_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse9_out = vec3(0.0); + mx_image_color3(diffuse9_file, diffuse9_layer, diffuse9_default, geomprop_UV0_out1, diffuse9_uaddressmode, diffuse9_vaddressmode, diffuse9_filtertype, diffuse9_framerange, diffuse9_frameoffset, diffuse9_frameendaction, diffuse9_uv_scale, diffuse9_uv_offset, diffuse9_out); + float metallic9_out = 0.0; + mx_image_float(metallic9_file, metallic9_layer, metallic9_default, geomprop_UV0_out1, metallic9_uaddressmode, metallic9_vaddressmode, metallic9_filtertype, metallic9_framerange, metallic9_frameoffset, metallic9_frameendaction, metallic9_uv_scale, metallic9_uv_offset, metallic9_out); + float roughness9_out = 0.0; + mx_image_float(roughness9_file, roughness9_layer, roughness9_default, geomprop_UV0_out1, roughness9_uaddressmode, roughness9_vaddressmode, roughness9_filtertype, roughness9_framerange, roughness9_frameoffset, roughness9_frameendaction, roughness9_uv_scale, roughness9_uv_offset, roughness9_out); + vec3 normal9_out = vec3(0.0); + mx_image_vector3(normal9_file, normal9_layer, normal9_default, geomprop_UV0_out1, normal9_uaddressmode, normal9_vaddressmode, normal9_filtertype, normal9_framerange, normal9_frameoffset, normal9_frameendaction, normal9_uv_scale, normal9_uv_offset, normal9_out); + vec3 diffuse9_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse9_out, diffuse9_out_cm_out); + vec3 mtlxnormalmap13_out = vec3(0.0); + mx_normalmap_float(normal9_out, mtlxnormalmap13_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap13_out); + surfaceshader Pawn_Body_B_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Pawn_Body_B_base, diffuse9_out_cm_out, Pawn_Body_B_diffuse_roughness, metallic9_out, Pawn_Body_B_specular, Pawn_Body_B_specular_color, roughness9_out, Pawn_Body_B_specular_IOR, Pawn_Body_B_specular_anisotropy, Pawn_Body_B_specular_rotation, Pawn_Body_B_transmission, Pawn_Body_B_transmission_color, Pawn_Body_B_transmission_depth, Pawn_Body_B_transmission_scatter, Pawn_Body_B_transmission_scatter_anisotropy, Pawn_Body_B_transmission_dispersion, Pawn_Body_B_transmission_extra_roughness, Pawn_Body_B_subsurface, diffuse9_out_cm_out, diffuse9_out_cm_out, Pawn_Body_B_subsurface_scale, Pawn_Body_B_subsurface_anisotropy, Pawn_Body_B_sheen, Pawn_Body_B_sheen_color, Pawn_Body_B_sheen_roughness, Pawn_Body_B_coat, Pawn_Body_B_coat_color, Pawn_Body_B_coat_roughness, Pawn_Body_B_coat_anisotropy, Pawn_Body_B_coat_rotation, Pawn_Body_B_coat_IOR, geomprop_Nworld_out1, Pawn_Body_B_coat_affect_color, Pawn_Body_B_coat_affect_roughness, Pawn_Body_B_thin_film_thickness, Pawn_Body_B_thin_film_IOR, Pawn_Body_B_emission, Pawn_Body_B_emission_color, Pawn_Body_B_opacity, Pawn_Body_B_thin_walled, mtlxnormalmap13_out, geomprop_Tworld_out1, Pawn_Body_B_out); + material M_Pawn_Body_B_out = Pawn_Body_B_out; + out1 = vec4(M_Pawn_Body_B_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Body_B.glsl.vert b/Materials/Examples/StandardSurface/M_Pawn_Body_B.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Body_B.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Body_B.mdl b/Materials/Examples/StandardSurface/M_Pawn_Body_B.mdl new file mode 100644 index 0000000000..58ce99d1f0 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Body_B.mdl @@ -0,0 +1,506 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Pawn_Body_B +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d diffuse9_file = texture_2d("/chess_set/pawn_black_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_PawnBodyBlack/diffuse9/file") + ]], + uniform string diffuse9_layer = "" + [[ + materialx::core::origin("NG_PawnBodyBlack/diffuse9/layer") + ]], + color diffuse9_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_PawnBodyBlack/diffuse9/default") + ]], + uniform mx_addressmode_type diffuse9_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyBlack/diffuse9/uaddressmode") + ]], + uniform mx_addressmode_type diffuse9_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyBlack/diffuse9/vaddressmode") + ]], + uniform mx_filterlookup_type diffuse9_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_PawnBodyBlack/diffuse9/filtertype") + ]], + uniform string diffuse9_framerange = "" + [[ + materialx::core::origin("NG_PawnBodyBlack/diffuse9/framerange") + ]], + uniform int diffuse9_frameoffset = 0 + [[ + materialx::core::origin("NG_PawnBodyBlack/diffuse9/frameoffset") + ]], + uniform mx_addressmode_type diffuse9_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_PawnBodyBlack/diffuse9/frameendaction") + ]], + uniform texture_2d metallic9_file = texture_2d("/chess_set/pawn_shared_metallic.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_PawnBodyBlack/metallic9/file") + ]], + uniform string metallic9_layer = "" + [[ + materialx::core::origin("NG_PawnBodyBlack/metallic9/layer") + ]], + float metallic9_default = 0.000000 + [[ + materialx::core::origin("NG_PawnBodyBlack/metallic9/default") + ]], + uniform mx_addressmode_type metallic9_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyBlack/metallic9/uaddressmode") + ]], + uniform mx_addressmode_type metallic9_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyBlack/metallic9/vaddressmode") + ]], + uniform mx_filterlookup_type metallic9_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_PawnBodyBlack/metallic9/filtertype") + ]], + uniform string metallic9_framerange = "" + [[ + materialx::core::origin("NG_PawnBodyBlack/metallic9/framerange") + ]], + uniform int metallic9_frameoffset = 0 + [[ + materialx::core::origin("NG_PawnBodyBlack/metallic9/frameoffset") + ]], + uniform mx_addressmode_type metallic9_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_PawnBodyBlack/metallic9/frameendaction") + ]], + uniform texture_2d roughness9_file = texture_2d("/chess_set/pawn_shared_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_PawnBodyBlack/roughness9/file") + ]], + uniform string roughness9_layer = "" + [[ + materialx::core::origin("NG_PawnBodyBlack/roughness9/layer") + ]], + float roughness9_default = 0.000000 + [[ + materialx::core::origin("NG_PawnBodyBlack/roughness9/default") + ]], + uniform mx_addressmode_type roughness9_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyBlack/roughness9/uaddressmode") + ]], + uniform mx_addressmode_type roughness9_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyBlack/roughness9/vaddressmode") + ]], + uniform mx_filterlookup_type roughness9_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_PawnBodyBlack/roughness9/filtertype") + ]], + uniform string roughness9_framerange = "" + [[ + materialx::core::origin("NG_PawnBodyBlack/roughness9/framerange") + ]], + uniform int roughness9_frameoffset = 0 + [[ + materialx::core::origin("NG_PawnBodyBlack/roughness9/frameoffset") + ]], + uniform mx_addressmode_type roughness9_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_PawnBodyBlack/roughness9/frameendaction") + ]], + uniform texture_2d normal9_file = texture_2d("/chess_set/pawn_shared_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_PawnBodyBlack/normal9/file") + ]], + uniform string normal9_layer = "" + [[ + materialx::core::origin("NG_PawnBodyBlack/normal9/layer") + ]], + float3 normal9_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_PawnBodyBlack/normal9/default") + ]], + uniform mx_addressmode_type normal9_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyBlack/normal9/uaddressmode") + ]], + uniform mx_addressmode_type normal9_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyBlack/normal9/vaddressmode") + ]], + uniform mx_filterlookup_type normal9_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_PawnBodyBlack/normal9/filtertype") + ]], + uniform string normal9_framerange = "" + [[ + materialx::core::origin("NG_PawnBodyBlack/normal9/framerange") + ]], + uniform int normal9_frameoffset = 0 + [[ + materialx::core::origin("NG_PawnBodyBlack/normal9/frameoffset") + ]], + uniform mx_addressmode_type normal9_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_PawnBodyBlack/normal9/frameendaction") + ]], + float mtlxnormalmap13_scale = 1.000000 + [[ + materialx::core::origin("NG_PawnBodyBlack/mtlxnormalmap13/scale") + ]], + float Pawn_Body_B_base = 1.000000 + [[ + materialx::core::origin("Pawn_Body_B/base") + ]], + float Pawn_Body_B_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/diffuse_roughness") + ]], + float Pawn_Body_B_specular = 1.000000 + [[ + materialx::core::origin("Pawn_Body_B/specular") + ]], + color Pawn_Body_B_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Body_B/specular_color") + ]], + uniform float Pawn_Body_B_specular_IOR = 1.500000 + [[ + materialx::core::origin("Pawn_Body_B/specular_IOR") + ]], + float Pawn_Body_B_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/specular_anisotropy") + ]], + float Pawn_Body_B_specular_rotation = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/specular_rotation") + ]], + float Pawn_Body_B_transmission = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/transmission") + ]], + color Pawn_Body_B_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Body_B/transmission_color") + ]], + float Pawn_Body_B_transmission_depth = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/transmission_depth") + ]], + color Pawn_Body_B_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Pawn_Body_B/transmission_scatter") + ]], + float Pawn_Body_B_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/transmission_scatter_anisotropy") + ]], + float Pawn_Body_B_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/transmission_dispersion") + ]], + float Pawn_Body_B_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/transmission_extra_roughness") + ]], + float Pawn_Body_B_subsurface = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/subsurface") + ]], + float Pawn_Body_B_subsurface_scale = 0.003000 + [[ + materialx::core::origin("Pawn_Body_B/subsurface_scale") + ]], + float Pawn_Body_B_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/subsurface_anisotropy") + ]], + float Pawn_Body_B_sheen = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/sheen") + ]], + color Pawn_Body_B_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Body_B/sheen_color") + ]], + float Pawn_Body_B_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Pawn_Body_B/sheen_roughness") + ]], + float Pawn_Body_B_coat = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/coat") + ]], + color Pawn_Body_B_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Body_B/coat_color") + ]], + float Pawn_Body_B_coat_roughness = 0.100000 + [[ + materialx::core::origin("Pawn_Body_B/coat_roughness") + ]], + float Pawn_Body_B_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/coat_anisotropy") + ]], + float Pawn_Body_B_coat_rotation = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/coat_rotation") + ]], + uniform float Pawn_Body_B_coat_IOR = 1.500000 + [[ + materialx::core::origin("Pawn_Body_B/coat_IOR") + ]], + float Pawn_Body_B_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/coat_affect_color") + ]], + float Pawn_Body_B_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/coat_affect_roughness") + ]], + float Pawn_Body_B_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/thin_film_thickness") + ]], + float Pawn_Body_B_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Pawn_Body_B/thin_film_IOR") + ]], + float Pawn_Body_B_emission = 0.000000 + [[ + materialx::core::origin("Pawn_Body_B/emission") + ]], + color Pawn_Body_B_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Body_B/emission_color") + ]], + color Pawn_Body_B_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Body_B/opacity") + ]], + bool Pawn_Body_B_thin_walled = false + [[ + materialx::core::origin("Pawn_Body_B/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color diffuse9_out = materialx::stdlib_1_8::mx_image_color3(diffuse9_file, diffuse9_layer, diffuse9_default, geomprop_UV0_out1, diffuse9_uaddressmode, diffuse9_vaddressmode, diffuse9_filtertype, diffuse9_framerange, diffuse9_frameoffset, diffuse9_frameendaction, mxp_flip_v:false); + float metallic9_out = materialx::stdlib_1_8::mx_image_float(metallic9_file, metallic9_layer, metallic9_default, geomprop_UV0_out1, metallic9_uaddressmode, metallic9_vaddressmode, metallic9_filtertype, metallic9_framerange, metallic9_frameoffset, metallic9_frameendaction, mxp_flip_v:false); + float roughness9_out = materialx::stdlib_1_8::mx_image_float(roughness9_file, roughness9_layer, roughness9_default, geomprop_UV0_out1, roughness9_uaddressmode, roughness9_vaddressmode, roughness9_filtertype, roughness9_framerange, roughness9_frameoffset, roughness9_frameendaction, mxp_flip_v:false); + float3 normal9_out = materialx::stdlib_1_8::mx_image_vector3(normal9_file, normal9_layer, normal9_default, geomprop_UV0_out1, normal9_uaddressmode, normal9_vaddressmode, normal9_filtertype, normal9_framerange, normal9_frameoffset, normal9_frameendaction, mxp_flip_v:false); + color diffuse9_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(diffuse9_out); + float3 mtlxnormalmap13_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:normal9_out, mxp_scale:mtlxnormalmap13_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Pawn_Body_B_out = NG_standard_surface_surfaceshader_100(Pawn_Body_B_base, diffuse9_out_cm_out, Pawn_Body_B_diffuse_roughness, metallic9_out, Pawn_Body_B_specular, Pawn_Body_B_specular_color, roughness9_out, Pawn_Body_B_specular_IOR, Pawn_Body_B_specular_anisotropy, Pawn_Body_B_specular_rotation, Pawn_Body_B_transmission, Pawn_Body_B_transmission_color, Pawn_Body_B_transmission_depth, Pawn_Body_B_transmission_scatter, Pawn_Body_B_transmission_scatter_anisotropy, Pawn_Body_B_transmission_dispersion, Pawn_Body_B_transmission_extra_roughness, Pawn_Body_B_subsurface, diffuse9_out_cm_out, diffuse9_out_cm_out, Pawn_Body_B_subsurface_scale, Pawn_Body_B_subsurface_anisotropy, Pawn_Body_B_sheen, Pawn_Body_B_sheen_color, Pawn_Body_B_sheen_roughness, Pawn_Body_B_coat, Pawn_Body_B_coat_color, Pawn_Body_B_coat_roughness, Pawn_Body_B_coat_anisotropy, Pawn_Body_B_coat_rotation, Pawn_Body_B_coat_IOR, geomprop_Nworld_out1, Pawn_Body_B_coat_affect_color, Pawn_Body_B_coat_affect_roughness, Pawn_Body_B_thin_film_thickness, Pawn_Body_B_thin_film_IOR, Pawn_Body_B_emission, Pawn_Body_B_emission_color, Pawn_Body_B_opacity, Pawn_Body_B_thin_walled, mtlxnormalmap13_out, geomprop_Tworld_out1); + material M_Pawn_Body_B_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Pawn_Body_B_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Pawn_Body_B_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Pawn_Body_B.msl.frag b/Materials/Examples/StandardSurface/M_Pawn_Body_B.msl.frag new file mode 100644 index 0000000000..114b918e2c --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Body_B.msl.frag @@ -0,0 +1,2961 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int diffuse9_layer; + vec3 diffuse9_default; + int diffuse9_uaddressmode; + int diffuse9_vaddressmode; + int diffuse9_filtertype; + int diffuse9_framerange; + int diffuse9_frameoffset; + int diffuse9_frameendaction; + vec2 diffuse9_uv_scale; + vec2 diffuse9_uv_offset; + int metallic9_layer; + float metallic9_default; + int metallic9_uaddressmode; + int metallic9_vaddressmode; + int metallic9_filtertype; + int metallic9_framerange; + int metallic9_frameoffset; + int metallic9_frameendaction; + vec2 metallic9_uv_scale; + vec2 metallic9_uv_offset; + int roughness9_layer; + float roughness9_default; + int roughness9_uaddressmode; + int roughness9_vaddressmode; + int roughness9_filtertype; + int roughness9_framerange; + int roughness9_frameoffset; + int roughness9_frameendaction; + vec2 roughness9_uv_scale; + vec2 roughness9_uv_offset; + int normal9_layer; + vec3 normal9_default; + int normal9_uaddressmode; + int normal9_vaddressmode; + int normal9_filtertype; + int normal9_framerange; + int normal9_frameoffset; + int normal9_frameendaction; + vec2 normal9_uv_scale; + vec2 normal9_uv_offset; + float mtlxnormalmap13_scale; + float Pawn_Body_B_base; + float Pawn_Body_B_diffuse_roughness; + float Pawn_Body_B_specular; + vec3 Pawn_Body_B_specular_color; + float Pawn_Body_B_specular_IOR; + float Pawn_Body_B_specular_anisotropy; + float Pawn_Body_B_specular_rotation; + float Pawn_Body_B_transmission; + vec3 Pawn_Body_B_transmission_color; + float Pawn_Body_B_transmission_depth; + vec3 Pawn_Body_B_transmission_scatter; + float Pawn_Body_B_transmission_scatter_anisotropy; + float Pawn_Body_B_transmission_dispersion; + float Pawn_Body_B_transmission_extra_roughness; + float Pawn_Body_B_subsurface; + float Pawn_Body_B_subsurface_scale; + float Pawn_Body_B_subsurface_anisotropy; + float Pawn_Body_B_sheen; + vec3 Pawn_Body_B_sheen_color; + float Pawn_Body_B_sheen_roughness; + float Pawn_Body_B_coat; + vec3 Pawn_Body_B_coat_color; + float Pawn_Body_B_coat_roughness; + float Pawn_Body_B_coat_anisotropy; + float Pawn_Body_B_coat_rotation; + float Pawn_Body_B_coat_IOR; + float Pawn_Body_B_coat_affect_color; + float Pawn_Body_B_coat_affect_roughness; + float Pawn_Body_B_thin_film_thickness; + float Pawn_Body_B_thin_film_IOR; + float Pawn_Body_B_emission; + vec3 Pawn_Body_B_emission_color; + vec3 Pawn_Body_B_opacity; + bool Pawn_Body_B_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture diffuse9_file , int diffuse9_layer + + , vec3 diffuse9_default + + , int diffuse9_uaddressmode + + , int diffuse9_vaddressmode + + , int diffuse9_filtertype + + , int diffuse9_framerange + + , int diffuse9_frameoffset + + , int diffuse9_frameendaction + + , vec2 diffuse9_uv_scale + + , vec2 diffuse9_uv_offset + +, MetalTexture metallic9_file , int metallic9_layer + + , float metallic9_default + + , int metallic9_uaddressmode + + , int metallic9_vaddressmode + + , int metallic9_filtertype + + , int metallic9_framerange + + , int metallic9_frameoffset + + , int metallic9_frameendaction + + , vec2 metallic9_uv_scale + + , vec2 metallic9_uv_offset + +, MetalTexture roughness9_file , int roughness9_layer + + , float roughness9_default + + , int roughness9_uaddressmode + + , int roughness9_vaddressmode + + , int roughness9_filtertype + + , int roughness9_framerange + + , int roughness9_frameoffset + + , int roughness9_frameendaction + + , vec2 roughness9_uv_scale + + , vec2 roughness9_uv_offset + +, MetalTexture normal9_file , int normal9_layer + + , vec3 normal9_default + + , int normal9_uaddressmode + + , int normal9_vaddressmode + + , int normal9_filtertype + + , int normal9_framerange + + , int normal9_frameoffset + + , int normal9_frameendaction + + , vec2 normal9_uv_scale + + , vec2 normal9_uv_offset + + , float mtlxnormalmap13_scale + + , float Pawn_Body_B_base + + , float Pawn_Body_B_diffuse_roughness + + , float Pawn_Body_B_specular + + , vec3 Pawn_Body_B_specular_color + + , float Pawn_Body_B_specular_IOR + + , float Pawn_Body_B_specular_anisotropy + + , float Pawn_Body_B_specular_rotation + + , float Pawn_Body_B_transmission + + , vec3 Pawn_Body_B_transmission_color + + , float Pawn_Body_B_transmission_depth + + , vec3 Pawn_Body_B_transmission_scatter + + , float Pawn_Body_B_transmission_scatter_anisotropy + + , float Pawn_Body_B_transmission_dispersion + + , float Pawn_Body_B_transmission_extra_roughness + + , float Pawn_Body_B_subsurface + + , float Pawn_Body_B_subsurface_scale + + , float Pawn_Body_B_subsurface_anisotropy + + , float Pawn_Body_B_sheen + + , vec3 Pawn_Body_B_sheen_color + + , float Pawn_Body_B_sheen_roughness + + , float Pawn_Body_B_coat + + , vec3 Pawn_Body_B_coat_color + + , float Pawn_Body_B_coat_roughness + + , float Pawn_Body_B_coat_anisotropy + + , float Pawn_Body_B_coat_rotation + + , float Pawn_Body_B_coat_IOR + + , float Pawn_Body_B_coat_affect_color + + , float Pawn_Body_B_coat_affect_roughness + + , float Pawn_Body_B_thin_film_thickness + + , float Pawn_Body_B_thin_film_IOR + + , float Pawn_Body_B_emission + + , vec3 Pawn_Body_B_emission_color + + , vec3 Pawn_Body_B_opacity + + , bool Pawn_Body_B_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, diffuse9_file(diffuse9_file) + , diffuse9_layer(diffuse9_layer) + + , diffuse9_default(diffuse9_default) + + , diffuse9_uaddressmode(diffuse9_uaddressmode) + + , diffuse9_vaddressmode(diffuse9_vaddressmode) + + , diffuse9_filtertype(diffuse9_filtertype) + + , diffuse9_framerange(diffuse9_framerange) + + , diffuse9_frameoffset(diffuse9_frameoffset) + + , diffuse9_frameendaction(diffuse9_frameendaction) + + , diffuse9_uv_scale(diffuse9_uv_scale) + + , diffuse9_uv_offset(diffuse9_uv_offset) + +, metallic9_file(metallic9_file) + , metallic9_layer(metallic9_layer) + + , metallic9_default(metallic9_default) + + , metallic9_uaddressmode(metallic9_uaddressmode) + + , metallic9_vaddressmode(metallic9_vaddressmode) + + , metallic9_filtertype(metallic9_filtertype) + + , metallic9_framerange(metallic9_framerange) + + , metallic9_frameoffset(metallic9_frameoffset) + + , metallic9_frameendaction(metallic9_frameendaction) + + , metallic9_uv_scale(metallic9_uv_scale) + + , metallic9_uv_offset(metallic9_uv_offset) + +, roughness9_file(roughness9_file) + , roughness9_layer(roughness9_layer) + + , roughness9_default(roughness9_default) + + , roughness9_uaddressmode(roughness9_uaddressmode) + + , roughness9_vaddressmode(roughness9_vaddressmode) + + , roughness9_filtertype(roughness9_filtertype) + + , roughness9_framerange(roughness9_framerange) + + , roughness9_frameoffset(roughness9_frameoffset) + + , roughness9_frameendaction(roughness9_frameendaction) + + , roughness9_uv_scale(roughness9_uv_scale) + + , roughness9_uv_offset(roughness9_uv_offset) + +, normal9_file(normal9_file) + , normal9_layer(normal9_layer) + + , normal9_default(normal9_default) + + , normal9_uaddressmode(normal9_uaddressmode) + + , normal9_vaddressmode(normal9_vaddressmode) + + , normal9_filtertype(normal9_filtertype) + + , normal9_framerange(normal9_framerange) + + , normal9_frameoffset(normal9_frameoffset) + + , normal9_frameendaction(normal9_frameendaction) + + , normal9_uv_scale(normal9_uv_scale) + + , normal9_uv_offset(normal9_uv_offset) + + , mtlxnormalmap13_scale(mtlxnormalmap13_scale) + + , Pawn_Body_B_base(Pawn_Body_B_base) + + , Pawn_Body_B_diffuse_roughness(Pawn_Body_B_diffuse_roughness) + + , Pawn_Body_B_specular(Pawn_Body_B_specular) + + , Pawn_Body_B_specular_color(Pawn_Body_B_specular_color) + + , Pawn_Body_B_specular_IOR(Pawn_Body_B_specular_IOR) + + , Pawn_Body_B_specular_anisotropy(Pawn_Body_B_specular_anisotropy) + + , Pawn_Body_B_specular_rotation(Pawn_Body_B_specular_rotation) + + , Pawn_Body_B_transmission(Pawn_Body_B_transmission) + + , Pawn_Body_B_transmission_color(Pawn_Body_B_transmission_color) + + , Pawn_Body_B_transmission_depth(Pawn_Body_B_transmission_depth) + + , Pawn_Body_B_transmission_scatter(Pawn_Body_B_transmission_scatter) + + , Pawn_Body_B_transmission_scatter_anisotropy(Pawn_Body_B_transmission_scatter_anisotropy) + + , Pawn_Body_B_transmission_dispersion(Pawn_Body_B_transmission_dispersion) + + , Pawn_Body_B_transmission_extra_roughness(Pawn_Body_B_transmission_extra_roughness) + + , Pawn_Body_B_subsurface(Pawn_Body_B_subsurface) + + , Pawn_Body_B_subsurface_scale(Pawn_Body_B_subsurface_scale) + + , Pawn_Body_B_subsurface_anisotropy(Pawn_Body_B_subsurface_anisotropy) + + , Pawn_Body_B_sheen(Pawn_Body_B_sheen) + + , Pawn_Body_B_sheen_color(Pawn_Body_B_sheen_color) + + , Pawn_Body_B_sheen_roughness(Pawn_Body_B_sheen_roughness) + + , Pawn_Body_B_coat(Pawn_Body_B_coat) + + , Pawn_Body_B_coat_color(Pawn_Body_B_coat_color) + + , Pawn_Body_B_coat_roughness(Pawn_Body_B_coat_roughness) + + , Pawn_Body_B_coat_anisotropy(Pawn_Body_B_coat_anisotropy) + + , Pawn_Body_B_coat_rotation(Pawn_Body_B_coat_rotation) + + , Pawn_Body_B_coat_IOR(Pawn_Body_B_coat_IOR) + + , Pawn_Body_B_coat_affect_color(Pawn_Body_B_coat_affect_color) + + , Pawn_Body_B_coat_affect_roughness(Pawn_Body_B_coat_affect_roughness) + + , Pawn_Body_B_thin_film_thickness(Pawn_Body_B_thin_film_thickness) + + , Pawn_Body_B_thin_film_IOR(Pawn_Body_B_thin_film_IOR) + + , Pawn_Body_B_emission(Pawn_Body_B_emission) + + , Pawn_Body_B_emission_color(Pawn_Body_B_emission_color) + + , Pawn_Body_B_opacity(Pawn_Body_B_opacity) + + , Pawn_Body_B_thin_walled(Pawn_Body_B_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture diffuse9_file; + int diffuse9_layer; + + + vec3 diffuse9_default; + + + int diffuse9_uaddressmode; + + + int diffuse9_vaddressmode; + + + int diffuse9_filtertype; + + + int diffuse9_framerange; + + + int diffuse9_frameoffset; + + + int diffuse9_frameendaction; + + + vec2 diffuse9_uv_scale; + + + vec2 diffuse9_uv_offset; + + +MetalTexture metallic9_file; + int metallic9_layer; + + + float metallic9_default; + + + int metallic9_uaddressmode; + + + int metallic9_vaddressmode; + + + int metallic9_filtertype; + + + int metallic9_framerange; + + + int metallic9_frameoffset; + + + int metallic9_frameendaction; + + + vec2 metallic9_uv_scale; + + + vec2 metallic9_uv_offset; + + +MetalTexture roughness9_file; + int roughness9_layer; + + + float roughness9_default; + + + int roughness9_uaddressmode; + + + int roughness9_vaddressmode; + + + int roughness9_filtertype; + + + int roughness9_framerange; + + + int roughness9_frameoffset; + + + int roughness9_frameendaction; + + + vec2 roughness9_uv_scale; + + + vec2 roughness9_uv_offset; + + +MetalTexture normal9_file; + int normal9_layer; + + + vec3 normal9_default; + + + int normal9_uaddressmode; + + + int normal9_vaddressmode; + + + int normal9_filtertype; + + + int normal9_framerange; + + + int normal9_frameoffset; + + + int normal9_frameendaction; + + + vec2 normal9_uv_scale; + + + vec2 normal9_uv_offset; + + + float mtlxnormalmap13_scale; + + + float Pawn_Body_B_base; + + + float Pawn_Body_B_diffuse_roughness; + + + float Pawn_Body_B_specular; + + + vec3 Pawn_Body_B_specular_color; + + + float Pawn_Body_B_specular_IOR; + + + float Pawn_Body_B_specular_anisotropy; + + + float Pawn_Body_B_specular_rotation; + + + float Pawn_Body_B_transmission; + + + vec3 Pawn_Body_B_transmission_color; + + + float Pawn_Body_B_transmission_depth; + + + vec3 Pawn_Body_B_transmission_scatter; + + + float Pawn_Body_B_transmission_scatter_anisotropy; + + + float Pawn_Body_B_transmission_dispersion; + + + float Pawn_Body_B_transmission_extra_roughness; + + + float Pawn_Body_B_subsurface; + + + float Pawn_Body_B_subsurface_scale; + + + float Pawn_Body_B_subsurface_anisotropy; + + + float Pawn_Body_B_sheen; + + + vec3 Pawn_Body_B_sheen_color; + + + float Pawn_Body_B_sheen_roughness; + + + float Pawn_Body_B_coat; + + + vec3 Pawn_Body_B_coat_color; + + + float Pawn_Body_B_coat_roughness; + + + float Pawn_Body_B_coat_anisotropy; + + + float Pawn_Body_B_coat_rotation; + + + float Pawn_Body_B_coat_IOR; + + + float Pawn_Body_B_coat_affect_color; + + + float Pawn_Body_B_coat_affect_roughness; + + + float Pawn_Body_B_thin_film_thickness; + + + float Pawn_Body_B_thin_film_IOR; + + + float Pawn_Body_B_emission; + + + vec3 Pawn_Body_B_emission_color; + + + vec3 Pawn_Body_B_opacity; + + + bool Pawn_Body_B_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse9_out = vec3(0.0); + mx_image_color3(diffuse9_file, diffuse9_layer, diffuse9_default, geomprop_UV0_out1, diffuse9_uaddressmode, diffuse9_vaddressmode, diffuse9_filtertype, diffuse9_framerange, diffuse9_frameoffset, diffuse9_frameendaction, diffuse9_uv_scale, diffuse9_uv_offset, diffuse9_out); + float metallic9_out = 0.0; + mx_image_float(metallic9_file, metallic9_layer, metallic9_default, geomprop_UV0_out1, metallic9_uaddressmode, metallic9_vaddressmode, metallic9_filtertype, metallic9_framerange, metallic9_frameoffset, metallic9_frameendaction, metallic9_uv_scale, metallic9_uv_offset, metallic9_out); + float roughness9_out = 0.0; + mx_image_float(roughness9_file, roughness9_layer, roughness9_default, geomprop_UV0_out1, roughness9_uaddressmode, roughness9_vaddressmode, roughness9_filtertype, roughness9_framerange, roughness9_frameoffset, roughness9_frameendaction, roughness9_uv_scale, roughness9_uv_offset, roughness9_out); + vec3 normal9_out = vec3(0.0); + mx_image_vector3(normal9_file, normal9_layer, normal9_default, geomprop_UV0_out1, normal9_uaddressmode, normal9_vaddressmode, normal9_filtertype, normal9_framerange, normal9_frameoffset, normal9_frameendaction, normal9_uv_scale, normal9_uv_offset, normal9_out); + vec3 diffuse9_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse9_out, diffuse9_out_cm_out); + vec3 mtlxnormalmap13_out = vec3(0.0); + mx_normalmap_float(normal9_out, mtlxnormalmap13_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap13_out); + surfaceshader Pawn_Body_B_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Pawn_Body_B_base, diffuse9_out_cm_out, Pawn_Body_B_diffuse_roughness, metallic9_out, Pawn_Body_B_specular, Pawn_Body_B_specular_color, roughness9_out, Pawn_Body_B_specular_IOR, Pawn_Body_B_specular_anisotropy, Pawn_Body_B_specular_rotation, Pawn_Body_B_transmission, Pawn_Body_B_transmission_color, Pawn_Body_B_transmission_depth, Pawn_Body_B_transmission_scatter, Pawn_Body_B_transmission_scatter_anisotropy, Pawn_Body_B_transmission_dispersion, Pawn_Body_B_transmission_extra_roughness, Pawn_Body_B_subsurface, diffuse9_out_cm_out, diffuse9_out_cm_out, Pawn_Body_B_subsurface_scale, Pawn_Body_B_subsurface_anisotropy, Pawn_Body_B_sheen, Pawn_Body_B_sheen_color, Pawn_Body_B_sheen_roughness, Pawn_Body_B_coat, Pawn_Body_B_coat_color, Pawn_Body_B_coat_roughness, Pawn_Body_B_coat_anisotropy, Pawn_Body_B_coat_rotation, Pawn_Body_B_coat_IOR, geomprop_Nworld_out1, Pawn_Body_B_coat_affect_color, Pawn_Body_B_coat_affect_roughness, Pawn_Body_B_thin_film_thickness, Pawn_Body_B_thin_film_IOR, Pawn_Body_B_emission, Pawn_Body_B_emission_color, Pawn_Body_B_opacity, Pawn_Body_B_thin_walled, mtlxnormalmap13_out, geomprop_Tworld_out1, Pawn_Body_B_out); + material M_Pawn_Body_B_out = Pawn_Body_B_out; + out1 = float4(M_Pawn_Body_B_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d diffuse9_file_tex [[texture(0)]], sampler diffuse9_file_sampler [[sampler(0)]] +, texture2d metallic9_file_tex [[texture(1)]], sampler metallic9_file_sampler [[sampler(1)]] +, texture2d roughness9_file_tex [[texture(2)]], sampler roughness9_file_sampler [[sampler(2)]] +, texture2d normal9_file_tex [[texture(3)]], sampler normal9_file_sampler [[sampler(3)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(4)]], sampler u_envRadiance_sampler [[sampler(4)]] +, texture2d u_envIrradiance_tex [[texture(5)]], sampler u_envIrradiance_sampler [[sampler(5)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +diffuse9_file_tex, diffuse9_file_sampler } + , u_pub.diffuse9_layer + , u_pub.diffuse9_default + , u_pub.diffuse9_uaddressmode + , u_pub.diffuse9_vaddressmode + , u_pub.diffuse9_filtertype + , u_pub.diffuse9_framerange + , u_pub.diffuse9_frameoffset + , u_pub.diffuse9_frameendaction + , u_pub.diffuse9_uv_scale + , u_pub.diffuse9_uv_offset +, MetalTexture { +metallic9_file_tex, metallic9_file_sampler } + , u_pub.metallic9_layer + , u_pub.metallic9_default + , u_pub.metallic9_uaddressmode + , u_pub.metallic9_vaddressmode + , u_pub.metallic9_filtertype + , u_pub.metallic9_framerange + , u_pub.metallic9_frameoffset + , u_pub.metallic9_frameendaction + , u_pub.metallic9_uv_scale + , u_pub.metallic9_uv_offset +, MetalTexture { +roughness9_file_tex, roughness9_file_sampler } + , u_pub.roughness9_layer + , u_pub.roughness9_default + , u_pub.roughness9_uaddressmode + , u_pub.roughness9_vaddressmode + , u_pub.roughness9_filtertype + , u_pub.roughness9_framerange + , u_pub.roughness9_frameoffset + , u_pub.roughness9_frameendaction + , u_pub.roughness9_uv_scale + , u_pub.roughness9_uv_offset +, MetalTexture { +normal9_file_tex, normal9_file_sampler } + , u_pub.normal9_layer + , u_pub.normal9_default + , u_pub.normal9_uaddressmode + , u_pub.normal9_vaddressmode + , u_pub.normal9_filtertype + , u_pub.normal9_framerange + , u_pub.normal9_frameoffset + , u_pub.normal9_frameendaction + , u_pub.normal9_uv_scale + , u_pub.normal9_uv_offset + , u_pub.mtlxnormalmap13_scale + , u_pub.Pawn_Body_B_base + , u_pub.Pawn_Body_B_diffuse_roughness + , u_pub.Pawn_Body_B_specular + , u_pub.Pawn_Body_B_specular_color + , u_pub.Pawn_Body_B_specular_IOR + , u_pub.Pawn_Body_B_specular_anisotropy + , u_pub.Pawn_Body_B_specular_rotation + , u_pub.Pawn_Body_B_transmission + , u_pub.Pawn_Body_B_transmission_color + , u_pub.Pawn_Body_B_transmission_depth + , u_pub.Pawn_Body_B_transmission_scatter + , u_pub.Pawn_Body_B_transmission_scatter_anisotropy + , u_pub.Pawn_Body_B_transmission_dispersion + , u_pub.Pawn_Body_B_transmission_extra_roughness + , u_pub.Pawn_Body_B_subsurface + , u_pub.Pawn_Body_B_subsurface_scale + , u_pub.Pawn_Body_B_subsurface_anisotropy + , u_pub.Pawn_Body_B_sheen + , u_pub.Pawn_Body_B_sheen_color + , u_pub.Pawn_Body_B_sheen_roughness + , u_pub.Pawn_Body_B_coat + , u_pub.Pawn_Body_B_coat_color + , u_pub.Pawn_Body_B_coat_roughness + , u_pub.Pawn_Body_B_coat_anisotropy + , u_pub.Pawn_Body_B_coat_rotation + , u_pub.Pawn_Body_B_coat_IOR + , u_pub.Pawn_Body_B_coat_affect_color + , u_pub.Pawn_Body_B_coat_affect_roughness + , u_pub.Pawn_Body_B_thin_film_thickness + , u_pub.Pawn_Body_B_thin_film_IOR + , u_pub.Pawn_Body_B_emission + , u_pub.Pawn_Body_B_emission_color + , u_pub.Pawn_Body_B_opacity + , u_pub.Pawn_Body_B_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Body_B.msl.vert b/Materials/Examples/StandardSurface/M_Pawn_Body_B.msl.vert new file mode 100644 index 0000000000..026a756290 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Body_B.msl.vert @@ -0,0 +1,127 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'diffuse9'. Function already called in this scope. + // Omitted node 'metallic9'. Function already called in this scope. + // Omitted node 'roughness9'. Function already called in this scope. + // Omitted node 'normal9'. Function already called in this scope. + // Omitted node 'diffuse9_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap13'. Function already called in this scope. + // Omitted node 'Pawn_Body_B'. Function already called in this scope. + // Omitted node 'M_Pawn_Body_B'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Body_B.osl b/Materials/Examples/StandardSurface/M_Pawn_Body_B.osl new file mode 100644 index 0000000000..dd713a3b6b --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Body_B.osl @@ -0,0 +1,678 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Pawn_Body_B +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Pawn_Body_B" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string diffuse9_file = "chess_set/pawn_black_base_color.jpg" + [[ + string widget = "filename" + ]], + string diffuse9_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string diffuse9_layer = "", + color diffuse9_default = color(0.000000, 0.000000, 0.000000), + string diffuse9_uaddressmode = "periodic", + string diffuse9_vaddressmode = "periodic", + string diffuse9_filtertype = "linear", + string diffuse9_framerange = "", + int diffuse9_frameoffset = 0 + [[ + string widget = "number" + ]], + string diffuse9_frameendaction = "constant", + string metallic9_file = "chess_set/pawn_shared_metallic.jpg" + [[ + string widget = "filename" + ]], + string metallic9_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string metallic9_layer = "", + float metallic9_default = 0.000000 + [[ + string widget = "number" + ]], + string metallic9_uaddressmode = "periodic", + string metallic9_vaddressmode = "periodic", + string metallic9_filtertype = "linear", + string metallic9_framerange = "", + int metallic9_frameoffset = 0 + [[ + string widget = "number" + ]], + string metallic9_frameendaction = "constant", + string roughness9_file = "chess_set/pawn_shared_roughness.jpg" + [[ + string widget = "filename" + ]], + string roughness9_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string roughness9_layer = "", + float roughness9_default = 0.000000 + [[ + string widget = "number" + ]], + string roughness9_uaddressmode = "periodic", + string roughness9_vaddressmode = "periodic", + string roughness9_filtertype = "linear", + string roughness9_framerange = "", + int roughness9_frameoffset = 0 + [[ + string widget = "number" + ]], + string roughness9_frameendaction = "constant", + string normal9_file = "chess_set/pawn_shared_normal.jpg" + [[ + string widget = "filename" + ]], + string normal9_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string normal9_layer = "", + vector normal9_default = vector(0.000000, 0.000000, 0.000000), + string normal9_uaddressmode = "periodic", + string normal9_vaddressmode = "periodic", + string normal9_filtertype = "linear", + string normal9_framerange = "", + int normal9_frameoffset = 0 + [[ + string widget = "number" + ]], + string normal9_frameendaction = "constant", + float mtlxnormalmap13_scale = 1.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_base = 1.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_specular = 1.000000 + [[ + string widget = "number" + ]], + color Pawn_Body_B_specular_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Body_B_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_transmission = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Body_B_transmission_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Body_B_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Body_B_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Pawn_Body_B_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_subsurface = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Body_B_sheen_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Body_B_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_coat = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Body_B_coat_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Body_B_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Pawn_Body_B_emission = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Body_B_emission_color = color(1.000000, 1.000000, 1.000000), + color Pawn_Body_B_opacity = color(1.000000, 1.000000, 1.000000), + int Pawn_Body_B_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource diffuse9_file_ = {diffuse9_file, diffuse9_file_colorspace}; + textureresource metallic9_file_ = {metallic9_file, metallic9_file_colorspace}; + textureresource roughness9_file_ = {roughness9_file, roughness9_file_colorspace}; + textureresource normal9_file_ = {normal9_file, normal9_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color diffuse9_out = color(0.0); + mx_image_color3(diffuse9_file_, diffuse9_layer, diffuse9_default, geomprop_UV0_out1, diffuse9_uaddressmode, diffuse9_vaddressmode, diffuse9_filtertype, diffuse9_framerange, diffuse9_frameoffset, diffuse9_frameendaction, diffuse9_out); + float metallic9_out = 0.0; + mx_image_float(metallic9_file_, metallic9_layer, metallic9_default, geomprop_UV0_out1, metallic9_uaddressmode, metallic9_vaddressmode, metallic9_filtertype, metallic9_framerange, metallic9_frameoffset, metallic9_frameendaction, metallic9_out); + float roughness9_out = 0.0; + mx_image_float(roughness9_file_, roughness9_layer, roughness9_default, geomprop_UV0_out1, roughness9_uaddressmode, roughness9_vaddressmode, roughness9_filtertype, roughness9_framerange, roughness9_frameoffset, roughness9_frameendaction, roughness9_out); + vector normal9_out = vector(0.0); + mx_image_vector3(normal9_file_, normal9_layer, normal9_default, geomprop_UV0_out1, normal9_uaddressmode, normal9_vaddressmode, normal9_filtertype, normal9_framerange, normal9_frameoffset, normal9_frameendaction, normal9_out); + color diffuse9_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse9_out, diffuse9_out_cm_out); + vector mtlxnormalmap13_out = vector(0.0); + mx_normalmap_float(normal9_out, mtlxnormalmap13_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap13_out); + surfaceshader Pawn_Body_B_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Pawn_Body_B_base, diffuse9_out_cm_out, Pawn_Body_B_diffuse_roughness, metallic9_out, Pawn_Body_B_specular, Pawn_Body_B_specular_color, roughness9_out, Pawn_Body_B_specular_IOR, Pawn_Body_B_specular_anisotropy, Pawn_Body_B_specular_rotation, Pawn_Body_B_transmission, Pawn_Body_B_transmission_color, Pawn_Body_B_transmission_depth, Pawn_Body_B_transmission_scatter, Pawn_Body_B_transmission_scatter_anisotropy, Pawn_Body_B_transmission_dispersion, Pawn_Body_B_transmission_extra_roughness, Pawn_Body_B_subsurface, diffuse9_out_cm_out, diffuse9_out_cm_out, Pawn_Body_B_subsurface_scale, Pawn_Body_B_subsurface_anisotropy, Pawn_Body_B_sheen, Pawn_Body_B_sheen_color, Pawn_Body_B_sheen_roughness, Pawn_Body_B_coat, Pawn_Body_B_coat_color, Pawn_Body_B_coat_roughness, Pawn_Body_B_coat_anisotropy, Pawn_Body_B_coat_rotation, Pawn_Body_B_coat_IOR, geomprop_Nworld_out1, Pawn_Body_B_coat_affect_color, Pawn_Body_B_coat_affect_roughness, Pawn_Body_B_thin_film_thickness, Pawn_Body_B_thin_film_IOR, Pawn_Body_B_emission, Pawn_Body_B_emission_color, Pawn_Body_B_opacity, Pawn_Body_B_thin_walled, mtlxnormalmap13_out, geomprop_Tworld_out1, Pawn_Body_B_out); + MATERIAL M_Pawn_Body_B_out = mx_surfacematerial(Pawn_Body_B_out, backsurfaceshader, displacementshader1); + out = M_Pawn_Body_B_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Body_W.glsl.frag b/Materials/Examples/StandardSurface/M_Pawn_Body_W.glsl.frag new file mode 100644 index 0000000000..45fe4d114d --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Body_W.glsl.frag @@ -0,0 +1,2013 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D diffuse8_file; +uniform int diffuse8_layer = 0; +uniform vec3 diffuse8_default = vec3(0.000000, 0.000000, 0.000000); +uniform int diffuse8_uaddressmode = 2; +uniform int diffuse8_vaddressmode = 2; +uniform int diffuse8_filtertype = 1; +uniform int diffuse8_framerange = 0; +uniform int diffuse8_frameoffset = 0; +uniform int diffuse8_frameendaction = 0; +uniform vec2 diffuse8_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 diffuse8_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D metallic8_file; +uniform int metallic8_layer = 0; +uniform float metallic8_default = 0.000000; +uniform int metallic8_uaddressmode = 2; +uniform int metallic8_vaddressmode = 2; +uniform int metallic8_filtertype = 1; +uniform int metallic8_framerange = 0; +uniform int metallic8_frameoffset = 0; +uniform int metallic8_frameendaction = 0; +uniform vec2 metallic8_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 metallic8_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D roughness8_file; +uniform int roughness8_layer = 0; +uniform float roughness8_default = 0.000000; +uniform int roughness8_uaddressmode = 2; +uniform int roughness8_vaddressmode = 2; +uniform int roughness8_filtertype = 1; +uniform int roughness8_framerange = 0; +uniform int roughness8_frameoffset = 0; +uniform int roughness8_frameendaction = 0; +uniform vec2 roughness8_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 roughness8_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D normal8_file; +uniform int normal8_layer = 0; +uniform vec3 normal8_default = vec3(0.000000, 0.000000, 0.000000); +uniform int normal8_uaddressmode = 2; +uniform int normal8_vaddressmode = 2; +uniform int normal8_filtertype = 1; +uniform int normal8_framerange = 0; +uniform int normal8_frameoffset = 0; +uniform int normal8_frameendaction = 0; +uniform vec2 normal8_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 normal8_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap10_scale = 1.000000; +uniform float Pawn_Body_W_base = 1.000000; +uniform float Pawn_Body_W_diffuse_roughness = 0.000000; +uniform float Pawn_Body_W_specular = 1.000000; +uniform vec3 Pawn_Body_W_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Body_W_specular_IOR = 1.500000; +uniform float Pawn_Body_W_specular_anisotropy = 0.000000; +uniform float Pawn_Body_W_specular_rotation = 0.000000; +uniform float Pawn_Body_W_transmission = 0.000000; +uniform vec3 Pawn_Body_W_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Body_W_transmission_depth = 0.000000; +uniform vec3 Pawn_Body_W_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Pawn_Body_W_transmission_scatter_anisotropy = 0.000000; +uniform float Pawn_Body_W_transmission_dispersion = 0.000000; +uniform float Pawn_Body_W_transmission_extra_roughness = 0.000000; +uniform float Pawn_Body_W_subsurface = 0.000000; +uniform float Pawn_Body_W_subsurface_scale = 0.003000; +uniform float Pawn_Body_W_subsurface_anisotropy = 0.000000; +uniform float Pawn_Body_W_sheen = 0.000000; +uniform vec3 Pawn_Body_W_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Body_W_sheen_roughness = 0.300000; +uniform float Pawn_Body_W_coat = 0.000000; +uniform vec3 Pawn_Body_W_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Body_W_coat_roughness = 0.100000; +uniform float Pawn_Body_W_coat_anisotropy = 0.000000; +uniform float Pawn_Body_W_coat_rotation = 0.000000; +uniform float Pawn_Body_W_coat_IOR = 1.500000; +uniform float Pawn_Body_W_coat_affect_color = 0.000000; +uniform float Pawn_Body_W_coat_affect_roughness = 0.000000; +uniform float Pawn_Body_W_thin_film_thickness = 0.000000; +uniform float Pawn_Body_W_thin_film_IOR = 1.500000; +uniform float Pawn_Body_W_emission = 0.000000; +uniform vec3 Pawn_Body_W_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Pawn_Body_W_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Pawn_Body_W_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse8_out = vec3(0.0); + mx_image_color3(diffuse8_file, diffuse8_layer, diffuse8_default, geomprop_UV0_out1, diffuse8_uaddressmode, diffuse8_vaddressmode, diffuse8_filtertype, diffuse8_framerange, diffuse8_frameoffset, diffuse8_frameendaction, diffuse8_uv_scale, diffuse8_uv_offset, diffuse8_out); + float metallic8_out = 0.0; + mx_image_float(metallic8_file, metallic8_layer, metallic8_default, geomprop_UV0_out1, metallic8_uaddressmode, metallic8_vaddressmode, metallic8_filtertype, metallic8_framerange, metallic8_frameoffset, metallic8_frameendaction, metallic8_uv_scale, metallic8_uv_offset, metallic8_out); + float roughness8_out = 0.0; + mx_image_float(roughness8_file, roughness8_layer, roughness8_default, geomprop_UV0_out1, roughness8_uaddressmode, roughness8_vaddressmode, roughness8_filtertype, roughness8_framerange, roughness8_frameoffset, roughness8_frameendaction, roughness8_uv_scale, roughness8_uv_offset, roughness8_out); + vec3 normal8_out = vec3(0.0); + mx_image_vector3(normal8_file, normal8_layer, normal8_default, geomprop_UV0_out1, normal8_uaddressmode, normal8_vaddressmode, normal8_filtertype, normal8_framerange, normal8_frameoffset, normal8_frameendaction, normal8_uv_scale, normal8_uv_offset, normal8_out); + vec3 diffuse8_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse8_out, diffuse8_out_cm_out); + vec3 mtlxnormalmap10_out = vec3(0.0); + mx_normalmap_float(normal8_out, mtlxnormalmap10_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap10_out); + surfaceshader Pawn_Body_W_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Pawn_Body_W_base, diffuse8_out_cm_out, Pawn_Body_W_diffuse_roughness, metallic8_out, Pawn_Body_W_specular, Pawn_Body_W_specular_color, roughness8_out, Pawn_Body_W_specular_IOR, Pawn_Body_W_specular_anisotropy, Pawn_Body_W_specular_rotation, Pawn_Body_W_transmission, Pawn_Body_W_transmission_color, Pawn_Body_W_transmission_depth, Pawn_Body_W_transmission_scatter, Pawn_Body_W_transmission_scatter_anisotropy, Pawn_Body_W_transmission_dispersion, Pawn_Body_W_transmission_extra_roughness, Pawn_Body_W_subsurface, diffuse8_out_cm_out, diffuse8_out_cm_out, Pawn_Body_W_subsurface_scale, Pawn_Body_W_subsurface_anisotropy, Pawn_Body_W_sheen, Pawn_Body_W_sheen_color, Pawn_Body_W_sheen_roughness, Pawn_Body_W_coat, Pawn_Body_W_coat_color, Pawn_Body_W_coat_roughness, Pawn_Body_W_coat_anisotropy, Pawn_Body_W_coat_rotation, Pawn_Body_W_coat_IOR, geomprop_Nworld_out1, Pawn_Body_W_coat_affect_color, Pawn_Body_W_coat_affect_roughness, Pawn_Body_W_thin_film_thickness, Pawn_Body_W_thin_film_IOR, Pawn_Body_W_emission, Pawn_Body_W_emission_color, Pawn_Body_W_opacity, Pawn_Body_W_thin_walled, mtlxnormalmap10_out, geomprop_Tworld_out1, Pawn_Body_W_out); + material M_Pawn_Body_W_out = Pawn_Body_W_out; + out1 = vec4(M_Pawn_Body_W_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Body_W.glsl.vert b/Materials/Examples/StandardSurface/M_Pawn_Body_W.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Body_W.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Body_W.mdl b/Materials/Examples/StandardSurface/M_Pawn_Body_W.mdl new file mode 100644 index 0000000000..22f8a4a164 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Body_W.mdl @@ -0,0 +1,506 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Pawn_Body_W +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d diffuse8_file = texture_2d("/chess_set/pawn_white_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_PawnBodyWhite/diffuse8/file") + ]], + uniform string diffuse8_layer = "" + [[ + materialx::core::origin("NG_PawnBodyWhite/diffuse8/layer") + ]], + color diffuse8_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_PawnBodyWhite/diffuse8/default") + ]], + uniform mx_addressmode_type diffuse8_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyWhite/diffuse8/uaddressmode") + ]], + uniform mx_addressmode_type diffuse8_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyWhite/diffuse8/vaddressmode") + ]], + uniform mx_filterlookup_type diffuse8_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_PawnBodyWhite/diffuse8/filtertype") + ]], + uniform string diffuse8_framerange = "" + [[ + materialx::core::origin("NG_PawnBodyWhite/diffuse8/framerange") + ]], + uniform int diffuse8_frameoffset = 0 + [[ + materialx::core::origin("NG_PawnBodyWhite/diffuse8/frameoffset") + ]], + uniform mx_addressmode_type diffuse8_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_PawnBodyWhite/diffuse8/frameendaction") + ]], + uniform texture_2d metallic8_file = texture_2d("/chess_set/pawn_shared_metallic.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_PawnBodyWhite/metallic8/file") + ]], + uniform string metallic8_layer = "" + [[ + materialx::core::origin("NG_PawnBodyWhite/metallic8/layer") + ]], + float metallic8_default = 0.000000 + [[ + materialx::core::origin("NG_PawnBodyWhite/metallic8/default") + ]], + uniform mx_addressmode_type metallic8_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyWhite/metallic8/uaddressmode") + ]], + uniform mx_addressmode_type metallic8_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyWhite/metallic8/vaddressmode") + ]], + uniform mx_filterlookup_type metallic8_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_PawnBodyWhite/metallic8/filtertype") + ]], + uniform string metallic8_framerange = "" + [[ + materialx::core::origin("NG_PawnBodyWhite/metallic8/framerange") + ]], + uniform int metallic8_frameoffset = 0 + [[ + materialx::core::origin("NG_PawnBodyWhite/metallic8/frameoffset") + ]], + uniform mx_addressmode_type metallic8_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_PawnBodyWhite/metallic8/frameendaction") + ]], + uniform texture_2d roughness8_file = texture_2d("/chess_set/pawn_shared_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_PawnBodyWhite/roughness8/file") + ]], + uniform string roughness8_layer = "" + [[ + materialx::core::origin("NG_PawnBodyWhite/roughness8/layer") + ]], + float roughness8_default = 0.000000 + [[ + materialx::core::origin("NG_PawnBodyWhite/roughness8/default") + ]], + uniform mx_addressmode_type roughness8_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyWhite/roughness8/uaddressmode") + ]], + uniform mx_addressmode_type roughness8_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyWhite/roughness8/vaddressmode") + ]], + uniform mx_filterlookup_type roughness8_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_PawnBodyWhite/roughness8/filtertype") + ]], + uniform string roughness8_framerange = "" + [[ + materialx::core::origin("NG_PawnBodyWhite/roughness8/framerange") + ]], + uniform int roughness8_frameoffset = 0 + [[ + materialx::core::origin("NG_PawnBodyWhite/roughness8/frameoffset") + ]], + uniform mx_addressmode_type roughness8_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_PawnBodyWhite/roughness8/frameendaction") + ]], + uniform texture_2d normal8_file = texture_2d("/chess_set/pawn_shared_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_PawnBodyWhite/normal8/file") + ]], + uniform string normal8_layer = "" + [[ + materialx::core::origin("NG_PawnBodyWhite/normal8/layer") + ]], + float3 normal8_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_PawnBodyWhite/normal8/default") + ]], + uniform mx_addressmode_type normal8_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyWhite/normal8/uaddressmode") + ]], + uniform mx_addressmode_type normal8_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnBodyWhite/normal8/vaddressmode") + ]], + uniform mx_filterlookup_type normal8_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_PawnBodyWhite/normal8/filtertype") + ]], + uniform string normal8_framerange = "" + [[ + materialx::core::origin("NG_PawnBodyWhite/normal8/framerange") + ]], + uniform int normal8_frameoffset = 0 + [[ + materialx::core::origin("NG_PawnBodyWhite/normal8/frameoffset") + ]], + uniform mx_addressmode_type normal8_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_PawnBodyWhite/normal8/frameendaction") + ]], + float mtlxnormalmap10_scale = 1.000000 + [[ + materialx::core::origin("NG_PawnBodyWhite/mtlxnormalmap10/scale") + ]], + float Pawn_Body_W_base = 1.000000 + [[ + materialx::core::origin("Pawn_Body_W/base") + ]], + float Pawn_Body_W_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/diffuse_roughness") + ]], + float Pawn_Body_W_specular = 1.000000 + [[ + materialx::core::origin("Pawn_Body_W/specular") + ]], + color Pawn_Body_W_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Body_W/specular_color") + ]], + uniform float Pawn_Body_W_specular_IOR = 1.500000 + [[ + materialx::core::origin("Pawn_Body_W/specular_IOR") + ]], + float Pawn_Body_W_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/specular_anisotropy") + ]], + float Pawn_Body_W_specular_rotation = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/specular_rotation") + ]], + float Pawn_Body_W_transmission = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/transmission") + ]], + color Pawn_Body_W_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Body_W/transmission_color") + ]], + float Pawn_Body_W_transmission_depth = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/transmission_depth") + ]], + color Pawn_Body_W_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Pawn_Body_W/transmission_scatter") + ]], + float Pawn_Body_W_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/transmission_scatter_anisotropy") + ]], + float Pawn_Body_W_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/transmission_dispersion") + ]], + float Pawn_Body_W_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/transmission_extra_roughness") + ]], + float Pawn_Body_W_subsurface = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/subsurface") + ]], + float Pawn_Body_W_subsurface_scale = 0.003000 + [[ + materialx::core::origin("Pawn_Body_W/subsurface_scale") + ]], + float Pawn_Body_W_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/subsurface_anisotropy") + ]], + float Pawn_Body_W_sheen = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/sheen") + ]], + color Pawn_Body_W_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Body_W/sheen_color") + ]], + float Pawn_Body_W_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Pawn_Body_W/sheen_roughness") + ]], + float Pawn_Body_W_coat = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/coat") + ]], + color Pawn_Body_W_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Body_W/coat_color") + ]], + float Pawn_Body_W_coat_roughness = 0.100000 + [[ + materialx::core::origin("Pawn_Body_W/coat_roughness") + ]], + float Pawn_Body_W_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/coat_anisotropy") + ]], + float Pawn_Body_W_coat_rotation = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/coat_rotation") + ]], + uniform float Pawn_Body_W_coat_IOR = 1.500000 + [[ + materialx::core::origin("Pawn_Body_W/coat_IOR") + ]], + float Pawn_Body_W_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/coat_affect_color") + ]], + float Pawn_Body_W_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/coat_affect_roughness") + ]], + float Pawn_Body_W_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/thin_film_thickness") + ]], + float Pawn_Body_W_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Pawn_Body_W/thin_film_IOR") + ]], + float Pawn_Body_W_emission = 0.000000 + [[ + materialx::core::origin("Pawn_Body_W/emission") + ]], + color Pawn_Body_W_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Body_W/emission_color") + ]], + color Pawn_Body_W_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Body_W/opacity") + ]], + bool Pawn_Body_W_thin_walled = false + [[ + materialx::core::origin("Pawn_Body_W/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color diffuse8_out = materialx::stdlib_1_8::mx_image_color3(diffuse8_file, diffuse8_layer, diffuse8_default, geomprop_UV0_out1, diffuse8_uaddressmode, diffuse8_vaddressmode, diffuse8_filtertype, diffuse8_framerange, diffuse8_frameoffset, diffuse8_frameendaction, mxp_flip_v:false); + float metallic8_out = materialx::stdlib_1_8::mx_image_float(metallic8_file, metallic8_layer, metallic8_default, geomprop_UV0_out1, metallic8_uaddressmode, metallic8_vaddressmode, metallic8_filtertype, metallic8_framerange, metallic8_frameoffset, metallic8_frameendaction, mxp_flip_v:false); + float roughness8_out = materialx::stdlib_1_8::mx_image_float(roughness8_file, roughness8_layer, roughness8_default, geomprop_UV0_out1, roughness8_uaddressmode, roughness8_vaddressmode, roughness8_filtertype, roughness8_framerange, roughness8_frameoffset, roughness8_frameendaction, mxp_flip_v:false); + float3 normal8_out = materialx::stdlib_1_8::mx_image_vector3(normal8_file, normal8_layer, normal8_default, geomprop_UV0_out1, normal8_uaddressmode, normal8_vaddressmode, normal8_filtertype, normal8_framerange, normal8_frameoffset, normal8_frameendaction, mxp_flip_v:false); + color diffuse8_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(diffuse8_out); + float3 mtlxnormalmap10_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:normal8_out, mxp_scale:mtlxnormalmap10_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Pawn_Body_W_out = NG_standard_surface_surfaceshader_100(Pawn_Body_W_base, diffuse8_out_cm_out, Pawn_Body_W_diffuse_roughness, metallic8_out, Pawn_Body_W_specular, Pawn_Body_W_specular_color, roughness8_out, Pawn_Body_W_specular_IOR, Pawn_Body_W_specular_anisotropy, Pawn_Body_W_specular_rotation, Pawn_Body_W_transmission, Pawn_Body_W_transmission_color, Pawn_Body_W_transmission_depth, Pawn_Body_W_transmission_scatter, Pawn_Body_W_transmission_scatter_anisotropy, Pawn_Body_W_transmission_dispersion, Pawn_Body_W_transmission_extra_roughness, Pawn_Body_W_subsurface, diffuse8_out_cm_out, diffuse8_out_cm_out, Pawn_Body_W_subsurface_scale, Pawn_Body_W_subsurface_anisotropy, Pawn_Body_W_sheen, Pawn_Body_W_sheen_color, Pawn_Body_W_sheen_roughness, Pawn_Body_W_coat, Pawn_Body_W_coat_color, Pawn_Body_W_coat_roughness, Pawn_Body_W_coat_anisotropy, Pawn_Body_W_coat_rotation, Pawn_Body_W_coat_IOR, geomprop_Nworld_out1, Pawn_Body_W_coat_affect_color, Pawn_Body_W_coat_affect_roughness, Pawn_Body_W_thin_film_thickness, Pawn_Body_W_thin_film_IOR, Pawn_Body_W_emission, Pawn_Body_W_emission_color, Pawn_Body_W_opacity, Pawn_Body_W_thin_walled, mtlxnormalmap10_out, geomprop_Tworld_out1); + material M_Pawn_Body_W_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Pawn_Body_W_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Pawn_Body_W_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Pawn_Body_W.msl.frag b/Materials/Examples/StandardSurface/M_Pawn_Body_W.msl.frag new file mode 100644 index 0000000000..c2b1e660ec --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Body_W.msl.frag @@ -0,0 +1,2961 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int diffuse8_layer; + vec3 diffuse8_default; + int diffuse8_uaddressmode; + int diffuse8_vaddressmode; + int diffuse8_filtertype; + int diffuse8_framerange; + int diffuse8_frameoffset; + int diffuse8_frameendaction; + vec2 diffuse8_uv_scale; + vec2 diffuse8_uv_offset; + int metallic8_layer; + float metallic8_default; + int metallic8_uaddressmode; + int metallic8_vaddressmode; + int metallic8_filtertype; + int metallic8_framerange; + int metallic8_frameoffset; + int metallic8_frameendaction; + vec2 metallic8_uv_scale; + vec2 metallic8_uv_offset; + int roughness8_layer; + float roughness8_default; + int roughness8_uaddressmode; + int roughness8_vaddressmode; + int roughness8_filtertype; + int roughness8_framerange; + int roughness8_frameoffset; + int roughness8_frameendaction; + vec2 roughness8_uv_scale; + vec2 roughness8_uv_offset; + int normal8_layer; + vec3 normal8_default; + int normal8_uaddressmode; + int normal8_vaddressmode; + int normal8_filtertype; + int normal8_framerange; + int normal8_frameoffset; + int normal8_frameendaction; + vec2 normal8_uv_scale; + vec2 normal8_uv_offset; + float mtlxnormalmap10_scale; + float Pawn_Body_W_base; + float Pawn_Body_W_diffuse_roughness; + float Pawn_Body_W_specular; + vec3 Pawn_Body_W_specular_color; + float Pawn_Body_W_specular_IOR; + float Pawn_Body_W_specular_anisotropy; + float Pawn_Body_W_specular_rotation; + float Pawn_Body_W_transmission; + vec3 Pawn_Body_W_transmission_color; + float Pawn_Body_W_transmission_depth; + vec3 Pawn_Body_W_transmission_scatter; + float Pawn_Body_W_transmission_scatter_anisotropy; + float Pawn_Body_W_transmission_dispersion; + float Pawn_Body_W_transmission_extra_roughness; + float Pawn_Body_W_subsurface; + float Pawn_Body_W_subsurface_scale; + float Pawn_Body_W_subsurface_anisotropy; + float Pawn_Body_W_sheen; + vec3 Pawn_Body_W_sheen_color; + float Pawn_Body_W_sheen_roughness; + float Pawn_Body_W_coat; + vec3 Pawn_Body_W_coat_color; + float Pawn_Body_W_coat_roughness; + float Pawn_Body_W_coat_anisotropy; + float Pawn_Body_W_coat_rotation; + float Pawn_Body_W_coat_IOR; + float Pawn_Body_W_coat_affect_color; + float Pawn_Body_W_coat_affect_roughness; + float Pawn_Body_W_thin_film_thickness; + float Pawn_Body_W_thin_film_IOR; + float Pawn_Body_W_emission; + vec3 Pawn_Body_W_emission_color; + vec3 Pawn_Body_W_opacity; + bool Pawn_Body_W_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture diffuse8_file , int diffuse8_layer + + , vec3 diffuse8_default + + , int diffuse8_uaddressmode + + , int diffuse8_vaddressmode + + , int diffuse8_filtertype + + , int diffuse8_framerange + + , int diffuse8_frameoffset + + , int diffuse8_frameendaction + + , vec2 diffuse8_uv_scale + + , vec2 diffuse8_uv_offset + +, MetalTexture metallic8_file , int metallic8_layer + + , float metallic8_default + + , int metallic8_uaddressmode + + , int metallic8_vaddressmode + + , int metallic8_filtertype + + , int metallic8_framerange + + , int metallic8_frameoffset + + , int metallic8_frameendaction + + , vec2 metallic8_uv_scale + + , vec2 metallic8_uv_offset + +, MetalTexture roughness8_file , int roughness8_layer + + , float roughness8_default + + , int roughness8_uaddressmode + + , int roughness8_vaddressmode + + , int roughness8_filtertype + + , int roughness8_framerange + + , int roughness8_frameoffset + + , int roughness8_frameendaction + + , vec2 roughness8_uv_scale + + , vec2 roughness8_uv_offset + +, MetalTexture normal8_file , int normal8_layer + + , vec3 normal8_default + + , int normal8_uaddressmode + + , int normal8_vaddressmode + + , int normal8_filtertype + + , int normal8_framerange + + , int normal8_frameoffset + + , int normal8_frameendaction + + , vec2 normal8_uv_scale + + , vec2 normal8_uv_offset + + , float mtlxnormalmap10_scale + + , float Pawn_Body_W_base + + , float Pawn_Body_W_diffuse_roughness + + , float Pawn_Body_W_specular + + , vec3 Pawn_Body_W_specular_color + + , float Pawn_Body_W_specular_IOR + + , float Pawn_Body_W_specular_anisotropy + + , float Pawn_Body_W_specular_rotation + + , float Pawn_Body_W_transmission + + , vec3 Pawn_Body_W_transmission_color + + , float Pawn_Body_W_transmission_depth + + , vec3 Pawn_Body_W_transmission_scatter + + , float Pawn_Body_W_transmission_scatter_anisotropy + + , float Pawn_Body_W_transmission_dispersion + + , float Pawn_Body_W_transmission_extra_roughness + + , float Pawn_Body_W_subsurface + + , float Pawn_Body_W_subsurface_scale + + , float Pawn_Body_W_subsurface_anisotropy + + , float Pawn_Body_W_sheen + + , vec3 Pawn_Body_W_sheen_color + + , float Pawn_Body_W_sheen_roughness + + , float Pawn_Body_W_coat + + , vec3 Pawn_Body_W_coat_color + + , float Pawn_Body_W_coat_roughness + + , float Pawn_Body_W_coat_anisotropy + + , float Pawn_Body_W_coat_rotation + + , float Pawn_Body_W_coat_IOR + + , float Pawn_Body_W_coat_affect_color + + , float Pawn_Body_W_coat_affect_roughness + + , float Pawn_Body_W_thin_film_thickness + + , float Pawn_Body_W_thin_film_IOR + + , float Pawn_Body_W_emission + + , vec3 Pawn_Body_W_emission_color + + , vec3 Pawn_Body_W_opacity + + , bool Pawn_Body_W_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, diffuse8_file(diffuse8_file) + , diffuse8_layer(diffuse8_layer) + + , diffuse8_default(diffuse8_default) + + , diffuse8_uaddressmode(diffuse8_uaddressmode) + + , diffuse8_vaddressmode(diffuse8_vaddressmode) + + , diffuse8_filtertype(diffuse8_filtertype) + + , diffuse8_framerange(diffuse8_framerange) + + , diffuse8_frameoffset(diffuse8_frameoffset) + + , diffuse8_frameendaction(diffuse8_frameendaction) + + , diffuse8_uv_scale(diffuse8_uv_scale) + + , diffuse8_uv_offset(diffuse8_uv_offset) + +, metallic8_file(metallic8_file) + , metallic8_layer(metallic8_layer) + + , metallic8_default(metallic8_default) + + , metallic8_uaddressmode(metallic8_uaddressmode) + + , metallic8_vaddressmode(metallic8_vaddressmode) + + , metallic8_filtertype(metallic8_filtertype) + + , metallic8_framerange(metallic8_framerange) + + , metallic8_frameoffset(metallic8_frameoffset) + + , metallic8_frameendaction(metallic8_frameendaction) + + , metallic8_uv_scale(metallic8_uv_scale) + + , metallic8_uv_offset(metallic8_uv_offset) + +, roughness8_file(roughness8_file) + , roughness8_layer(roughness8_layer) + + , roughness8_default(roughness8_default) + + , roughness8_uaddressmode(roughness8_uaddressmode) + + , roughness8_vaddressmode(roughness8_vaddressmode) + + , roughness8_filtertype(roughness8_filtertype) + + , roughness8_framerange(roughness8_framerange) + + , roughness8_frameoffset(roughness8_frameoffset) + + , roughness8_frameendaction(roughness8_frameendaction) + + , roughness8_uv_scale(roughness8_uv_scale) + + , roughness8_uv_offset(roughness8_uv_offset) + +, normal8_file(normal8_file) + , normal8_layer(normal8_layer) + + , normal8_default(normal8_default) + + , normal8_uaddressmode(normal8_uaddressmode) + + , normal8_vaddressmode(normal8_vaddressmode) + + , normal8_filtertype(normal8_filtertype) + + , normal8_framerange(normal8_framerange) + + , normal8_frameoffset(normal8_frameoffset) + + , normal8_frameendaction(normal8_frameendaction) + + , normal8_uv_scale(normal8_uv_scale) + + , normal8_uv_offset(normal8_uv_offset) + + , mtlxnormalmap10_scale(mtlxnormalmap10_scale) + + , Pawn_Body_W_base(Pawn_Body_W_base) + + , Pawn_Body_W_diffuse_roughness(Pawn_Body_W_diffuse_roughness) + + , Pawn_Body_W_specular(Pawn_Body_W_specular) + + , Pawn_Body_W_specular_color(Pawn_Body_W_specular_color) + + , Pawn_Body_W_specular_IOR(Pawn_Body_W_specular_IOR) + + , Pawn_Body_W_specular_anisotropy(Pawn_Body_W_specular_anisotropy) + + , Pawn_Body_W_specular_rotation(Pawn_Body_W_specular_rotation) + + , Pawn_Body_W_transmission(Pawn_Body_W_transmission) + + , Pawn_Body_W_transmission_color(Pawn_Body_W_transmission_color) + + , Pawn_Body_W_transmission_depth(Pawn_Body_W_transmission_depth) + + , Pawn_Body_W_transmission_scatter(Pawn_Body_W_transmission_scatter) + + , Pawn_Body_W_transmission_scatter_anisotropy(Pawn_Body_W_transmission_scatter_anisotropy) + + , Pawn_Body_W_transmission_dispersion(Pawn_Body_W_transmission_dispersion) + + , Pawn_Body_W_transmission_extra_roughness(Pawn_Body_W_transmission_extra_roughness) + + , Pawn_Body_W_subsurface(Pawn_Body_W_subsurface) + + , Pawn_Body_W_subsurface_scale(Pawn_Body_W_subsurface_scale) + + , Pawn_Body_W_subsurface_anisotropy(Pawn_Body_W_subsurface_anisotropy) + + , Pawn_Body_W_sheen(Pawn_Body_W_sheen) + + , Pawn_Body_W_sheen_color(Pawn_Body_W_sheen_color) + + , Pawn_Body_W_sheen_roughness(Pawn_Body_W_sheen_roughness) + + , Pawn_Body_W_coat(Pawn_Body_W_coat) + + , Pawn_Body_W_coat_color(Pawn_Body_W_coat_color) + + , Pawn_Body_W_coat_roughness(Pawn_Body_W_coat_roughness) + + , Pawn_Body_W_coat_anisotropy(Pawn_Body_W_coat_anisotropy) + + , Pawn_Body_W_coat_rotation(Pawn_Body_W_coat_rotation) + + , Pawn_Body_W_coat_IOR(Pawn_Body_W_coat_IOR) + + , Pawn_Body_W_coat_affect_color(Pawn_Body_W_coat_affect_color) + + , Pawn_Body_W_coat_affect_roughness(Pawn_Body_W_coat_affect_roughness) + + , Pawn_Body_W_thin_film_thickness(Pawn_Body_W_thin_film_thickness) + + , Pawn_Body_W_thin_film_IOR(Pawn_Body_W_thin_film_IOR) + + , Pawn_Body_W_emission(Pawn_Body_W_emission) + + , Pawn_Body_W_emission_color(Pawn_Body_W_emission_color) + + , Pawn_Body_W_opacity(Pawn_Body_W_opacity) + + , Pawn_Body_W_thin_walled(Pawn_Body_W_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture diffuse8_file; + int diffuse8_layer; + + + vec3 diffuse8_default; + + + int diffuse8_uaddressmode; + + + int diffuse8_vaddressmode; + + + int diffuse8_filtertype; + + + int diffuse8_framerange; + + + int diffuse8_frameoffset; + + + int diffuse8_frameendaction; + + + vec2 diffuse8_uv_scale; + + + vec2 diffuse8_uv_offset; + + +MetalTexture metallic8_file; + int metallic8_layer; + + + float metallic8_default; + + + int metallic8_uaddressmode; + + + int metallic8_vaddressmode; + + + int metallic8_filtertype; + + + int metallic8_framerange; + + + int metallic8_frameoffset; + + + int metallic8_frameendaction; + + + vec2 metallic8_uv_scale; + + + vec2 metallic8_uv_offset; + + +MetalTexture roughness8_file; + int roughness8_layer; + + + float roughness8_default; + + + int roughness8_uaddressmode; + + + int roughness8_vaddressmode; + + + int roughness8_filtertype; + + + int roughness8_framerange; + + + int roughness8_frameoffset; + + + int roughness8_frameendaction; + + + vec2 roughness8_uv_scale; + + + vec2 roughness8_uv_offset; + + +MetalTexture normal8_file; + int normal8_layer; + + + vec3 normal8_default; + + + int normal8_uaddressmode; + + + int normal8_vaddressmode; + + + int normal8_filtertype; + + + int normal8_framerange; + + + int normal8_frameoffset; + + + int normal8_frameendaction; + + + vec2 normal8_uv_scale; + + + vec2 normal8_uv_offset; + + + float mtlxnormalmap10_scale; + + + float Pawn_Body_W_base; + + + float Pawn_Body_W_diffuse_roughness; + + + float Pawn_Body_W_specular; + + + vec3 Pawn_Body_W_specular_color; + + + float Pawn_Body_W_specular_IOR; + + + float Pawn_Body_W_specular_anisotropy; + + + float Pawn_Body_W_specular_rotation; + + + float Pawn_Body_W_transmission; + + + vec3 Pawn_Body_W_transmission_color; + + + float Pawn_Body_W_transmission_depth; + + + vec3 Pawn_Body_W_transmission_scatter; + + + float Pawn_Body_W_transmission_scatter_anisotropy; + + + float Pawn_Body_W_transmission_dispersion; + + + float Pawn_Body_W_transmission_extra_roughness; + + + float Pawn_Body_W_subsurface; + + + float Pawn_Body_W_subsurface_scale; + + + float Pawn_Body_W_subsurface_anisotropy; + + + float Pawn_Body_W_sheen; + + + vec3 Pawn_Body_W_sheen_color; + + + float Pawn_Body_W_sheen_roughness; + + + float Pawn_Body_W_coat; + + + vec3 Pawn_Body_W_coat_color; + + + float Pawn_Body_W_coat_roughness; + + + float Pawn_Body_W_coat_anisotropy; + + + float Pawn_Body_W_coat_rotation; + + + float Pawn_Body_W_coat_IOR; + + + float Pawn_Body_W_coat_affect_color; + + + float Pawn_Body_W_coat_affect_roughness; + + + float Pawn_Body_W_thin_film_thickness; + + + float Pawn_Body_W_thin_film_IOR; + + + float Pawn_Body_W_emission; + + + vec3 Pawn_Body_W_emission_color; + + + vec3 Pawn_Body_W_opacity; + + + bool Pawn_Body_W_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse8_out = vec3(0.0); + mx_image_color3(diffuse8_file, diffuse8_layer, diffuse8_default, geomprop_UV0_out1, diffuse8_uaddressmode, diffuse8_vaddressmode, diffuse8_filtertype, diffuse8_framerange, diffuse8_frameoffset, diffuse8_frameendaction, diffuse8_uv_scale, diffuse8_uv_offset, diffuse8_out); + float metallic8_out = 0.0; + mx_image_float(metallic8_file, metallic8_layer, metallic8_default, geomprop_UV0_out1, metallic8_uaddressmode, metallic8_vaddressmode, metallic8_filtertype, metallic8_framerange, metallic8_frameoffset, metallic8_frameendaction, metallic8_uv_scale, metallic8_uv_offset, metallic8_out); + float roughness8_out = 0.0; + mx_image_float(roughness8_file, roughness8_layer, roughness8_default, geomprop_UV0_out1, roughness8_uaddressmode, roughness8_vaddressmode, roughness8_filtertype, roughness8_framerange, roughness8_frameoffset, roughness8_frameendaction, roughness8_uv_scale, roughness8_uv_offset, roughness8_out); + vec3 normal8_out = vec3(0.0); + mx_image_vector3(normal8_file, normal8_layer, normal8_default, geomprop_UV0_out1, normal8_uaddressmode, normal8_vaddressmode, normal8_filtertype, normal8_framerange, normal8_frameoffset, normal8_frameendaction, normal8_uv_scale, normal8_uv_offset, normal8_out); + vec3 diffuse8_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse8_out, diffuse8_out_cm_out); + vec3 mtlxnormalmap10_out = vec3(0.0); + mx_normalmap_float(normal8_out, mtlxnormalmap10_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap10_out); + surfaceshader Pawn_Body_W_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Pawn_Body_W_base, diffuse8_out_cm_out, Pawn_Body_W_diffuse_roughness, metallic8_out, Pawn_Body_W_specular, Pawn_Body_W_specular_color, roughness8_out, Pawn_Body_W_specular_IOR, Pawn_Body_W_specular_anisotropy, Pawn_Body_W_specular_rotation, Pawn_Body_W_transmission, Pawn_Body_W_transmission_color, Pawn_Body_W_transmission_depth, Pawn_Body_W_transmission_scatter, Pawn_Body_W_transmission_scatter_anisotropy, Pawn_Body_W_transmission_dispersion, Pawn_Body_W_transmission_extra_roughness, Pawn_Body_W_subsurface, diffuse8_out_cm_out, diffuse8_out_cm_out, Pawn_Body_W_subsurface_scale, Pawn_Body_W_subsurface_anisotropy, Pawn_Body_W_sheen, Pawn_Body_W_sheen_color, Pawn_Body_W_sheen_roughness, Pawn_Body_W_coat, Pawn_Body_W_coat_color, Pawn_Body_W_coat_roughness, Pawn_Body_W_coat_anisotropy, Pawn_Body_W_coat_rotation, Pawn_Body_W_coat_IOR, geomprop_Nworld_out1, Pawn_Body_W_coat_affect_color, Pawn_Body_W_coat_affect_roughness, Pawn_Body_W_thin_film_thickness, Pawn_Body_W_thin_film_IOR, Pawn_Body_W_emission, Pawn_Body_W_emission_color, Pawn_Body_W_opacity, Pawn_Body_W_thin_walled, mtlxnormalmap10_out, geomprop_Tworld_out1, Pawn_Body_W_out); + material M_Pawn_Body_W_out = Pawn_Body_W_out; + out1 = float4(M_Pawn_Body_W_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d diffuse8_file_tex [[texture(0)]], sampler diffuse8_file_sampler [[sampler(0)]] +, texture2d metallic8_file_tex [[texture(1)]], sampler metallic8_file_sampler [[sampler(1)]] +, texture2d roughness8_file_tex [[texture(2)]], sampler roughness8_file_sampler [[sampler(2)]] +, texture2d normal8_file_tex [[texture(3)]], sampler normal8_file_sampler [[sampler(3)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(4)]], sampler u_envRadiance_sampler [[sampler(4)]] +, texture2d u_envIrradiance_tex [[texture(5)]], sampler u_envIrradiance_sampler [[sampler(5)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +diffuse8_file_tex, diffuse8_file_sampler } + , u_pub.diffuse8_layer + , u_pub.diffuse8_default + , u_pub.diffuse8_uaddressmode + , u_pub.diffuse8_vaddressmode + , u_pub.diffuse8_filtertype + , u_pub.diffuse8_framerange + , u_pub.diffuse8_frameoffset + , u_pub.diffuse8_frameendaction + , u_pub.diffuse8_uv_scale + , u_pub.diffuse8_uv_offset +, MetalTexture { +metallic8_file_tex, metallic8_file_sampler } + , u_pub.metallic8_layer + , u_pub.metallic8_default + , u_pub.metallic8_uaddressmode + , u_pub.metallic8_vaddressmode + , u_pub.metallic8_filtertype + , u_pub.metallic8_framerange + , u_pub.metallic8_frameoffset + , u_pub.metallic8_frameendaction + , u_pub.metallic8_uv_scale + , u_pub.metallic8_uv_offset +, MetalTexture { +roughness8_file_tex, roughness8_file_sampler } + , u_pub.roughness8_layer + , u_pub.roughness8_default + , u_pub.roughness8_uaddressmode + , u_pub.roughness8_vaddressmode + , u_pub.roughness8_filtertype + , u_pub.roughness8_framerange + , u_pub.roughness8_frameoffset + , u_pub.roughness8_frameendaction + , u_pub.roughness8_uv_scale + , u_pub.roughness8_uv_offset +, MetalTexture { +normal8_file_tex, normal8_file_sampler } + , u_pub.normal8_layer + , u_pub.normal8_default + , u_pub.normal8_uaddressmode + , u_pub.normal8_vaddressmode + , u_pub.normal8_filtertype + , u_pub.normal8_framerange + , u_pub.normal8_frameoffset + , u_pub.normal8_frameendaction + , u_pub.normal8_uv_scale + , u_pub.normal8_uv_offset + , u_pub.mtlxnormalmap10_scale + , u_pub.Pawn_Body_W_base + , u_pub.Pawn_Body_W_diffuse_roughness + , u_pub.Pawn_Body_W_specular + , u_pub.Pawn_Body_W_specular_color + , u_pub.Pawn_Body_W_specular_IOR + , u_pub.Pawn_Body_W_specular_anisotropy + , u_pub.Pawn_Body_W_specular_rotation + , u_pub.Pawn_Body_W_transmission + , u_pub.Pawn_Body_W_transmission_color + , u_pub.Pawn_Body_W_transmission_depth + , u_pub.Pawn_Body_W_transmission_scatter + , u_pub.Pawn_Body_W_transmission_scatter_anisotropy + , u_pub.Pawn_Body_W_transmission_dispersion + , u_pub.Pawn_Body_W_transmission_extra_roughness + , u_pub.Pawn_Body_W_subsurface + , u_pub.Pawn_Body_W_subsurface_scale + , u_pub.Pawn_Body_W_subsurface_anisotropy + , u_pub.Pawn_Body_W_sheen + , u_pub.Pawn_Body_W_sheen_color + , u_pub.Pawn_Body_W_sheen_roughness + , u_pub.Pawn_Body_W_coat + , u_pub.Pawn_Body_W_coat_color + , u_pub.Pawn_Body_W_coat_roughness + , u_pub.Pawn_Body_W_coat_anisotropy + , u_pub.Pawn_Body_W_coat_rotation + , u_pub.Pawn_Body_W_coat_IOR + , u_pub.Pawn_Body_W_coat_affect_color + , u_pub.Pawn_Body_W_coat_affect_roughness + , u_pub.Pawn_Body_W_thin_film_thickness + , u_pub.Pawn_Body_W_thin_film_IOR + , u_pub.Pawn_Body_W_emission + , u_pub.Pawn_Body_W_emission_color + , u_pub.Pawn_Body_W_opacity + , u_pub.Pawn_Body_W_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Body_W.msl.vert b/Materials/Examples/StandardSurface/M_Pawn_Body_W.msl.vert new file mode 100644 index 0000000000..e3f088a0da --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Body_W.msl.vert @@ -0,0 +1,127 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'diffuse8'. Function already called in this scope. + // Omitted node 'metallic8'. Function already called in this scope. + // Omitted node 'roughness8'. Function already called in this scope. + // Omitted node 'normal8'. Function already called in this scope. + // Omitted node 'diffuse8_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap10'. Function already called in this scope. + // Omitted node 'Pawn_Body_W'. Function already called in this scope. + // Omitted node 'M_Pawn_Body_W'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Body_W.osl b/Materials/Examples/StandardSurface/M_Pawn_Body_W.osl new file mode 100644 index 0000000000..efbbd4505a --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Body_W.osl @@ -0,0 +1,678 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Pawn_Body_W +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Pawn_Body_W" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string diffuse8_file = "chess_set/pawn_white_base_color.jpg" + [[ + string widget = "filename" + ]], + string diffuse8_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string diffuse8_layer = "", + color diffuse8_default = color(0.000000, 0.000000, 0.000000), + string diffuse8_uaddressmode = "periodic", + string diffuse8_vaddressmode = "periodic", + string diffuse8_filtertype = "linear", + string diffuse8_framerange = "", + int diffuse8_frameoffset = 0 + [[ + string widget = "number" + ]], + string diffuse8_frameendaction = "constant", + string metallic8_file = "chess_set/pawn_shared_metallic.jpg" + [[ + string widget = "filename" + ]], + string metallic8_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string metallic8_layer = "", + float metallic8_default = 0.000000 + [[ + string widget = "number" + ]], + string metallic8_uaddressmode = "periodic", + string metallic8_vaddressmode = "periodic", + string metallic8_filtertype = "linear", + string metallic8_framerange = "", + int metallic8_frameoffset = 0 + [[ + string widget = "number" + ]], + string metallic8_frameendaction = "constant", + string roughness8_file = "chess_set/pawn_shared_roughness.jpg" + [[ + string widget = "filename" + ]], + string roughness8_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string roughness8_layer = "", + float roughness8_default = 0.000000 + [[ + string widget = "number" + ]], + string roughness8_uaddressmode = "periodic", + string roughness8_vaddressmode = "periodic", + string roughness8_filtertype = "linear", + string roughness8_framerange = "", + int roughness8_frameoffset = 0 + [[ + string widget = "number" + ]], + string roughness8_frameendaction = "constant", + string normal8_file = "chess_set/pawn_shared_normal.jpg" + [[ + string widget = "filename" + ]], + string normal8_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string normal8_layer = "", + vector normal8_default = vector(0.000000, 0.000000, 0.000000), + string normal8_uaddressmode = "periodic", + string normal8_vaddressmode = "periodic", + string normal8_filtertype = "linear", + string normal8_framerange = "", + int normal8_frameoffset = 0 + [[ + string widget = "number" + ]], + string normal8_frameendaction = "constant", + float mtlxnormalmap10_scale = 1.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_base = 1.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_specular = 1.000000 + [[ + string widget = "number" + ]], + color Pawn_Body_W_specular_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Body_W_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_transmission = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Body_W_transmission_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Body_W_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Body_W_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Pawn_Body_W_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_subsurface = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Body_W_sheen_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Body_W_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_coat = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Body_W_coat_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Body_W_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Pawn_Body_W_emission = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Body_W_emission_color = color(1.000000, 1.000000, 1.000000), + color Pawn_Body_W_opacity = color(1.000000, 1.000000, 1.000000), + int Pawn_Body_W_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource diffuse8_file_ = {diffuse8_file, diffuse8_file_colorspace}; + textureresource metallic8_file_ = {metallic8_file, metallic8_file_colorspace}; + textureresource roughness8_file_ = {roughness8_file, roughness8_file_colorspace}; + textureresource normal8_file_ = {normal8_file, normal8_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color diffuse8_out = color(0.0); + mx_image_color3(diffuse8_file_, diffuse8_layer, diffuse8_default, geomprop_UV0_out1, diffuse8_uaddressmode, diffuse8_vaddressmode, diffuse8_filtertype, diffuse8_framerange, diffuse8_frameoffset, diffuse8_frameendaction, diffuse8_out); + float metallic8_out = 0.0; + mx_image_float(metallic8_file_, metallic8_layer, metallic8_default, geomprop_UV0_out1, metallic8_uaddressmode, metallic8_vaddressmode, metallic8_filtertype, metallic8_framerange, metallic8_frameoffset, metallic8_frameendaction, metallic8_out); + float roughness8_out = 0.0; + mx_image_float(roughness8_file_, roughness8_layer, roughness8_default, geomprop_UV0_out1, roughness8_uaddressmode, roughness8_vaddressmode, roughness8_filtertype, roughness8_framerange, roughness8_frameoffset, roughness8_frameendaction, roughness8_out); + vector normal8_out = vector(0.0); + mx_image_vector3(normal8_file_, normal8_layer, normal8_default, geomprop_UV0_out1, normal8_uaddressmode, normal8_vaddressmode, normal8_filtertype, normal8_framerange, normal8_frameoffset, normal8_frameendaction, normal8_out); + color diffuse8_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse8_out, diffuse8_out_cm_out); + vector mtlxnormalmap10_out = vector(0.0); + mx_normalmap_float(normal8_out, mtlxnormalmap10_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap10_out); + surfaceshader Pawn_Body_W_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Pawn_Body_W_base, diffuse8_out_cm_out, Pawn_Body_W_diffuse_roughness, metallic8_out, Pawn_Body_W_specular, Pawn_Body_W_specular_color, roughness8_out, Pawn_Body_W_specular_IOR, Pawn_Body_W_specular_anisotropy, Pawn_Body_W_specular_rotation, Pawn_Body_W_transmission, Pawn_Body_W_transmission_color, Pawn_Body_W_transmission_depth, Pawn_Body_W_transmission_scatter, Pawn_Body_W_transmission_scatter_anisotropy, Pawn_Body_W_transmission_dispersion, Pawn_Body_W_transmission_extra_roughness, Pawn_Body_W_subsurface, diffuse8_out_cm_out, diffuse8_out_cm_out, Pawn_Body_W_subsurface_scale, Pawn_Body_W_subsurface_anisotropy, Pawn_Body_W_sheen, Pawn_Body_W_sheen_color, Pawn_Body_W_sheen_roughness, Pawn_Body_W_coat, Pawn_Body_W_coat_color, Pawn_Body_W_coat_roughness, Pawn_Body_W_coat_anisotropy, Pawn_Body_W_coat_rotation, Pawn_Body_W_coat_IOR, geomprop_Nworld_out1, Pawn_Body_W_coat_affect_color, Pawn_Body_W_coat_affect_roughness, Pawn_Body_W_thin_film_thickness, Pawn_Body_W_thin_film_IOR, Pawn_Body_W_emission, Pawn_Body_W_emission_color, Pawn_Body_W_opacity, Pawn_Body_W_thin_walled, mtlxnormalmap10_out, geomprop_Tworld_out1, Pawn_Body_W_out); + MATERIAL M_Pawn_Body_W_out = mx_surfacematerial(Pawn_Body_W_out, backsurfaceshader, displacementshader1); + out = M_Pawn_Body_W_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Top_B.glsl.frag b/Materials/Examples/StandardSurface/M_Pawn_Top_B.glsl.frag new file mode 100644 index 0000000000..f44646e539 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Top_B.glsl.frag @@ -0,0 +1,1936 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D mtlximage19_file; +uniform int mtlximage19_layer = 0; +uniform float mtlximage19_default = 0.000000; +uniform int mtlximage19_uaddressmode = 2; +uniform int mtlximage19_vaddressmode = 2; +uniform int mtlximage19_filtertype = 1; +uniform int mtlximage19_framerange = 0; +uniform int mtlximage19_frameoffset = 0; +uniform int mtlximage19_frameendaction = 0; +uniform vec2 mtlximage19_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage19_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage18_file; +uniform int mtlximage18_layer = 0; +uniform vec3 mtlximage18_default = vec3(0.000000, 0.000000, 0.000000); +uniform int mtlximage18_uaddressmode = 2; +uniform int mtlximage18_vaddressmode = 2; +uniform int mtlximage18_filtertype = 1; +uniform int mtlximage18_framerange = 0; +uniform int mtlximage18_frameoffset = 0; +uniform int mtlximage18_frameendaction = 0; +uniform vec2 mtlximage18_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage18_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap14_scale = 1.000000; +uniform float Pawn_Top_B_base = 1.000000; +uniform vec3 Pawn_Top_B_base_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Top_B_diffuse_roughness = 0.000000; +uniform float Pawn_Top_B_metalness = 0.000000; +uniform float Pawn_Top_B_specular = 1.000000; +uniform vec3 Pawn_Top_B_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Top_B_specular_IOR = 1.500000; +uniform float Pawn_Top_B_specular_anisotropy = 0.000000; +uniform float Pawn_Top_B_specular_rotation = 0.000000; +uniform float Pawn_Top_B_transmission = 1.000000; +uniform vec3 Pawn_Top_B_transmission_color = vec3(0.299500, 0.500000, 0.450276); +uniform float Pawn_Top_B_transmission_depth = 0.000000; +uniform vec3 Pawn_Top_B_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Pawn_Top_B_transmission_scatter_anisotropy = 0.000000; +uniform float Pawn_Top_B_transmission_dispersion = 0.000000; +uniform float Pawn_Top_B_transmission_extra_roughness = 0.000000; +uniform float Pawn_Top_B_subsurface = 0.000000; +uniform vec3 Pawn_Top_B_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Pawn_Top_B_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Top_B_subsurface_scale = 0.003000; +uniform float Pawn_Top_B_subsurface_anisotropy = 0.000000; +uniform float Pawn_Top_B_sheen = 0.000000; +uniform vec3 Pawn_Top_B_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Top_B_sheen_roughness = 0.300000; +uniform float Pawn_Top_B_coat = 0.000000; +uniform vec3 Pawn_Top_B_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Top_B_coat_roughness = 0.100000; +uniform float Pawn_Top_B_coat_anisotropy = 0.000000; +uniform float Pawn_Top_B_coat_rotation = 0.000000; +uniform float Pawn_Top_B_coat_IOR = 1.500000; +uniform float Pawn_Top_B_coat_affect_color = 0.000000; +uniform float Pawn_Top_B_coat_affect_roughness = 0.000000; +uniform float Pawn_Top_B_thin_film_thickness = 0.000000; +uniform float Pawn_Top_B_thin_film_IOR = 1.500000; +uniform float Pawn_Top_B_emission = 0.000000; +uniform vec3 Pawn_Top_B_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Pawn_Top_B_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Pawn_Top_B_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + float mtlximage19_out = 0.0; + mx_image_float(mtlximage19_file, mtlximage19_layer, mtlximage19_default, geomprop_UV0_out1, mtlximage19_uaddressmode, mtlximage19_vaddressmode, mtlximage19_filtertype, mtlximage19_framerange, mtlximage19_frameoffset, mtlximage19_frameendaction, mtlximage19_uv_scale, mtlximage19_uv_offset, mtlximage19_out); + vec3 mtlximage18_out = vec3(0.0); + mx_image_vector3(mtlximage18_file, mtlximage18_layer, mtlximage18_default, geomprop_UV0_out1, mtlximage18_uaddressmode, mtlximage18_vaddressmode, mtlximage18_filtertype, mtlximage18_framerange, mtlximage18_frameoffset, mtlximage18_frameendaction, mtlximage18_uv_scale, mtlximage18_uv_offset, mtlximage18_out); + vec3 mtlxnormalmap14_out = vec3(0.0); + mx_normalmap_float(mtlximage18_out, mtlxnormalmap14_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap14_out); + surfaceshader Pawn_Top_B_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Pawn_Top_B_base, Pawn_Top_B_base_color, Pawn_Top_B_diffuse_roughness, Pawn_Top_B_metalness, Pawn_Top_B_specular, Pawn_Top_B_specular_color, mtlximage19_out, Pawn_Top_B_specular_IOR, Pawn_Top_B_specular_anisotropy, Pawn_Top_B_specular_rotation, Pawn_Top_B_transmission, Pawn_Top_B_transmission_color, Pawn_Top_B_transmission_depth, Pawn_Top_B_transmission_scatter, Pawn_Top_B_transmission_scatter_anisotropy, Pawn_Top_B_transmission_dispersion, Pawn_Top_B_transmission_extra_roughness, Pawn_Top_B_subsurface, Pawn_Top_B_subsurface_color, Pawn_Top_B_subsurface_radius, Pawn_Top_B_subsurface_scale, Pawn_Top_B_subsurface_anisotropy, Pawn_Top_B_sheen, Pawn_Top_B_sheen_color, Pawn_Top_B_sheen_roughness, Pawn_Top_B_coat, Pawn_Top_B_coat_color, Pawn_Top_B_coat_roughness, Pawn_Top_B_coat_anisotropy, Pawn_Top_B_coat_rotation, Pawn_Top_B_coat_IOR, geomprop_Nworld_out1, Pawn_Top_B_coat_affect_color, Pawn_Top_B_coat_affect_roughness, Pawn_Top_B_thin_film_thickness, Pawn_Top_B_thin_film_IOR, Pawn_Top_B_emission, Pawn_Top_B_emission_color, Pawn_Top_B_opacity, Pawn_Top_B_thin_walled, mtlxnormalmap14_out, geomprop_Tworld_out1, Pawn_Top_B_out); + material M_Pawn_Top_B_out = Pawn_Top_B_out; + out1 = vec4(M_Pawn_Top_B_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Top_B.glsl.vert b/Materials/Examples/StandardSurface/M_Pawn_Top_B.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Top_B.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Top_B.mdl b/Materials/Examples/StandardSurface/M_Pawn_Top_B.mdl new file mode 100644 index 0000000000..9c4c0e9807 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Top_B.mdl @@ -0,0 +1,406 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Pawn_Top_B +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d mtlximage19_file = texture_2d("/chess_set/pawn_shared_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage19/file") + ]], + uniform string mtlximage19_layer = "" + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage19/layer") + ]], + float mtlximage19_default = 0.000000 + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage19/default") + ]], + uniform mx_addressmode_type mtlximage19_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage19/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage19_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage19/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage19_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage19/filtertype") + ]], + uniform string mtlximage19_framerange = "" + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage19/framerange") + ]], + uniform int mtlximage19_frameoffset = 0 + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage19/frameoffset") + ]], + uniform mx_addressmode_type mtlximage19_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage19/frameendaction") + ]], + uniform texture_2d mtlximage18_file = texture_2d("/chess_set/pawn_shared_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage18/file") + ]], + uniform string mtlximage18_layer = "" + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage18/layer") + ]], + float3 mtlximage18_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage18/default") + ]], + uniform mx_addressmode_type mtlximage18_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage18/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage18_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage18/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage18_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage18/filtertype") + ]], + uniform string mtlximage18_framerange = "" + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage18/framerange") + ]], + uniform int mtlximage18_frameoffset = 0 + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage18/frameoffset") + ]], + uniform mx_addressmode_type mtlximage18_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_PawnTopBlack/mtlximage18/frameendaction") + ]], + float mtlxnormalmap14_scale = 1.000000 + [[ + materialx::core::origin("NG_PawnTopBlack/mtlxnormalmap14/scale") + ]], + float Pawn_Top_B_base = 1.000000 + [[ + materialx::core::origin("Pawn_Top_B/base") + ]], + color Pawn_Top_B_base_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_B/base_color") + ]], + float Pawn_Top_B_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/diffuse_roughness") + ]], + float Pawn_Top_B_metalness = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/metalness") + ]], + float Pawn_Top_B_specular = 1.000000 + [[ + materialx::core::origin("Pawn_Top_B/specular") + ]], + color Pawn_Top_B_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_B/specular_color") + ]], + uniform float Pawn_Top_B_specular_IOR = 1.500000 + [[ + materialx::core::origin("Pawn_Top_B/specular_IOR") + ]], + float Pawn_Top_B_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/specular_anisotropy") + ]], + float Pawn_Top_B_specular_rotation = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/specular_rotation") + ]], + float Pawn_Top_B_transmission = 1.000000 + [[ + materialx::core::origin("Pawn_Top_B/transmission") + ]], + color Pawn_Top_B_transmission_color = color(0.299500, 0.500000, 0.450276) + [[ + materialx::core::origin("Pawn_Top_B/transmission_color") + ]], + float Pawn_Top_B_transmission_depth = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/transmission_depth") + ]], + color Pawn_Top_B_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Pawn_Top_B/transmission_scatter") + ]], + float Pawn_Top_B_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/transmission_scatter_anisotropy") + ]], + float Pawn_Top_B_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/transmission_dispersion") + ]], + float Pawn_Top_B_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/transmission_extra_roughness") + ]], + float Pawn_Top_B_subsurface = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/subsurface") + ]], + color Pawn_Top_B_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_B/subsurface_color") + ]], + color Pawn_Top_B_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_B/subsurface_radius") + ]], + float Pawn_Top_B_subsurface_scale = 0.003000 + [[ + materialx::core::origin("Pawn_Top_B/subsurface_scale") + ]], + float Pawn_Top_B_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/subsurface_anisotropy") + ]], + float Pawn_Top_B_sheen = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/sheen") + ]], + color Pawn_Top_B_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_B/sheen_color") + ]], + float Pawn_Top_B_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Pawn_Top_B/sheen_roughness") + ]], + float Pawn_Top_B_coat = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/coat") + ]], + color Pawn_Top_B_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_B/coat_color") + ]], + float Pawn_Top_B_coat_roughness = 0.100000 + [[ + materialx::core::origin("Pawn_Top_B/coat_roughness") + ]], + float Pawn_Top_B_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/coat_anisotropy") + ]], + float Pawn_Top_B_coat_rotation = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/coat_rotation") + ]], + uniform float Pawn_Top_B_coat_IOR = 1.500000 + [[ + materialx::core::origin("Pawn_Top_B/coat_IOR") + ]], + float Pawn_Top_B_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/coat_affect_color") + ]], + float Pawn_Top_B_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/coat_affect_roughness") + ]], + float Pawn_Top_B_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/thin_film_thickness") + ]], + float Pawn_Top_B_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Pawn_Top_B/thin_film_IOR") + ]], + float Pawn_Top_B_emission = 0.000000 + [[ + materialx::core::origin("Pawn_Top_B/emission") + ]], + color Pawn_Top_B_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_B/emission_color") + ]], + color Pawn_Top_B_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_B/opacity") + ]], + bool Pawn_Top_B_thin_walled = false + [[ + materialx::core::origin("Pawn_Top_B/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + float mtlximage19_out = materialx::stdlib_1_8::mx_image_float(mtlximage19_file, mtlximage19_layer, mtlximage19_default, geomprop_UV0_out1, mtlximage19_uaddressmode, mtlximage19_vaddressmode, mtlximage19_filtertype, mtlximage19_framerange, mtlximage19_frameoffset, mtlximage19_frameendaction, mxp_flip_v:false); + float3 mtlximage18_out = materialx::stdlib_1_8::mx_image_vector3(mtlximage18_file, mtlximage18_layer, mtlximage18_default, geomprop_UV0_out1, mtlximage18_uaddressmode, mtlximage18_vaddressmode, mtlximage18_filtertype, mtlximage18_framerange, mtlximage18_frameoffset, mtlximage18_frameendaction, mxp_flip_v:false); + float3 mtlxnormalmap14_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:mtlximage18_out, mxp_scale:mtlxnormalmap14_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Pawn_Top_B_out = NG_standard_surface_surfaceshader_100(Pawn_Top_B_base, Pawn_Top_B_base_color, Pawn_Top_B_diffuse_roughness, Pawn_Top_B_metalness, Pawn_Top_B_specular, Pawn_Top_B_specular_color, mtlximage19_out, Pawn_Top_B_specular_IOR, Pawn_Top_B_specular_anisotropy, Pawn_Top_B_specular_rotation, Pawn_Top_B_transmission, Pawn_Top_B_transmission_color, Pawn_Top_B_transmission_depth, Pawn_Top_B_transmission_scatter, Pawn_Top_B_transmission_scatter_anisotropy, Pawn_Top_B_transmission_dispersion, Pawn_Top_B_transmission_extra_roughness, Pawn_Top_B_subsurface, Pawn_Top_B_subsurface_color, Pawn_Top_B_subsurface_radius, Pawn_Top_B_subsurface_scale, Pawn_Top_B_subsurface_anisotropy, Pawn_Top_B_sheen, Pawn_Top_B_sheen_color, Pawn_Top_B_sheen_roughness, Pawn_Top_B_coat, Pawn_Top_B_coat_color, Pawn_Top_B_coat_roughness, Pawn_Top_B_coat_anisotropy, Pawn_Top_B_coat_rotation, Pawn_Top_B_coat_IOR, geomprop_Nworld_out1, Pawn_Top_B_coat_affect_color, Pawn_Top_B_coat_affect_roughness, Pawn_Top_B_thin_film_thickness, Pawn_Top_B_thin_film_IOR, Pawn_Top_B_emission, Pawn_Top_B_emission_color, Pawn_Top_B_opacity, Pawn_Top_B_thin_walled, mtlxnormalmap14_out, geomprop_Tworld_out1); + material M_Pawn_Top_B_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Pawn_Top_B_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Pawn_Top_B_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Pawn_Top_B.msl.frag b/Materials/Examples/StandardSurface/M_Pawn_Top_B.msl.frag new file mode 100644 index 0000000000..ff9841d6f2 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Top_B.msl.frag @@ -0,0 +1,2748 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int mtlximage19_layer; + float mtlximage19_default; + int mtlximage19_uaddressmode; + int mtlximage19_vaddressmode; + int mtlximage19_filtertype; + int mtlximage19_framerange; + int mtlximage19_frameoffset; + int mtlximage19_frameendaction; + vec2 mtlximage19_uv_scale; + vec2 mtlximage19_uv_offset; + int mtlximage18_layer; + vec3 mtlximage18_default; + int mtlximage18_uaddressmode; + int mtlximage18_vaddressmode; + int mtlximage18_filtertype; + int mtlximage18_framerange; + int mtlximage18_frameoffset; + int mtlximage18_frameendaction; + vec2 mtlximage18_uv_scale; + vec2 mtlximage18_uv_offset; + float mtlxnormalmap14_scale; + float Pawn_Top_B_base; + vec3 Pawn_Top_B_base_color; + float Pawn_Top_B_diffuse_roughness; + float Pawn_Top_B_metalness; + float Pawn_Top_B_specular; + vec3 Pawn_Top_B_specular_color; + float Pawn_Top_B_specular_IOR; + float Pawn_Top_B_specular_anisotropy; + float Pawn_Top_B_specular_rotation; + float Pawn_Top_B_transmission; + vec3 Pawn_Top_B_transmission_color; + float Pawn_Top_B_transmission_depth; + vec3 Pawn_Top_B_transmission_scatter; + float Pawn_Top_B_transmission_scatter_anisotropy; + float Pawn_Top_B_transmission_dispersion; + float Pawn_Top_B_transmission_extra_roughness; + float Pawn_Top_B_subsurface; + vec3 Pawn_Top_B_subsurface_color; + vec3 Pawn_Top_B_subsurface_radius; + float Pawn_Top_B_subsurface_scale; + float Pawn_Top_B_subsurface_anisotropy; + float Pawn_Top_B_sheen; + vec3 Pawn_Top_B_sheen_color; + float Pawn_Top_B_sheen_roughness; + float Pawn_Top_B_coat; + vec3 Pawn_Top_B_coat_color; + float Pawn_Top_B_coat_roughness; + float Pawn_Top_B_coat_anisotropy; + float Pawn_Top_B_coat_rotation; + float Pawn_Top_B_coat_IOR; + float Pawn_Top_B_coat_affect_color; + float Pawn_Top_B_coat_affect_roughness; + float Pawn_Top_B_thin_film_thickness; + float Pawn_Top_B_thin_film_IOR; + float Pawn_Top_B_emission; + vec3 Pawn_Top_B_emission_color; + vec3 Pawn_Top_B_opacity; + bool Pawn_Top_B_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture mtlximage19_file , int mtlximage19_layer + + , float mtlximage19_default + + , int mtlximage19_uaddressmode + + , int mtlximage19_vaddressmode + + , int mtlximage19_filtertype + + , int mtlximage19_framerange + + , int mtlximage19_frameoffset + + , int mtlximage19_frameendaction + + , vec2 mtlximage19_uv_scale + + , vec2 mtlximage19_uv_offset + +, MetalTexture mtlximage18_file , int mtlximage18_layer + + , vec3 mtlximage18_default + + , int mtlximage18_uaddressmode + + , int mtlximage18_vaddressmode + + , int mtlximage18_filtertype + + , int mtlximage18_framerange + + , int mtlximage18_frameoffset + + , int mtlximage18_frameendaction + + , vec2 mtlximage18_uv_scale + + , vec2 mtlximage18_uv_offset + + , float mtlxnormalmap14_scale + + , float Pawn_Top_B_base + + , vec3 Pawn_Top_B_base_color + + , float Pawn_Top_B_diffuse_roughness + + , float Pawn_Top_B_metalness + + , float Pawn_Top_B_specular + + , vec3 Pawn_Top_B_specular_color + + , float Pawn_Top_B_specular_IOR + + , float Pawn_Top_B_specular_anisotropy + + , float Pawn_Top_B_specular_rotation + + , float Pawn_Top_B_transmission + + , vec3 Pawn_Top_B_transmission_color + + , float Pawn_Top_B_transmission_depth + + , vec3 Pawn_Top_B_transmission_scatter + + , float Pawn_Top_B_transmission_scatter_anisotropy + + , float Pawn_Top_B_transmission_dispersion + + , float Pawn_Top_B_transmission_extra_roughness + + , float Pawn_Top_B_subsurface + + , vec3 Pawn_Top_B_subsurface_color + + , vec3 Pawn_Top_B_subsurface_radius + + , float Pawn_Top_B_subsurface_scale + + , float Pawn_Top_B_subsurface_anisotropy + + , float Pawn_Top_B_sheen + + , vec3 Pawn_Top_B_sheen_color + + , float Pawn_Top_B_sheen_roughness + + , float Pawn_Top_B_coat + + , vec3 Pawn_Top_B_coat_color + + , float Pawn_Top_B_coat_roughness + + , float Pawn_Top_B_coat_anisotropy + + , float Pawn_Top_B_coat_rotation + + , float Pawn_Top_B_coat_IOR + + , float Pawn_Top_B_coat_affect_color + + , float Pawn_Top_B_coat_affect_roughness + + , float Pawn_Top_B_thin_film_thickness + + , float Pawn_Top_B_thin_film_IOR + + , float Pawn_Top_B_emission + + , vec3 Pawn_Top_B_emission_color + + , vec3 Pawn_Top_B_opacity + + , bool Pawn_Top_B_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, mtlximage19_file(mtlximage19_file) + , mtlximage19_layer(mtlximage19_layer) + + , mtlximage19_default(mtlximage19_default) + + , mtlximage19_uaddressmode(mtlximage19_uaddressmode) + + , mtlximage19_vaddressmode(mtlximage19_vaddressmode) + + , mtlximage19_filtertype(mtlximage19_filtertype) + + , mtlximage19_framerange(mtlximage19_framerange) + + , mtlximage19_frameoffset(mtlximage19_frameoffset) + + , mtlximage19_frameendaction(mtlximage19_frameendaction) + + , mtlximage19_uv_scale(mtlximage19_uv_scale) + + , mtlximage19_uv_offset(mtlximage19_uv_offset) + +, mtlximage18_file(mtlximage18_file) + , mtlximage18_layer(mtlximage18_layer) + + , mtlximage18_default(mtlximage18_default) + + , mtlximage18_uaddressmode(mtlximage18_uaddressmode) + + , mtlximage18_vaddressmode(mtlximage18_vaddressmode) + + , mtlximage18_filtertype(mtlximage18_filtertype) + + , mtlximage18_framerange(mtlximage18_framerange) + + , mtlximage18_frameoffset(mtlximage18_frameoffset) + + , mtlximage18_frameendaction(mtlximage18_frameendaction) + + , mtlximage18_uv_scale(mtlximage18_uv_scale) + + , mtlximage18_uv_offset(mtlximage18_uv_offset) + + , mtlxnormalmap14_scale(mtlxnormalmap14_scale) + + , Pawn_Top_B_base(Pawn_Top_B_base) + + , Pawn_Top_B_base_color(Pawn_Top_B_base_color) + + , Pawn_Top_B_diffuse_roughness(Pawn_Top_B_diffuse_roughness) + + , Pawn_Top_B_metalness(Pawn_Top_B_metalness) + + , Pawn_Top_B_specular(Pawn_Top_B_specular) + + , Pawn_Top_B_specular_color(Pawn_Top_B_specular_color) + + , Pawn_Top_B_specular_IOR(Pawn_Top_B_specular_IOR) + + , Pawn_Top_B_specular_anisotropy(Pawn_Top_B_specular_anisotropy) + + , Pawn_Top_B_specular_rotation(Pawn_Top_B_specular_rotation) + + , Pawn_Top_B_transmission(Pawn_Top_B_transmission) + + , Pawn_Top_B_transmission_color(Pawn_Top_B_transmission_color) + + , Pawn_Top_B_transmission_depth(Pawn_Top_B_transmission_depth) + + , Pawn_Top_B_transmission_scatter(Pawn_Top_B_transmission_scatter) + + , Pawn_Top_B_transmission_scatter_anisotropy(Pawn_Top_B_transmission_scatter_anisotropy) + + , Pawn_Top_B_transmission_dispersion(Pawn_Top_B_transmission_dispersion) + + , Pawn_Top_B_transmission_extra_roughness(Pawn_Top_B_transmission_extra_roughness) + + , Pawn_Top_B_subsurface(Pawn_Top_B_subsurface) + + , Pawn_Top_B_subsurface_color(Pawn_Top_B_subsurface_color) + + , Pawn_Top_B_subsurface_radius(Pawn_Top_B_subsurface_radius) + + , Pawn_Top_B_subsurface_scale(Pawn_Top_B_subsurface_scale) + + , Pawn_Top_B_subsurface_anisotropy(Pawn_Top_B_subsurface_anisotropy) + + , Pawn_Top_B_sheen(Pawn_Top_B_sheen) + + , Pawn_Top_B_sheen_color(Pawn_Top_B_sheen_color) + + , Pawn_Top_B_sheen_roughness(Pawn_Top_B_sheen_roughness) + + , Pawn_Top_B_coat(Pawn_Top_B_coat) + + , Pawn_Top_B_coat_color(Pawn_Top_B_coat_color) + + , Pawn_Top_B_coat_roughness(Pawn_Top_B_coat_roughness) + + , Pawn_Top_B_coat_anisotropy(Pawn_Top_B_coat_anisotropy) + + , Pawn_Top_B_coat_rotation(Pawn_Top_B_coat_rotation) + + , Pawn_Top_B_coat_IOR(Pawn_Top_B_coat_IOR) + + , Pawn_Top_B_coat_affect_color(Pawn_Top_B_coat_affect_color) + + , Pawn_Top_B_coat_affect_roughness(Pawn_Top_B_coat_affect_roughness) + + , Pawn_Top_B_thin_film_thickness(Pawn_Top_B_thin_film_thickness) + + , Pawn_Top_B_thin_film_IOR(Pawn_Top_B_thin_film_IOR) + + , Pawn_Top_B_emission(Pawn_Top_B_emission) + + , Pawn_Top_B_emission_color(Pawn_Top_B_emission_color) + + , Pawn_Top_B_opacity(Pawn_Top_B_opacity) + + , Pawn_Top_B_thin_walled(Pawn_Top_B_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture mtlximage19_file; + int mtlximage19_layer; + + + float mtlximage19_default; + + + int mtlximage19_uaddressmode; + + + int mtlximage19_vaddressmode; + + + int mtlximage19_filtertype; + + + int mtlximage19_framerange; + + + int mtlximage19_frameoffset; + + + int mtlximage19_frameendaction; + + + vec2 mtlximage19_uv_scale; + + + vec2 mtlximage19_uv_offset; + + +MetalTexture mtlximage18_file; + int mtlximage18_layer; + + + vec3 mtlximage18_default; + + + int mtlximage18_uaddressmode; + + + int mtlximage18_vaddressmode; + + + int mtlximage18_filtertype; + + + int mtlximage18_framerange; + + + int mtlximage18_frameoffset; + + + int mtlximage18_frameendaction; + + + vec2 mtlximage18_uv_scale; + + + vec2 mtlximage18_uv_offset; + + + float mtlxnormalmap14_scale; + + + float Pawn_Top_B_base; + + + vec3 Pawn_Top_B_base_color; + + + float Pawn_Top_B_diffuse_roughness; + + + float Pawn_Top_B_metalness; + + + float Pawn_Top_B_specular; + + + vec3 Pawn_Top_B_specular_color; + + + float Pawn_Top_B_specular_IOR; + + + float Pawn_Top_B_specular_anisotropy; + + + float Pawn_Top_B_specular_rotation; + + + float Pawn_Top_B_transmission; + + + vec3 Pawn_Top_B_transmission_color; + + + float Pawn_Top_B_transmission_depth; + + + vec3 Pawn_Top_B_transmission_scatter; + + + float Pawn_Top_B_transmission_scatter_anisotropy; + + + float Pawn_Top_B_transmission_dispersion; + + + float Pawn_Top_B_transmission_extra_roughness; + + + float Pawn_Top_B_subsurface; + + + vec3 Pawn_Top_B_subsurface_color; + + + vec3 Pawn_Top_B_subsurface_radius; + + + float Pawn_Top_B_subsurface_scale; + + + float Pawn_Top_B_subsurface_anisotropy; + + + float Pawn_Top_B_sheen; + + + vec3 Pawn_Top_B_sheen_color; + + + float Pawn_Top_B_sheen_roughness; + + + float Pawn_Top_B_coat; + + + vec3 Pawn_Top_B_coat_color; + + + float Pawn_Top_B_coat_roughness; + + + float Pawn_Top_B_coat_anisotropy; + + + float Pawn_Top_B_coat_rotation; + + + float Pawn_Top_B_coat_IOR; + + + float Pawn_Top_B_coat_affect_color; + + + float Pawn_Top_B_coat_affect_roughness; + + + float Pawn_Top_B_thin_film_thickness; + + + float Pawn_Top_B_thin_film_IOR; + + + float Pawn_Top_B_emission; + + + vec3 Pawn_Top_B_emission_color; + + + vec3 Pawn_Top_B_opacity; + + + bool Pawn_Top_B_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + float mtlximage19_out = 0.0; + mx_image_float(mtlximage19_file, mtlximage19_layer, mtlximage19_default, geomprop_UV0_out1, mtlximage19_uaddressmode, mtlximage19_vaddressmode, mtlximage19_filtertype, mtlximage19_framerange, mtlximage19_frameoffset, mtlximage19_frameendaction, mtlximage19_uv_scale, mtlximage19_uv_offset, mtlximage19_out); + vec3 mtlximage18_out = vec3(0.0); + mx_image_vector3(mtlximage18_file, mtlximage18_layer, mtlximage18_default, geomprop_UV0_out1, mtlximage18_uaddressmode, mtlximage18_vaddressmode, mtlximage18_filtertype, mtlximage18_framerange, mtlximage18_frameoffset, mtlximage18_frameendaction, mtlximage18_uv_scale, mtlximage18_uv_offset, mtlximage18_out); + vec3 mtlxnormalmap14_out = vec3(0.0); + mx_normalmap_float(mtlximage18_out, mtlxnormalmap14_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap14_out); + surfaceshader Pawn_Top_B_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Pawn_Top_B_base, Pawn_Top_B_base_color, Pawn_Top_B_diffuse_roughness, Pawn_Top_B_metalness, Pawn_Top_B_specular, Pawn_Top_B_specular_color, mtlximage19_out, Pawn_Top_B_specular_IOR, Pawn_Top_B_specular_anisotropy, Pawn_Top_B_specular_rotation, Pawn_Top_B_transmission, Pawn_Top_B_transmission_color, Pawn_Top_B_transmission_depth, Pawn_Top_B_transmission_scatter, Pawn_Top_B_transmission_scatter_anisotropy, Pawn_Top_B_transmission_dispersion, Pawn_Top_B_transmission_extra_roughness, Pawn_Top_B_subsurface, Pawn_Top_B_subsurface_color, Pawn_Top_B_subsurface_radius, Pawn_Top_B_subsurface_scale, Pawn_Top_B_subsurface_anisotropy, Pawn_Top_B_sheen, Pawn_Top_B_sheen_color, Pawn_Top_B_sheen_roughness, Pawn_Top_B_coat, Pawn_Top_B_coat_color, Pawn_Top_B_coat_roughness, Pawn_Top_B_coat_anisotropy, Pawn_Top_B_coat_rotation, Pawn_Top_B_coat_IOR, geomprop_Nworld_out1, Pawn_Top_B_coat_affect_color, Pawn_Top_B_coat_affect_roughness, Pawn_Top_B_thin_film_thickness, Pawn_Top_B_thin_film_IOR, Pawn_Top_B_emission, Pawn_Top_B_emission_color, Pawn_Top_B_opacity, Pawn_Top_B_thin_walled, mtlxnormalmap14_out, geomprop_Tworld_out1, Pawn_Top_B_out); + material M_Pawn_Top_B_out = Pawn_Top_B_out; + out1 = float4(M_Pawn_Top_B_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d mtlximage19_file_tex [[texture(0)]], sampler mtlximage19_file_sampler [[sampler(0)]] +, texture2d mtlximage18_file_tex [[texture(1)]], sampler mtlximage18_file_sampler [[sampler(1)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(2)]], sampler u_envRadiance_sampler [[sampler(2)]] +, texture2d u_envIrradiance_tex [[texture(3)]], sampler u_envIrradiance_sampler [[sampler(3)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +mtlximage19_file_tex, mtlximage19_file_sampler } + , u_pub.mtlximage19_layer + , u_pub.mtlximage19_default + , u_pub.mtlximage19_uaddressmode + , u_pub.mtlximage19_vaddressmode + , u_pub.mtlximage19_filtertype + , u_pub.mtlximage19_framerange + , u_pub.mtlximage19_frameoffset + , u_pub.mtlximage19_frameendaction + , u_pub.mtlximage19_uv_scale + , u_pub.mtlximage19_uv_offset +, MetalTexture { +mtlximage18_file_tex, mtlximage18_file_sampler } + , u_pub.mtlximage18_layer + , u_pub.mtlximage18_default + , u_pub.mtlximage18_uaddressmode + , u_pub.mtlximage18_vaddressmode + , u_pub.mtlximage18_filtertype + , u_pub.mtlximage18_framerange + , u_pub.mtlximage18_frameoffset + , u_pub.mtlximage18_frameendaction + , u_pub.mtlximage18_uv_scale + , u_pub.mtlximage18_uv_offset + , u_pub.mtlxnormalmap14_scale + , u_pub.Pawn_Top_B_base + , u_pub.Pawn_Top_B_base_color + , u_pub.Pawn_Top_B_diffuse_roughness + , u_pub.Pawn_Top_B_metalness + , u_pub.Pawn_Top_B_specular + , u_pub.Pawn_Top_B_specular_color + , u_pub.Pawn_Top_B_specular_IOR + , u_pub.Pawn_Top_B_specular_anisotropy + , u_pub.Pawn_Top_B_specular_rotation + , u_pub.Pawn_Top_B_transmission + , u_pub.Pawn_Top_B_transmission_color + , u_pub.Pawn_Top_B_transmission_depth + , u_pub.Pawn_Top_B_transmission_scatter + , u_pub.Pawn_Top_B_transmission_scatter_anisotropy + , u_pub.Pawn_Top_B_transmission_dispersion + , u_pub.Pawn_Top_B_transmission_extra_roughness + , u_pub.Pawn_Top_B_subsurface + , u_pub.Pawn_Top_B_subsurface_color + , u_pub.Pawn_Top_B_subsurface_radius + , u_pub.Pawn_Top_B_subsurface_scale + , u_pub.Pawn_Top_B_subsurface_anisotropy + , u_pub.Pawn_Top_B_sheen + , u_pub.Pawn_Top_B_sheen_color + , u_pub.Pawn_Top_B_sheen_roughness + , u_pub.Pawn_Top_B_coat + , u_pub.Pawn_Top_B_coat_color + , u_pub.Pawn_Top_B_coat_roughness + , u_pub.Pawn_Top_B_coat_anisotropy + , u_pub.Pawn_Top_B_coat_rotation + , u_pub.Pawn_Top_B_coat_IOR + , u_pub.Pawn_Top_B_coat_affect_color + , u_pub.Pawn_Top_B_coat_affect_roughness + , u_pub.Pawn_Top_B_thin_film_thickness + , u_pub.Pawn_Top_B_thin_film_IOR + , u_pub.Pawn_Top_B_emission + , u_pub.Pawn_Top_B_emission_color + , u_pub.Pawn_Top_B_opacity + , u_pub.Pawn_Top_B_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Top_B.msl.vert b/Materials/Examples/StandardSurface/M_Pawn_Top_B.msl.vert new file mode 100644 index 0000000000..2f90d0d634 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Top_B.msl.vert @@ -0,0 +1,124 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'mtlximage19'. Function already called in this scope. + // Omitted node 'mtlximage18'. Function already called in this scope. + // Omitted node 'mtlxnormalmap14'. Function already called in this scope. + // Omitted node 'Pawn_Top_B'. Function already called in this scope. + // Omitted node 'M_Pawn_Top_B'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Top_B.osl b/Materials/Examples/StandardSurface/M_Pawn_Top_B.osl new file mode 100644 index 0000000000..19a1f80e54 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Top_B.osl @@ -0,0 +1,574 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Pawn_Top_B +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Pawn_Top_B" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string mtlximage19_file = "chess_set/pawn_shared_roughness.jpg" + [[ + string widget = "filename" + ]], + string mtlximage19_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage19_layer = "", + float mtlximage19_default = 0.000000 + [[ + string widget = "number" + ]], + string mtlximage19_uaddressmode = "periodic", + string mtlximage19_vaddressmode = "periodic", + string mtlximage19_filtertype = "linear", + string mtlximage19_framerange = "", + int mtlximage19_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage19_frameendaction = "constant", + string mtlximage18_file = "chess_set/pawn_shared_normal.jpg" + [[ + string widget = "filename" + ]], + string mtlximage18_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage18_layer = "", + vector mtlximage18_default = vector(0.000000, 0.000000, 0.000000), + string mtlximage18_uaddressmode = "periodic", + string mtlximage18_vaddressmode = "periodic", + string mtlximage18_filtertype = "linear", + string mtlximage18_framerange = "", + int mtlximage18_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage18_frameendaction = "constant", + float mtlxnormalmap14_scale = 1.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_base = 1.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_B_base_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Top_B_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_metalness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_specular = 1.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_B_specular_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Top_B_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_transmission = 1.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_B_transmission_color = color(0.299500, 0.500000, 0.450276), + float Pawn_Top_B_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_B_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Pawn_Top_B_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_B_subsurface_color = color(1.000000, 1.000000, 1.000000), + color Pawn_Top_B_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float Pawn_Top_B_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_B_sheen_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Top_B_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_coat = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_B_coat_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Top_B_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Pawn_Top_B_emission = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_B_emission_color = color(1.000000, 1.000000, 1.000000), + color Pawn_Top_B_opacity = color(1.000000, 1.000000, 1.000000), + int Pawn_Top_B_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource mtlximage19_file_ = {mtlximage19_file, mtlximage19_file_colorspace}; + textureresource mtlximage18_file_ = {mtlximage18_file, mtlximage18_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + float mtlximage19_out = 0.0; + mx_image_float(mtlximage19_file_, mtlximage19_layer, mtlximage19_default, geomprop_UV0_out1, mtlximage19_uaddressmode, mtlximage19_vaddressmode, mtlximage19_filtertype, mtlximage19_framerange, mtlximage19_frameoffset, mtlximage19_frameendaction, mtlximage19_out); + vector mtlximage18_out = vector(0.0); + mx_image_vector3(mtlximage18_file_, mtlximage18_layer, mtlximage18_default, geomprop_UV0_out1, mtlximage18_uaddressmode, mtlximage18_vaddressmode, mtlximage18_filtertype, mtlximage18_framerange, mtlximage18_frameoffset, mtlximage18_frameendaction, mtlximage18_out); + vector mtlxnormalmap14_out = vector(0.0); + mx_normalmap_float(mtlximage18_out, mtlxnormalmap14_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap14_out); + surfaceshader Pawn_Top_B_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Pawn_Top_B_base, Pawn_Top_B_base_color, Pawn_Top_B_diffuse_roughness, Pawn_Top_B_metalness, Pawn_Top_B_specular, Pawn_Top_B_specular_color, mtlximage19_out, Pawn_Top_B_specular_IOR, Pawn_Top_B_specular_anisotropy, Pawn_Top_B_specular_rotation, Pawn_Top_B_transmission, Pawn_Top_B_transmission_color, Pawn_Top_B_transmission_depth, Pawn_Top_B_transmission_scatter, Pawn_Top_B_transmission_scatter_anisotropy, Pawn_Top_B_transmission_dispersion, Pawn_Top_B_transmission_extra_roughness, Pawn_Top_B_subsurface, Pawn_Top_B_subsurface_color, Pawn_Top_B_subsurface_radius, Pawn_Top_B_subsurface_scale, Pawn_Top_B_subsurface_anisotropy, Pawn_Top_B_sheen, Pawn_Top_B_sheen_color, Pawn_Top_B_sheen_roughness, Pawn_Top_B_coat, Pawn_Top_B_coat_color, Pawn_Top_B_coat_roughness, Pawn_Top_B_coat_anisotropy, Pawn_Top_B_coat_rotation, Pawn_Top_B_coat_IOR, geomprop_Nworld_out1, Pawn_Top_B_coat_affect_color, Pawn_Top_B_coat_affect_roughness, Pawn_Top_B_thin_film_thickness, Pawn_Top_B_thin_film_IOR, Pawn_Top_B_emission, Pawn_Top_B_emission_color, Pawn_Top_B_opacity, Pawn_Top_B_thin_walled, mtlxnormalmap14_out, geomprop_Tworld_out1, Pawn_Top_B_out); + MATERIAL M_Pawn_Top_B_out = mx_surfacematerial(Pawn_Top_B_out, backsurfaceshader, displacementshader1); + out = M_Pawn_Top_B_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Top_W.glsl.frag b/Materials/Examples/StandardSurface/M_Pawn_Top_W.glsl.frag new file mode 100644 index 0000000000..e31e0468f6 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Top_W.glsl.frag @@ -0,0 +1,1936 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D mtlximage21_file; +uniform int mtlximage21_layer = 0; +uniform float mtlximage21_default = 0.000000; +uniform int mtlximage21_uaddressmode = 2; +uniform int mtlximage21_vaddressmode = 2; +uniform int mtlximage21_filtertype = 1; +uniform int mtlximage21_framerange = 0; +uniform int mtlximage21_frameoffset = 0; +uniform int mtlximage21_frameendaction = 0; +uniform vec2 mtlximage21_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage21_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D mtlximage20_file; +uniform int mtlximage20_layer = 0; +uniform vec3 mtlximage20_default = vec3(0.000000, 0.000000, 0.000000); +uniform int mtlximage20_uaddressmode = 2; +uniform int mtlximage20_vaddressmode = 2; +uniform int mtlximage20_filtertype = 1; +uniform int mtlximage20_framerange = 0; +uniform int mtlximage20_frameoffset = 0; +uniform int mtlximage20_frameendaction = 0; +uniform vec2 mtlximage20_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 mtlximage20_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap15_scale = 1.000000; +uniform float Pawn_Top_W_base = 1.000000; +uniform vec3 Pawn_Top_W_base_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Top_W_diffuse_roughness = 0.000000; +uniform float Pawn_Top_W_metalness = 0.000000; +uniform float Pawn_Top_W_specular = 1.000000; +uniform vec3 Pawn_Top_W_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Top_W_specular_IOR = 1.500000; +uniform float Pawn_Top_W_specular_anisotropy = 0.000000; +uniform float Pawn_Top_W_specular_rotation = 0.000000; +uniform float Pawn_Top_W_transmission = 1.000000; +uniform vec3 Pawn_Top_W_transmission_color = vec3(1.000000, 1.000000, 0.828000); +uniform float Pawn_Top_W_transmission_depth = 0.000000; +uniform vec3 Pawn_Top_W_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Pawn_Top_W_transmission_scatter_anisotropy = 0.000000; +uniform float Pawn_Top_W_transmission_dispersion = 0.000000; +uniform float Pawn_Top_W_transmission_extra_roughness = 0.000000; +uniform float Pawn_Top_W_subsurface = 0.000000; +uniform vec3 Pawn_Top_W_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Pawn_Top_W_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Top_W_subsurface_scale = 0.003000; +uniform float Pawn_Top_W_subsurface_anisotropy = 0.000000; +uniform float Pawn_Top_W_sheen = 0.000000; +uniform vec3 Pawn_Top_W_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Top_W_sheen_roughness = 0.300000; +uniform float Pawn_Top_W_coat = 0.000000; +uniform vec3 Pawn_Top_W_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Pawn_Top_W_coat_roughness = 0.100000; +uniform float Pawn_Top_W_coat_anisotropy = 0.000000; +uniform float Pawn_Top_W_coat_rotation = 0.000000; +uniform float Pawn_Top_W_coat_IOR = 1.500000; +uniform float Pawn_Top_W_coat_affect_color = 0.000000; +uniform float Pawn_Top_W_coat_affect_roughness = 0.000000; +uniform float Pawn_Top_W_thin_film_thickness = 0.000000; +uniform float Pawn_Top_W_thin_film_IOR = 1.500000; +uniform float Pawn_Top_W_emission = 0.000000; +uniform vec3 Pawn_Top_W_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Pawn_Top_W_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Pawn_Top_W_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + float mtlximage21_out = 0.0; + mx_image_float(mtlximage21_file, mtlximage21_layer, mtlximage21_default, geomprop_UV0_out1, mtlximage21_uaddressmode, mtlximage21_vaddressmode, mtlximage21_filtertype, mtlximage21_framerange, mtlximage21_frameoffset, mtlximage21_frameendaction, mtlximage21_uv_scale, mtlximage21_uv_offset, mtlximage21_out); + vec3 mtlximage20_out = vec3(0.0); + mx_image_vector3(mtlximage20_file, mtlximage20_layer, mtlximage20_default, geomprop_UV0_out1, mtlximage20_uaddressmode, mtlximage20_vaddressmode, mtlximage20_filtertype, mtlximage20_framerange, mtlximage20_frameoffset, mtlximage20_frameendaction, mtlximage20_uv_scale, mtlximage20_uv_offset, mtlximage20_out); + vec3 mtlxnormalmap15_out = vec3(0.0); + mx_normalmap_float(mtlximage20_out, mtlxnormalmap15_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap15_out); + surfaceshader Pawn_Top_W_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Pawn_Top_W_base, Pawn_Top_W_base_color, Pawn_Top_W_diffuse_roughness, Pawn_Top_W_metalness, Pawn_Top_W_specular, Pawn_Top_W_specular_color, mtlximage21_out, Pawn_Top_W_specular_IOR, Pawn_Top_W_specular_anisotropy, Pawn_Top_W_specular_rotation, Pawn_Top_W_transmission, Pawn_Top_W_transmission_color, Pawn_Top_W_transmission_depth, Pawn_Top_W_transmission_scatter, Pawn_Top_W_transmission_scatter_anisotropy, Pawn_Top_W_transmission_dispersion, Pawn_Top_W_transmission_extra_roughness, Pawn_Top_W_subsurface, Pawn_Top_W_subsurface_color, Pawn_Top_W_subsurface_radius, Pawn_Top_W_subsurface_scale, Pawn_Top_W_subsurface_anisotropy, Pawn_Top_W_sheen, Pawn_Top_W_sheen_color, Pawn_Top_W_sheen_roughness, Pawn_Top_W_coat, Pawn_Top_W_coat_color, Pawn_Top_W_coat_roughness, Pawn_Top_W_coat_anisotropy, Pawn_Top_W_coat_rotation, Pawn_Top_W_coat_IOR, geomprop_Nworld_out1, Pawn_Top_W_coat_affect_color, Pawn_Top_W_coat_affect_roughness, Pawn_Top_W_thin_film_thickness, Pawn_Top_W_thin_film_IOR, Pawn_Top_W_emission, Pawn_Top_W_emission_color, Pawn_Top_W_opacity, Pawn_Top_W_thin_walled, mtlxnormalmap15_out, geomprop_Tworld_out1, Pawn_Top_W_out); + material M_Pawn_Top_W_out = Pawn_Top_W_out; + out1 = vec4(M_Pawn_Top_W_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Top_W.glsl.vert b/Materials/Examples/StandardSurface/M_Pawn_Top_W.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Top_W.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Top_W.mdl b/Materials/Examples/StandardSurface/M_Pawn_Top_W.mdl new file mode 100644 index 0000000000..caaa4a8c85 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Top_W.mdl @@ -0,0 +1,406 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Pawn_Top_W +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d mtlximage21_file = texture_2d("/chess_set/pawn_shared_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage21/file") + ]], + uniform string mtlximage21_layer = "" + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage21/layer") + ]], + float mtlximage21_default = 0.000000 + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage21/default") + ]], + uniform mx_addressmode_type mtlximage21_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage21/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage21_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage21/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage21_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage21/filtertype") + ]], + uniform string mtlximage21_framerange = "" + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage21/framerange") + ]], + uniform int mtlximage21_frameoffset = 0 + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage21/frameoffset") + ]], + uniform mx_addressmode_type mtlximage21_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage21/frameendaction") + ]], + uniform texture_2d mtlximage20_file = texture_2d("/chess_set/pawn_shared_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage20/file") + ]], + uniform string mtlximage20_layer = "" + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage20/layer") + ]], + float3 mtlximage20_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage20/default") + ]], + uniform mx_addressmode_type mtlximage20_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage20/uaddressmode") + ]], + uniform mx_addressmode_type mtlximage20_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage20/vaddressmode") + ]], + uniform mx_filterlookup_type mtlximage20_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage20/filtertype") + ]], + uniform string mtlximage20_framerange = "" + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage20/framerange") + ]], + uniform int mtlximage20_frameoffset = 0 + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage20/frameoffset") + ]], + uniform mx_addressmode_type mtlximage20_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_PawnTopWhite/mtlximage20/frameendaction") + ]], + float mtlxnormalmap15_scale = 1.000000 + [[ + materialx::core::origin("NG_PawnTopWhite/mtlxnormalmap15/scale") + ]], + float Pawn_Top_W_base = 1.000000 + [[ + materialx::core::origin("Pawn_Top_W/base") + ]], + color Pawn_Top_W_base_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_W/base_color") + ]], + float Pawn_Top_W_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/diffuse_roughness") + ]], + float Pawn_Top_W_metalness = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/metalness") + ]], + float Pawn_Top_W_specular = 1.000000 + [[ + materialx::core::origin("Pawn_Top_W/specular") + ]], + color Pawn_Top_W_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_W/specular_color") + ]], + uniform float Pawn_Top_W_specular_IOR = 1.500000 + [[ + materialx::core::origin("Pawn_Top_W/specular_IOR") + ]], + float Pawn_Top_W_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/specular_anisotropy") + ]], + float Pawn_Top_W_specular_rotation = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/specular_rotation") + ]], + float Pawn_Top_W_transmission = 1.000000 + [[ + materialx::core::origin("Pawn_Top_W/transmission") + ]], + color Pawn_Top_W_transmission_color = color(1.000000, 1.000000, 0.828000) + [[ + materialx::core::origin("Pawn_Top_W/transmission_color") + ]], + float Pawn_Top_W_transmission_depth = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/transmission_depth") + ]], + color Pawn_Top_W_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Pawn_Top_W/transmission_scatter") + ]], + float Pawn_Top_W_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/transmission_scatter_anisotropy") + ]], + float Pawn_Top_W_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/transmission_dispersion") + ]], + float Pawn_Top_W_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/transmission_extra_roughness") + ]], + float Pawn_Top_W_subsurface = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/subsurface") + ]], + color Pawn_Top_W_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_W/subsurface_color") + ]], + color Pawn_Top_W_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_W/subsurface_radius") + ]], + float Pawn_Top_W_subsurface_scale = 0.003000 + [[ + materialx::core::origin("Pawn_Top_W/subsurface_scale") + ]], + float Pawn_Top_W_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/subsurface_anisotropy") + ]], + float Pawn_Top_W_sheen = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/sheen") + ]], + color Pawn_Top_W_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_W/sheen_color") + ]], + float Pawn_Top_W_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Pawn_Top_W/sheen_roughness") + ]], + float Pawn_Top_W_coat = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/coat") + ]], + color Pawn_Top_W_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_W/coat_color") + ]], + float Pawn_Top_W_coat_roughness = 0.100000 + [[ + materialx::core::origin("Pawn_Top_W/coat_roughness") + ]], + float Pawn_Top_W_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/coat_anisotropy") + ]], + float Pawn_Top_W_coat_rotation = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/coat_rotation") + ]], + uniform float Pawn_Top_W_coat_IOR = 1.500000 + [[ + materialx::core::origin("Pawn_Top_W/coat_IOR") + ]], + float Pawn_Top_W_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/coat_affect_color") + ]], + float Pawn_Top_W_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/coat_affect_roughness") + ]], + float Pawn_Top_W_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/thin_film_thickness") + ]], + float Pawn_Top_W_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Pawn_Top_W/thin_film_IOR") + ]], + float Pawn_Top_W_emission = 0.000000 + [[ + materialx::core::origin("Pawn_Top_W/emission") + ]], + color Pawn_Top_W_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_W/emission_color") + ]], + color Pawn_Top_W_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Pawn_Top_W/opacity") + ]], + bool Pawn_Top_W_thin_walled = false + [[ + materialx::core::origin("Pawn_Top_W/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + float mtlximage21_out = materialx::stdlib_1_8::mx_image_float(mtlximage21_file, mtlximage21_layer, mtlximage21_default, geomprop_UV0_out1, mtlximage21_uaddressmode, mtlximage21_vaddressmode, mtlximage21_filtertype, mtlximage21_framerange, mtlximage21_frameoffset, mtlximage21_frameendaction, mxp_flip_v:false); + float3 mtlximage20_out = materialx::stdlib_1_8::mx_image_vector3(mtlximage20_file, mtlximage20_layer, mtlximage20_default, geomprop_UV0_out1, mtlximage20_uaddressmode, mtlximage20_vaddressmode, mtlximage20_filtertype, mtlximage20_framerange, mtlximage20_frameoffset, mtlximage20_frameendaction, mxp_flip_v:false); + float3 mtlxnormalmap15_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:mtlximage20_out, mxp_scale:mtlxnormalmap15_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Pawn_Top_W_out = NG_standard_surface_surfaceshader_100(Pawn_Top_W_base, Pawn_Top_W_base_color, Pawn_Top_W_diffuse_roughness, Pawn_Top_W_metalness, Pawn_Top_W_specular, Pawn_Top_W_specular_color, mtlximage21_out, Pawn_Top_W_specular_IOR, Pawn_Top_W_specular_anisotropy, Pawn_Top_W_specular_rotation, Pawn_Top_W_transmission, Pawn_Top_W_transmission_color, Pawn_Top_W_transmission_depth, Pawn_Top_W_transmission_scatter, Pawn_Top_W_transmission_scatter_anisotropy, Pawn_Top_W_transmission_dispersion, Pawn_Top_W_transmission_extra_roughness, Pawn_Top_W_subsurface, Pawn_Top_W_subsurface_color, Pawn_Top_W_subsurface_radius, Pawn_Top_W_subsurface_scale, Pawn_Top_W_subsurface_anisotropy, Pawn_Top_W_sheen, Pawn_Top_W_sheen_color, Pawn_Top_W_sheen_roughness, Pawn_Top_W_coat, Pawn_Top_W_coat_color, Pawn_Top_W_coat_roughness, Pawn_Top_W_coat_anisotropy, Pawn_Top_W_coat_rotation, Pawn_Top_W_coat_IOR, geomprop_Nworld_out1, Pawn_Top_W_coat_affect_color, Pawn_Top_W_coat_affect_roughness, Pawn_Top_W_thin_film_thickness, Pawn_Top_W_thin_film_IOR, Pawn_Top_W_emission, Pawn_Top_W_emission_color, Pawn_Top_W_opacity, Pawn_Top_W_thin_walled, mtlxnormalmap15_out, geomprop_Tworld_out1); + material M_Pawn_Top_W_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Pawn_Top_W_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Pawn_Top_W_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Pawn_Top_W.msl.frag b/Materials/Examples/StandardSurface/M_Pawn_Top_W.msl.frag new file mode 100644 index 0000000000..f277266360 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Top_W.msl.frag @@ -0,0 +1,2748 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int mtlximage21_layer; + float mtlximage21_default; + int mtlximage21_uaddressmode; + int mtlximage21_vaddressmode; + int mtlximage21_filtertype; + int mtlximage21_framerange; + int mtlximage21_frameoffset; + int mtlximage21_frameendaction; + vec2 mtlximage21_uv_scale; + vec2 mtlximage21_uv_offset; + int mtlximage20_layer; + vec3 mtlximage20_default; + int mtlximage20_uaddressmode; + int mtlximage20_vaddressmode; + int mtlximage20_filtertype; + int mtlximage20_framerange; + int mtlximage20_frameoffset; + int mtlximage20_frameendaction; + vec2 mtlximage20_uv_scale; + vec2 mtlximage20_uv_offset; + float mtlxnormalmap15_scale; + float Pawn_Top_W_base; + vec3 Pawn_Top_W_base_color; + float Pawn_Top_W_diffuse_roughness; + float Pawn_Top_W_metalness; + float Pawn_Top_W_specular; + vec3 Pawn_Top_W_specular_color; + float Pawn_Top_W_specular_IOR; + float Pawn_Top_W_specular_anisotropy; + float Pawn_Top_W_specular_rotation; + float Pawn_Top_W_transmission; + vec3 Pawn_Top_W_transmission_color; + float Pawn_Top_W_transmission_depth; + vec3 Pawn_Top_W_transmission_scatter; + float Pawn_Top_W_transmission_scatter_anisotropy; + float Pawn_Top_W_transmission_dispersion; + float Pawn_Top_W_transmission_extra_roughness; + float Pawn_Top_W_subsurface; + vec3 Pawn_Top_W_subsurface_color; + vec3 Pawn_Top_W_subsurface_radius; + float Pawn_Top_W_subsurface_scale; + float Pawn_Top_W_subsurface_anisotropy; + float Pawn_Top_W_sheen; + vec3 Pawn_Top_W_sheen_color; + float Pawn_Top_W_sheen_roughness; + float Pawn_Top_W_coat; + vec3 Pawn_Top_W_coat_color; + float Pawn_Top_W_coat_roughness; + float Pawn_Top_W_coat_anisotropy; + float Pawn_Top_W_coat_rotation; + float Pawn_Top_W_coat_IOR; + float Pawn_Top_W_coat_affect_color; + float Pawn_Top_W_coat_affect_roughness; + float Pawn_Top_W_thin_film_thickness; + float Pawn_Top_W_thin_film_IOR; + float Pawn_Top_W_emission; + vec3 Pawn_Top_W_emission_color; + vec3 Pawn_Top_W_opacity; + bool Pawn_Top_W_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture mtlximage21_file , int mtlximage21_layer + + , float mtlximage21_default + + , int mtlximage21_uaddressmode + + , int mtlximage21_vaddressmode + + , int mtlximage21_filtertype + + , int mtlximage21_framerange + + , int mtlximage21_frameoffset + + , int mtlximage21_frameendaction + + , vec2 mtlximage21_uv_scale + + , vec2 mtlximage21_uv_offset + +, MetalTexture mtlximage20_file , int mtlximage20_layer + + , vec3 mtlximage20_default + + , int mtlximage20_uaddressmode + + , int mtlximage20_vaddressmode + + , int mtlximage20_filtertype + + , int mtlximage20_framerange + + , int mtlximage20_frameoffset + + , int mtlximage20_frameendaction + + , vec2 mtlximage20_uv_scale + + , vec2 mtlximage20_uv_offset + + , float mtlxnormalmap15_scale + + , float Pawn_Top_W_base + + , vec3 Pawn_Top_W_base_color + + , float Pawn_Top_W_diffuse_roughness + + , float Pawn_Top_W_metalness + + , float Pawn_Top_W_specular + + , vec3 Pawn_Top_W_specular_color + + , float Pawn_Top_W_specular_IOR + + , float Pawn_Top_W_specular_anisotropy + + , float Pawn_Top_W_specular_rotation + + , float Pawn_Top_W_transmission + + , vec3 Pawn_Top_W_transmission_color + + , float Pawn_Top_W_transmission_depth + + , vec3 Pawn_Top_W_transmission_scatter + + , float Pawn_Top_W_transmission_scatter_anisotropy + + , float Pawn_Top_W_transmission_dispersion + + , float Pawn_Top_W_transmission_extra_roughness + + , float Pawn_Top_W_subsurface + + , vec3 Pawn_Top_W_subsurface_color + + , vec3 Pawn_Top_W_subsurface_radius + + , float Pawn_Top_W_subsurface_scale + + , float Pawn_Top_W_subsurface_anisotropy + + , float Pawn_Top_W_sheen + + , vec3 Pawn_Top_W_sheen_color + + , float Pawn_Top_W_sheen_roughness + + , float Pawn_Top_W_coat + + , vec3 Pawn_Top_W_coat_color + + , float Pawn_Top_W_coat_roughness + + , float Pawn_Top_W_coat_anisotropy + + , float Pawn_Top_W_coat_rotation + + , float Pawn_Top_W_coat_IOR + + , float Pawn_Top_W_coat_affect_color + + , float Pawn_Top_W_coat_affect_roughness + + , float Pawn_Top_W_thin_film_thickness + + , float Pawn_Top_W_thin_film_IOR + + , float Pawn_Top_W_emission + + , vec3 Pawn_Top_W_emission_color + + , vec3 Pawn_Top_W_opacity + + , bool Pawn_Top_W_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, mtlximage21_file(mtlximage21_file) + , mtlximage21_layer(mtlximage21_layer) + + , mtlximage21_default(mtlximage21_default) + + , mtlximage21_uaddressmode(mtlximage21_uaddressmode) + + , mtlximage21_vaddressmode(mtlximage21_vaddressmode) + + , mtlximage21_filtertype(mtlximage21_filtertype) + + , mtlximage21_framerange(mtlximage21_framerange) + + , mtlximage21_frameoffset(mtlximage21_frameoffset) + + , mtlximage21_frameendaction(mtlximage21_frameendaction) + + , mtlximage21_uv_scale(mtlximage21_uv_scale) + + , mtlximage21_uv_offset(mtlximage21_uv_offset) + +, mtlximage20_file(mtlximage20_file) + , mtlximage20_layer(mtlximage20_layer) + + , mtlximage20_default(mtlximage20_default) + + , mtlximage20_uaddressmode(mtlximage20_uaddressmode) + + , mtlximage20_vaddressmode(mtlximage20_vaddressmode) + + , mtlximage20_filtertype(mtlximage20_filtertype) + + , mtlximage20_framerange(mtlximage20_framerange) + + , mtlximage20_frameoffset(mtlximage20_frameoffset) + + , mtlximage20_frameendaction(mtlximage20_frameendaction) + + , mtlximage20_uv_scale(mtlximage20_uv_scale) + + , mtlximage20_uv_offset(mtlximage20_uv_offset) + + , mtlxnormalmap15_scale(mtlxnormalmap15_scale) + + , Pawn_Top_W_base(Pawn_Top_W_base) + + , Pawn_Top_W_base_color(Pawn_Top_W_base_color) + + , Pawn_Top_W_diffuse_roughness(Pawn_Top_W_diffuse_roughness) + + , Pawn_Top_W_metalness(Pawn_Top_W_metalness) + + , Pawn_Top_W_specular(Pawn_Top_W_specular) + + , Pawn_Top_W_specular_color(Pawn_Top_W_specular_color) + + , Pawn_Top_W_specular_IOR(Pawn_Top_W_specular_IOR) + + , Pawn_Top_W_specular_anisotropy(Pawn_Top_W_specular_anisotropy) + + , Pawn_Top_W_specular_rotation(Pawn_Top_W_specular_rotation) + + , Pawn_Top_W_transmission(Pawn_Top_W_transmission) + + , Pawn_Top_W_transmission_color(Pawn_Top_W_transmission_color) + + , Pawn_Top_W_transmission_depth(Pawn_Top_W_transmission_depth) + + , Pawn_Top_W_transmission_scatter(Pawn_Top_W_transmission_scatter) + + , Pawn_Top_W_transmission_scatter_anisotropy(Pawn_Top_W_transmission_scatter_anisotropy) + + , Pawn_Top_W_transmission_dispersion(Pawn_Top_W_transmission_dispersion) + + , Pawn_Top_W_transmission_extra_roughness(Pawn_Top_W_transmission_extra_roughness) + + , Pawn_Top_W_subsurface(Pawn_Top_W_subsurface) + + , Pawn_Top_W_subsurface_color(Pawn_Top_W_subsurface_color) + + , Pawn_Top_W_subsurface_radius(Pawn_Top_W_subsurface_radius) + + , Pawn_Top_W_subsurface_scale(Pawn_Top_W_subsurface_scale) + + , Pawn_Top_W_subsurface_anisotropy(Pawn_Top_W_subsurface_anisotropy) + + , Pawn_Top_W_sheen(Pawn_Top_W_sheen) + + , Pawn_Top_W_sheen_color(Pawn_Top_W_sheen_color) + + , Pawn_Top_W_sheen_roughness(Pawn_Top_W_sheen_roughness) + + , Pawn_Top_W_coat(Pawn_Top_W_coat) + + , Pawn_Top_W_coat_color(Pawn_Top_W_coat_color) + + , Pawn_Top_W_coat_roughness(Pawn_Top_W_coat_roughness) + + , Pawn_Top_W_coat_anisotropy(Pawn_Top_W_coat_anisotropy) + + , Pawn_Top_W_coat_rotation(Pawn_Top_W_coat_rotation) + + , Pawn_Top_W_coat_IOR(Pawn_Top_W_coat_IOR) + + , Pawn_Top_W_coat_affect_color(Pawn_Top_W_coat_affect_color) + + , Pawn_Top_W_coat_affect_roughness(Pawn_Top_W_coat_affect_roughness) + + , Pawn_Top_W_thin_film_thickness(Pawn_Top_W_thin_film_thickness) + + , Pawn_Top_W_thin_film_IOR(Pawn_Top_W_thin_film_IOR) + + , Pawn_Top_W_emission(Pawn_Top_W_emission) + + , Pawn_Top_W_emission_color(Pawn_Top_W_emission_color) + + , Pawn_Top_W_opacity(Pawn_Top_W_opacity) + + , Pawn_Top_W_thin_walled(Pawn_Top_W_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture mtlximage21_file; + int mtlximage21_layer; + + + float mtlximage21_default; + + + int mtlximage21_uaddressmode; + + + int mtlximage21_vaddressmode; + + + int mtlximage21_filtertype; + + + int mtlximage21_framerange; + + + int mtlximage21_frameoffset; + + + int mtlximage21_frameendaction; + + + vec2 mtlximage21_uv_scale; + + + vec2 mtlximage21_uv_offset; + + +MetalTexture mtlximage20_file; + int mtlximage20_layer; + + + vec3 mtlximage20_default; + + + int mtlximage20_uaddressmode; + + + int mtlximage20_vaddressmode; + + + int mtlximage20_filtertype; + + + int mtlximage20_framerange; + + + int mtlximage20_frameoffset; + + + int mtlximage20_frameendaction; + + + vec2 mtlximage20_uv_scale; + + + vec2 mtlximage20_uv_offset; + + + float mtlxnormalmap15_scale; + + + float Pawn_Top_W_base; + + + vec3 Pawn_Top_W_base_color; + + + float Pawn_Top_W_diffuse_roughness; + + + float Pawn_Top_W_metalness; + + + float Pawn_Top_W_specular; + + + vec3 Pawn_Top_W_specular_color; + + + float Pawn_Top_W_specular_IOR; + + + float Pawn_Top_W_specular_anisotropy; + + + float Pawn_Top_W_specular_rotation; + + + float Pawn_Top_W_transmission; + + + vec3 Pawn_Top_W_transmission_color; + + + float Pawn_Top_W_transmission_depth; + + + vec3 Pawn_Top_W_transmission_scatter; + + + float Pawn_Top_W_transmission_scatter_anisotropy; + + + float Pawn_Top_W_transmission_dispersion; + + + float Pawn_Top_W_transmission_extra_roughness; + + + float Pawn_Top_W_subsurface; + + + vec3 Pawn_Top_W_subsurface_color; + + + vec3 Pawn_Top_W_subsurface_radius; + + + float Pawn_Top_W_subsurface_scale; + + + float Pawn_Top_W_subsurface_anisotropy; + + + float Pawn_Top_W_sheen; + + + vec3 Pawn_Top_W_sheen_color; + + + float Pawn_Top_W_sheen_roughness; + + + float Pawn_Top_W_coat; + + + vec3 Pawn_Top_W_coat_color; + + + float Pawn_Top_W_coat_roughness; + + + float Pawn_Top_W_coat_anisotropy; + + + float Pawn_Top_W_coat_rotation; + + + float Pawn_Top_W_coat_IOR; + + + float Pawn_Top_W_coat_affect_color; + + + float Pawn_Top_W_coat_affect_roughness; + + + float Pawn_Top_W_thin_film_thickness; + + + float Pawn_Top_W_thin_film_IOR; + + + float Pawn_Top_W_emission; + + + vec3 Pawn_Top_W_emission_color; + + + vec3 Pawn_Top_W_opacity; + + + bool Pawn_Top_W_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + float mtlximage21_out = 0.0; + mx_image_float(mtlximage21_file, mtlximage21_layer, mtlximage21_default, geomprop_UV0_out1, mtlximage21_uaddressmode, mtlximage21_vaddressmode, mtlximage21_filtertype, mtlximage21_framerange, mtlximage21_frameoffset, mtlximage21_frameendaction, mtlximage21_uv_scale, mtlximage21_uv_offset, mtlximage21_out); + vec3 mtlximage20_out = vec3(0.0); + mx_image_vector3(mtlximage20_file, mtlximage20_layer, mtlximage20_default, geomprop_UV0_out1, mtlximage20_uaddressmode, mtlximage20_vaddressmode, mtlximage20_filtertype, mtlximage20_framerange, mtlximage20_frameoffset, mtlximage20_frameendaction, mtlximage20_uv_scale, mtlximage20_uv_offset, mtlximage20_out); + vec3 mtlxnormalmap15_out = vec3(0.0); + mx_normalmap_float(mtlximage20_out, mtlxnormalmap15_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap15_out); + surfaceshader Pawn_Top_W_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Pawn_Top_W_base, Pawn_Top_W_base_color, Pawn_Top_W_diffuse_roughness, Pawn_Top_W_metalness, Pawn_Top_W_specular, Pawn_Top_W_specular_color, mtlximage21_out, Pawn_Top_W_specular_IOR, Pawn_Top_W_specular_anisotropy, Pawn_Top_W_specular_rotation, Pawn_Top_W_transmission, Pawn_Top_W_transmission_color, Pawn_Top_W_transmission_depth, Pawn_Top_W_transmission_scatter, Pawn_Top_W_transmission_scatter_anisotropy, Pawn_Top_W_transmission_dispersion, Pawn_Top_W_transmission_extra_roughness, Pawn_Top_W_subsurface, Pawn_Top_W_subsurface_color, Pawn_Top_W_subsurface_radius, Pawn_Top_W_subsurface_scale, Pawn_Top_W_subsurface_anisotropy, Pawn_Top_W_sheen, Pawn_Top_W_sheen_color, Pawn_Top_W_sheen_roughness, Pawn_Top_W_coat, Pawn_Top_W_coat_color, Pawn_Top_W_coat_roughness, Pawn_Top_W_coat_anisotropy, Pawn_Top_W_coat_rotation, Pawn_Top_W_coat_IOR, geomprop_Nworld_out1, Pawn_Top_W_coat_affect_color, Pawn_Top_W_coat_affect_roughness, Pawn_Top_W_thin_film_thickness, Pawn_Top_W_thin_film_IOR, Pawn_Top_W_emission, Pawn_Top_W_emission_color, Pawn_Top_W_opacity, Pawn_Top_W_thin_walled, mtlxnormalmap15_out, geomprop_Tworld_out1, Pawn_Top_W_out); + material M_Pawn_Top_W_out = Pawn_Top_W_out; + out1 = float4(M_Pawn_Top_W_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d mtlximage21_file_tex [[texture(0)]], sampler mtlximage21_file_sampler [[sampler(0)]] +, texture2d mtlximage20_file_tex [[texture(1)]], sampler mtlximage20_file_sampler [[sampler(1)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(2)]], sampler u_envRadiance_sampler [[sampler(2)]] +, texture2d u_envIrradiance_tex [[texture(3)]], sampler u_envIrradiance_sampler [[sampler(3)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +mtlximage21_file_tex, mtlximage21_file_sampler } + , u_pub.mtlximage21_layer + , u_pub.mtlximage21_default + , u_pub.mtlximage21_uaddressmode + , u_pub.mtlximage21_vaddressmode + , u_pub.mtlximage21_filtertype + , u_pub.mtlximage21_framerange + , u_pub.mtlximage21_frameoffset + , u_pub.mtlximage21_frameendaction + , u_pub.mtlximage21_uv_scale + , u_pub.mtlximage21_uv_offset +, MetalTexture { +mtlximage20_file_tex, mtlximage20_file_sampler } + , u_pub.mtlximage20_layer + , u_pub.mtlximage20_default + , u_pub.mtlximage20_uaddressmode + , u_pub.mtlximage20_vaddressmode + , u_pub.mtlximage20_filtertype + , u_pub.mtlximage20_framerange + , u_pub.mtlximage20_frameoffset + , u_pub.mtlximage20_frameendaction + , u_pub.mtlximage20_uv_scale + , u_pub.mtlximage20_uv_offset + , u_pub.mtlxnormalmap15_scale + , u_pub.Pawn_Top_W_base + , u_pub.Pawn_Top_W_base_color + , u_pub.Pawn_Top_W_diffuse_roughness + , u_pub.Pawn_Top_W_metalness + , u_pub.Pawn_Top_W_specular + , u_pub.Pawn_Top_W_specular_color + , u_pub.Pawn_Top_W_specular_IOR + , u_pub.Pawn_Top_W_specular_anisotropy + , u_pub.Pawn_Top_W_specular_rotation + , u_pub.Pawn_Top_W_transmission + , u_pub.Pawn_Top_W_transmission_color + , u_pub.Pawn_Top_W_transmission_depth + , u_pub.Pawn_Top_W_transmission_scatter + , u_pub.Pawn_Top_W_transmission_scatter_anisotropy + , u_pub.Pawn_Top_W_transmission_dispersion + , u_pub.Pawn_Top_W_transmission_extra_roughness + , u_pub.Pawn_Top_W_subsurface + , u_pub.Pawn_Top_W_subsurface_color + , u_pub.Pawn_Top_W_subsurface_radius + , u_pub.Pawn_Top_W_subsurface_scale + , u_pub.Pawn_Top_W_subsurface_anisotropy + , u_pub.Pawn_Top_W_sheen + , u_pub.Pawn_Top_W_sheen_color + , u_pub.Pawn_Top_W_sheen_roughness + , u_pub.Pawn_Top_W_coat + , u_pub.Pawn_Top_W_coat_color + , u_pub.Pawn_Top_W_coat_roughness + , u_pub.Pawn_Top_W_coat_anisotropy + , u_pub.Pawn_Top_W_coat_rotation + , u_pub.Pawn_Top_W_coat_IOR + , u_pub.Pawn_Top_W_coat_affect_color + , u_pub.Pawn_Top_W_coat_affect_roughness + , u_pub.Pawn_Top_W_thin_film_thickness + , u_pub.Pawn_Top_W_thin_film_IOR + , u_pub.Pawn_Top_W_emission + , u_pub.Pawn_Top_W_emission_color + , u_pub.Pawn_Top_W_opacity + , u_pub.Pawn_Top_W_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Top_W.msl.vert b/Materials/Examples/StandardSurface/M_Pawn_Top_W.msl.vert new file mode 100644 index 0000000000..1641c6a981 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Top_W.msl.vert @@ -0,0 +1,124 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'mtlximage21'. Function already called in this scope. + // Omitted node 'mtlximage20'. Function already called in this scope. + // Omitted node 'mtlxnormalmap15'. Function already called in this scope. + // Omitted node 'Pawn_Top_W'. Function already called in this scope. + // Omitted node 'M_Pawn_Top_W'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Pawn_Top_W.osl b/Materials/Examples/StandardSurface/M_Pawn_Top_W.osl new file mode 100644 index 0000000000..3f5d6bb7a7 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Pawn_Top_W.osl @@ -0,0 +1,574 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Pawn_Top_W +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Pawn_Top_W" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string mtlximage21_file = "chess_set/pawn_shared_roughness.jpg" + [[ + string widget = "filename" + ]], + string mtlximage21_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage21_layer = "", + float mtlximage21_default = 0.000000 + [[ + string widget = "number" + ]], + string mtlximage21_uaddressmode = "periodic", + string mtlximage21_vaddressmode = "periodic", + string mtlximage21_filtertype = "linear", + string mtlximage21_framerange = "", + int mtlximage21_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage21_frameendaction = "constant", + string mtlximage20_file = "chess_set/pawn_shared_normal.jpg" + [[ + string widget = "filename" + ]], + string mtlximage20_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string mtlximage20_layer = "", + vector mtlximage20_default = vector(0.000000, 0.000000, 0.000000), + string mtlximage20_uaddressmode = "periodic", + string mtlximage20_vaddressmode = "periodic", + string mtlximage20_filtertype = "linear", + string mtlximage20_framerange = "", + int mtlximage20_frameoffset = 0 + [[ + string widget = "number" + ]], + string mtlximage20_frameendaction = "constant", + float mtlxnormalmap15_scale = 1.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_base = 1.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_W_base_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Top_W_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_metalness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_specular = 1.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_W_specular_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Top_W_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_transmission = 1.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_W_transmission_color = color(1.000000, 1.000000, 0.828000), + float Pawn_Top_W_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_W_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Pawn_Top_W_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_W_subsurface_color = color(1.000000, 1.000000, 1.000000), + color Pawn_Top_W_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float Pawn_Top_W_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_W_sheen_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Top_W_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_coat = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_W_coat_color = color(1.000000, 1.000000, 1.000000), + float Pawn_Top_W_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Pawn_Top_W_emission = 0.000000 + [[ + string widget = "number" + ]], + color Pawn_Top_W_emission_color = color(1.000000, 1.000000, 1.000000), + color Pawn_Top_W_opacity = color(1.000000, 1.000000, 1.000000), + int Pawn_Top_W_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource mtlximage21_file_ = {mtlximage21_file, mtlximage21_file_colorspace}; + textureresource mtlximage20_file_ = {mtlximage20_file, mtlximage20_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + float mtlximage21_out = 0.0; + mx_image_float(mtlximage21_file_, mtlximage21_layer, mtlximage21_default, geomprop_UV0_out1, mtlximage21_uaddressmode, mtlximage21_vaddressmode, mtlximage21_filtertype, mtlximage21_framerange, mtlximage21_frameoffset, mtlximage21_frameendaction, mtlximage21_out); + vector mtlximage20_out = vector(0.0); + mx_image_vector3(mtlximage20_file_, mtlximage20_layer, mtlximage20_default, geomprop_UV0_out1, mtlximage20_uaddressmode, mtlximage20_vaddressmode, mtlximage20_filtertype, mtlximage20_framerange, mtlximage20_frameoffset, mtlximage20_frameendaction, mtlximage20_out); + vector mtlxnormalmap15_out = vector(0.0); + mx_normalmap_float(mtlximage20_out, mtlxnormalmap15_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap15_out); + surfaceshader Pawn_Top_W_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Pawn_Top_W_base, Pawn_Top_W_base_color, Pawn_Top_W_diffuse_roughness, Pawn_Top_W_metalness, Pawn_Top_W_specular, Pawn_Top_W_specular_color, mtlximage21_out, Pawn_Top_W_specular_IOR, Pawn_Top_W_specular_anisotropy, Pawn_Top_W_specular_rotation, Pawn_Top_W_transmission, Pawn_Top_W_transmission_color, Pawn_Top_W_transmission_depth, Pawn_Top_W_transmission_scatter, Pawn_Top_W_transmission_scatter_anisotropy, Pawn_Top_W_transmission_dispersion, Pawn_Top_W_transmission_extra_roughness, Pawn_Top_W_subsurface, Pawn_Top_W_subsurface_color, Pawn_Top_W_subsurface_radius, Pawn_Top_W_subsurface_scale, Pawn_Top_W_subsurface_anisotropy, Pawn_Top_W_sheen, Pawn_Top_W_sheen_color, Pawn_Top_W_sheen_roughness, Pawn_Top_W_coat, Pawn_Top_W_coat_color, Pawn_Top_W_coat_roughness, Pawn_Top_W_coat_anisotropy, Pawn_Top_W_coat_rotation, Pawn_Top_W_coat_IOR, geomprop_Nworld_out1, Pawn_Top_W_coat_affect_color, Pawn_Top_W_coat_affect_roughness, Pawn_Top_W_thin_film_thickness, Pawn_Top_W_thin_film_IOR, Pawn_Top_W_emission, Pawn_Top_W_emission_color, Pawn_Top_W_opacity, Pawn_Top_W_thin_walled, mtlxnormalmap15_out, geomprop_Tworld_out1, Pawn_Top_W_out); + MATERIAL M_Pawn_Top_W_out = mx_surfacematerial(Pawn_Top_W_out, backsurfaceshader, displacementshader1); + out = M_Pawn_Top_W_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Queen_B.glsl.frag b/Materials/Examples/StandardSurface/M_Queen_B.glsl.frag new file mode 100644 index 0000000000..57c29709a1 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Queen_B.glsl.frag @@ -0,0 +1,2025 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D diffuse_file; +uniform int diffuse_layer = 0; +uniform vec3 diffuse_default = vec3(0.000000, 0.000000, 0.000000); +uniform int diffuse_uaddressmode = 2; +uniform int diffuse_vaddressmode = 2; +uniform int diffuse_filtertype = 1; +uniform int diffuse_framerange = 0; +uniform int diffuse_frameoffset = 0; +uniform int diffuse_frameendaction = 0; +uniform vec2 diffuse_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 diffuse_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D metallic_file; +uniform int metallic_layer = 0; +uniform float metallic_default = 0.000000; +uniform int metallic_uaddressmode = 2; +uniform int metallic_vaddressmode = 2; +uniform int metallic_filtertype = 1; +uniform int metallic_framerange = 0; +uniform int metallic_frameoffset = 0; +uniform int metallic_frameendaction = 0; +uniform vec2 metallic_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 metallic_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D roughness_file; +uniform int roughness_layer = 0; +uniform float roughness_default = 0.000000; +uniform int roughness_uaddressmode = 2; +uniform int roughness_vaddressmode = 2; +uniform int roughness_filtertype = 1; +uniform int roughness_framerange = 0; +uniform int roughness_frameoffset = 0; +uniform int roughness_frameendaction = 0; +uniform vec2 roughness_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 roughness_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D sss_file; +uniform int sss_layer = 0; +uniform float sss_default = 0.000000; +uniform int sss_uaddressmode = 2; +uniform int sss_vaddressmode = 2; +uniform int sss_filtertype = 1; +uniform int sss_framerange = 0; +uniform int sss_frameoffset = 0; +uniform int sss_frameendaction = 0; +uniform vec2 sss_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 sss_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D normal_file; +uniform int normal_layer = 0; +uniform vec3 normal_default = vec3(0.000000, 0.000000, 0.000000); +uniform int normal_uaddressmode = 2; +uniform int normal_vaddressmode = 2; +uniform int normal_filtertype = 1; +uniform int normal_framerange = 0; +uniform int normal_frameoffset = 0; +uniform int normal_frameendaction = 0; +uniform vec2 normal_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 normal_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap2_scale = 1.000000; +uniform float Queen_B_base = 1.000000; +uniform float Queen_B_diffuse_roughness = 0.000000; +uniform float Queen_B_specular = 1.000000; +uniform vec3 Queen_B_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Queen_B_specular_IOR = 1.500000; +uniform float Queen_B_specular_anisotropy = 0.000000; +uniform float Queen_B_specular_rotation = 0.000000; +uniform float Queen_B_transmission = 0.000000; +uniform vec3 Queen_B_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Queen_B_transmission_depth = 0.000000; +uniform vec3 Queen_B_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Queen_B_transmission_scatter_anisotropy = 0.000000; +uniform float Queen_B_transmission_dispersion = 0.000000; +uniform float Queen_B_transmission_extra_roughness = 0.000000; +uniform float Queen_B_subsurface_scale = 0.003000; +uniform float Queen_B_subsurface_anisotropy = 0.000000; +uniform float Queen_B_sheen = 0.000000; +uniform vec3 Queen_B_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Queen_B_sheen_roughness = 0.300000; +uniform float Queen_B_coat = 0.000000; +uniform vec3 Queen_B_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Queen_B_coat_roughness = 0.100000; +uniform float Queen_B_coat_anisotropy = 0.000000; +uniform float Queen_B_coat_rotation = 0.000000; +uniform float Queen_B_coat_IOR = 1.500000; +uniform float Queen_B_coat_affect_color = 0.000000; +uniform float Queen_B_coat_affect_roughness = 0.000000; +uniform float Queen_B_thin_film_thickness = 0.000000; +uniform float Queen_B_thin_film_IOR = 1.500000; +uniform float Queen_B_emission = 0.000000; +uniform vec3 Queen_B_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Queen_B_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Queen_B_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse_out = vec3(0.0); + mx_image_color3(diffuse_file, diffuse_layer, diffuse_default, geomprop_UV0_out1, diffuse_uaddressmode, diffuse_vaddressmode, diffuse_filtertype, diffuse_framerange, diffuse_frameoffset, diffuse_frameendaction, diffuse_uv_scale, diffuse_uv_offset, diffuse_out); + float metallic_out = 0.0; + mx_image_float(metallic_file, metallic_layer, metallic_default, geomprop_UV0_out1, metallic_uaddressmode, metallic_vaddressmode, metallic_filtertype, metallic_framerange, metallic_frameoffset, metallic_frameendaction, metallic_uv_scale, metallic_uv_offset, metallic_out); + float roughness_out = 0.0; + mx_image_float(roughness_file, roughness_layer, roughness_default, geomprop_UV0_out1, roughness_uaddressmode, roughness_vaddressmode, roughness_filtertype, roughness_framerange, roughness_frameoffset, roughness_frameendaction, roughness_uv_scale, roughness_uv_offset, roughness_out); + float sss_out = 0.0; + mx_image_float(sss_file, sss_layer, sss_default, geomprop_UV0_out1, sss_uaddressmode, sss_vaddressmode, sss_filtertype, sss_framerange, sss_frameoffset, sss_frameendaction, sss_uv_scale, sss_uv_offset, sss_out); + vec3 normal_out = vec3(0.0); + mx_image_vector3(normal_file, normal_layer, normal_default, geomprop_UV0_out1, normal_uaddressmode, normal_vaddressmode, normal_filtertype, normal_framerange, normal_frameoffset, normal_frameendaction, normal_uv_scale, normal_uv_offset, normal_out); + vec3 diffuse_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse_out, diffuse_out_cm_out); + vec3 mtlxnormalmap2_out = vec3(0.0); + mx_normalmap_float(normal_out, mtlxnormalmap2_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap2_out); + surfaceshader Queen_B_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Queen_B_base, diffuse_out_cm_out, Queen_B_diffuse_roughness, metallic_out, Queen_B_specular, Queen_B_specular_color, roughness_out, Queen_B_specular_IOR, Queen_B_specular_anisotropy, Queen_B_specular_rotation, Queen_B_transmission, Queen_B_transmission_color, Queen_B_transmission_depth, Queen_B_transmission_scatter, Queen_B_transmission_scatter_anisotropy, Queen_B_transmission_dispersion, Queen_B_transmission_extra_roughness, sss_out, diffuse_out_cm_out, diffuse_out_cm_out, Queen_B_subsurface_scale, Queen_B_subsurface_anisotropy, Queen_B_sheen, Queen_B_sheen_color, Queen_B_sheen_roughness, Queen_B_coat, Queen_B_coat_color, Queen_B_coat_roughness, Queen_B_coat_anisotropy, Queen_B_coat_rotation, Queen_B_coat_IOR, geomprop_Nworld_out1, Queen_B_coat_affect_color, Queen_B_coat_affect_roughness, Queen_B_thin_film_thickness, Queen_B_thin_film_IOR, Queen_B_emission, Queen_B_emission_color, Queen_B_opacity, Queen_B_thin_walled, mtlxnormalmap2_out, geomprop_Tworld_out1, Queen_B_out); + material M_Queen_B_out = Queen_B_out; + out1 = vec4(M_Queen_B_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Queen_B.glsl.vert b/Materials/Examples/StandardSurface/M_Queen_B.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Queen_B.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Queen_B.mdl b/Materials/Examples/StandardSurface/M_Queen_B.mdl new file mode 100644 index 0000000000..fb7ce307b9 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Queen_B.mdl @@ -0,0 +1,539 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Queen_B +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d diffuse_file = texture_2d("/chess_set/queen_black_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_QueenBlack/diffuse/file") + ]], + uniform string diffuse_layer = "" + [[ + materialx::core::origin("NG_QueenBlack/diffuse/layer") + ]], + color diffuse_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_QueenBlack/diffuse/default") + ]], + uniform mx_addressmode_type diffuse_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenBlack/diffuse/uaddressmode") + ]], + uniform mx_addressmode_type diffuse_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenBlack/diffuse/vaddressmode") + ]], + uniform mx_filterlookup_type diffuse_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_QueenBlack/diffuse/filtertype") + ]], + uniform string diffuse_framerange = "" + [[ + materialx::core::origin("NG_QueenBlack/diffuse/framerange") + ]], + uniform int diffuse_frameoffset = 0 + [[ + materialx::core::origin("NG_QueenBlack/diffuse/frameoffset") + ]], + uniform mx_addressmode_type diffuse_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_QueenBlack/diffuse/frameendaction") + ]], + uniform texture_2d metallic_file = texture_2d("/chess_set/queen_shared_metallic.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_QueenBlack/metallic/file") + ]], + uniform string metallic_layer = "" + [[ + materialx::core::origin("NG_QueenBlack/metallic/layer") + ]], + float metallic_default = 0.000000 + [[ + materialx::core::origin("NG_QueenBlack/metallic/default") + ]], + uniform mx_addressmode_type metallic_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenBlack/metallic/uaddressmode") + ]], + uniform mx_addressmode_type metallic_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenBlack/metallic/vaddressmode") + ]], + uniform mx_filterlookup_type metallic_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_QueenBlack/metallic/filtertype") + ]], + uniform string metallic_framerange = "" + [[ + materialx::core::origin("NG_QueenBlack/metallic/framerange") + ]], + uniform int metallic_frameoffset = 0 + [[ + materialx::core::origin("NG_QueenBlack/metallic/frameoffset") + ]], + uniform mx_addressmode_type metallic_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_QueenBlack/metallic/frameendaction") + ]], + uniform texture_2d roughness_file = texture_2d("/chess_set/queen_black_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_QueenBlack/roughness/file") + ]], + uniform string roughness_layer = "" + [[ + materialx::core::origin("NG_QueenBlack/roughness/layer") + ]], + float roughness_default = 0.000000 + [[ + materialx::core::origin("NG_QueenBlack/roughness/default") + ]], + uniform mx_addressmode_type roughness_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenBlack/roughness/uaddressmode") + ]], + uniform mx_addressmode_type roughness_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenBlack/roughness/vaddressmode") + ]], + uniform mx_filterlookup_type roughness_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_QueenBlack/roughness/filtertype") + ]], + uniform string roughness_framerange = "" + [[ + materialx::core::origin("NG_QueenBlack/roughness/framerange") + ]], + uniform int roughness_frameoffset = 0 + [[ + materialx::core::origin("NG_QueenBlack/roughness/frameoffset") + ]], + uniform mx_addressmode_type roughness_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_QueenBlack/roughness/frameendaction") + ]], + uniform texture_2d sss_file = texture_2d("/chess_set/queen_shared_scattering.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_QueenBlack/sss/file") + ]], + uniform string sss_layer = "" + [[ + materialx::core::origin("NG_QueenBlack/sss/layer") + ]], + float sss_default = 0.000000 + [[ + materialx::core::origin("NG_QueenBlack/sss/default") + ]], + uniform mx_addressmode_type sss_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenBlack/sss/uaddressmode") + ]], + uniform mx_addressmode_type sss_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenBlack/sss/vaddressmode") + ]], + uniform mx_filterlookup_type sss_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_QueenBlack/sss/filtertype") + ]], + uniform string sss_framerange = "" + [[ + materialx::core::origin("NG_QueenBlack/sss/framerange") + ]], + uniform int sss_frameoffset = 0 + [[ + materialx::core::origin("NG_QueenBlack/sss/frameoffset") + ]], + uniform mx_addressmode_type sss_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_QueenBlack/sss/frameendaction") + ]], + uniform texture_2d normal_file = texture_2d("/chess_set/queen_black_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_QueenBlack/normal/file") + ]], + uniform string normal_layer = "" + [[ + materialx::core::origin("NG_QueenBlack/normal/layer") + ]], + float3 normal_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_QueenBlack/normal/default") + ]], + uniform mx_addressmode_type normal_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenBlack/normal/uaddressmode") + ]], + uniform mx_addressmode_type normal_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenBlack/normal/vaddressmode") + ]], + uniform mx_filterlookup_type normal_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_QueenBlack/normal/filtertype") + ]], + uniform string normal_framerange = "" + [[ + materialx::core::origin("NG_QueenBlack/normal/framerange") + ]], + uniform int normal_frameoffset = 0 + [[ + materialx::core::origin("NG_QueenBlack/normal/frameoffset") + ]], + uniform mx_addressmode_type normal_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_QueenBlack/normal/frameendaction") + ]], + float mtlxnormalmap2_scale = 1.000000 + [[ + materialx::core::origin("NG_QueenBlack/mtlxnormalmap2/scale") + ]], + float Queen_B_base = 1.000000 + [[ + materialx::core::origin("Queen_B/base") + ]], + float Queen_B_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Queen_B/diffuse_roughness") + ]], + float Queen_B_specular = 1.000000 + [[ + materialx::core::origin("Queen_B/specular") + ]], + color Queen_B_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Queen_B/specular_color") + ]], + uniform float Queen_B_specular_IOR = 1.500000 + [[ + materialx::core::origin("Queen_B/specular_IOR") + ]], + float Queen_B_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Queen_B/specular_anisotropy") + ]], + float Queen_B_specular_rotation = 0.000000 + [[ + materialx::core::origin("Queen_B/specular_rotation") + ]], + float Queen_B_transmission = 0.000000 + [[ + materialx::core::origin("Queen_B/transmission") + ]], + color Queen_B_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Queen_B/transmission_color") + ]], + float Queen_B_transmission_depth = 0.000000 + [[ + materialx::core::origin("Queen_B/transmission_depth") + ]], + color Queen_B_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Queen_B/transmission_scatter") + ]], + float Queen_B_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Queen_B/transmission_scatter_anisotropy") + ]], + float Queen_B_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Queen_B/transmission_dispersion") + ]], + float Queen_B_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Queen_B/transmission_extra_roughness") + ]], + float Queen_B_subsurface_scale = 0.003000 + [[ + materialx::core::origin("Queen_B/subsurface_scale") + ]], + float Queen_B_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Queen_B/subsurface_anisotropy") + ]], + float Queen_B_sheen = 0.000000 + [[ + materialx::core::origin("Queen_B/sheen") + ]], + color Queen_B_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Queen_B/sheen_color") + ]], + float Queen_B_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Queen_B/sheen_roughness") + ]], + float Queen_B_coat = 0.000000 + [[ + materialx::core::origin("Queen_B/coat") + ]], + color Queen_B_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Queen_B/coat_color") + ]], + float Queen_B_coat_roughness = 0.100000 + [[ + materialx::core::origin("Queen_B/coat_roughness") + ]], + float Queen_B_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Queen_B/coat_anisotropy") + ]], + float Queen_B_coat_rotation = 0.000000 + [[ + materialx::core::origin("Queen_B/coat_rotation") + ]], + uniform float Queen_B_coat_IOR = 1.500000 + [[ + materialx::core::origin("Queen_B/coat_IOR") + ]], + float Queen_B_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Queen_B/coat_affect_color") + ]], + float Queen_B_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Queen_B/coat_affect_roughness") + ]], + float Queen_B_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Queen_B/thin_film_thickness") + ]], + float Queen_B_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Queen_B/thin_film_IOR") + ]], + float Queen_B_emission = 0.000000 + [[ + materialx::core::origin("Queen_B/emission") + ]], + color Queen_B_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Queen_B/emission_color") + ]], + color Queen_B_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Queen_B/opacity") + ]], + bool Queen_B_thin_walled = false + [[ + materialx::core::origin("Queen_B/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color diffuse_out = materialx::stdlib_1_8::mx_image_color3(diffuse_file, diffuse_layer, diffuse_default, geomprop_UV0_out1, diffuse_uaddressmode, diffuse_vaddressmode, diffuse_filtertype, diffuse_framerange, diffuse_frameoffset, diffuse_frameendaction, mxp_flip_v:false); + float metallic_out = materialx::stdlib_1_8::mx_image_float(metallic_file, metallic_layer, metallic_default, geomprop_UV0_out1, metallic_uaddressmode, metallic_vaddressmode, metallic_filtertype, metallic_framerange, metallic_frameoffset, metallic_frameendaction, mxp_flip_v:false); + float roughness_out = materialx::stdlib_1_8::mx_image_float(roughness_file, roughness_layer, roughness_default, geomprop_UV0_out1, roughness_uaddressmode, roughness_vaddressmode, roughness_filtertype, roughness_framerange, roughness_frameoffset, roughness_frameendaction, mxp_flip_v:false); + float sss_out = materialx::stdlib_1_8::mx_image_float(sss_file, sss_layer, sss_default, geomprop_UV0_out1, sss_uaddressmode, sss_vaddressmode, sss_filtertype, sss_framerange, sss_frameoffset, sss_frameendaction, mxp_flip_v:false); + float3 normal_out = materialx::stdlib_1_8::mx_image_vector3(normal_file, normal_layer, normal_default, geomprop_UV0_out1, normal_uaddressmode, normal_vaddressmode, normal_filtertype, normal_framerange, normal_frameoffset, normal_frameendaction, mxp_flip_v:false); + color diffuse_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(diffuse_out); + float3 mtlxnormalmap2_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:normal_out, mxp_scale:mtlxnormalmap2_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Queen_B_out = NG_standard_surface_surfaceshader_100(Queen_B_base, diffuse_out_cm_out, Queen_B_diffuse_roughness, metallic_out, Queen_B_specular, Queen_B_specular_color, roughness_out, Queen_B_specular_IOR, Queen_B_specular_anisotropy, Queen_B_specular_rotation, Queen_B_transmission, Queen_B_transmission_color, Queen_B_transmission_depth, Queen_B_transmission_scatter, Queen_B_transmission_scatter_anisotropy, Queen_B_transmission_dispersion, Queen_B_transmission_extra_roughness, sss_out, diffuse_out_cm_out, diffuse_out_cm_out, Queen_B_subsurface_scale, Queen_B_subsurface_anisotropy, Queen_B_sheen, Queen_B_sheen_color, Queen_B_sheen_roughness, Queen_B_coat, Queen_B_coat_color, Queen_B_coat_roughness, Queen_B_coat_anisotropy, Queen_B_coat_rotation, Queen_B_coat_IOR, geomprop_Nworld_out1, Queen_B_coat_affect_color, Queen_B_coat_affect_roughness, Queen_B_thin_film_thickness, Queen_B_thin_film_IOR, Queen_B_emission, Queen_B_emission_color, Queen_B_opacity, Queen_B_thin_walled, mtlxnormalmap2_out, geomprop_Tworld_out1); + material M_Queen_B_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Queen_B_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Queen_B_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Queen_B.msl.frag b/Materials/Examples/StandardSurface/M_Queen_B.msl.frag new file mode 100644 index 0000000000..bd889e6155 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Queen_B.msl.frag @@ -0,0 +1,3049 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int diffuse_layer; + vec3 diffuse_default; + int diffuse_uaddressmode; + int diffuse_vaddressmode; + int diffuse_filtertype; + int diffuse_framerange; + int diffuse_frameoffset; + int diffuse_frameendaction; + vec2 diffuse_uv_scale; + vec2 diffuse_uv_offset; + int metallic_layer; + float metallic_default; + int metallic_uaddressmode; + int metallic_vaddressmode; + int metallic_filtertype; + int metallic_framerange; + int metallic_frameoffset; + int metallic_frameendaction; + vec2 metallic_uv_scale; + vec2 metallic_uv_offset; + int roughness_layer; + float roughness_default; + int roughness_uaddressmode; + int roughness_vaddressmode; + int roughness_filtertype; + int roughness_framerange; + int roughness_frameoffset; + int roughness_frameendaction; + vec2 roughness_uv_scale; + vec2 roughness_uv_offset; + int sss_layer; + float sss_default; + int sss_uaddressmode; + int sss_vaddressmode; + int sss_filtertype; + int sss_framerange; + int sss_frameoffset; + int sss_frameendaction; + vec2 sss_uv_scale; + vec2 sss_uv_offset; + int normal_layer; + vec3 normal_default; + int normal_uaddressmode; + int normal_vaddressmode; + int normal_filtertype; + int normal_framerange; + int normal_frameoffset; + int normal_frameendaction; + vec2 normal_uv_scale; + vec2 normal_uv_offset; + float mtlxnormalmap2_scale; + float Queen_B_base; + float Queen_B_diffuse_roughness; + float Queen_B_specular; + vec3 Queen_B_specular_color; + float Queen_B_specular_IOR; + float Queen_B_specular_anisotropy; + float Queen_B_specular_rotation; + float Queen_B_transmission; + vec3 Queen_B_transmission_color; + float Queen_B_transmission_depth; + vec3 Queen_B_transmission_scatter; + float Queen_B_transmission_scatter_anisotropy; + float Queen_B_transmission_dispersion; + float Queen_B_transmission_extra_roughness; + float Queen_B_subsurface_scale; + float Queen_B_subsurface_anisotropy; + float Queen_B_sheen; + vec3 Queen_B_sheen_color; + float Queen_B_sheen_roughness; + float Queen_B_coat; + vec3 Queen_B_coat_color; + float Queen_B_coat_roughness; + float Queen_B_coat_anisotropy; + float Queen_B_coat_rotation; + float Queen_B_coat_IOR; + float Queen_B_coat_affect_color; + float Queen_B_coat_affect_roughness; + float Queen_B_thin_film_thickness; + float Queen_B_thin_film_IOR; + float Queen_B_emission; + vec3 Queen_B_emission_color; + vec3 Queen_B_opacity; + bool Queen_B_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture diffuse_file , int diffuse_layer + + , vec3 diffuse_default + + , int diffuse_uaddressmode + + , int diffuse_vaddressmode + + , int diffuse_filtertype + + , int diffuse_framerange + + , int diffuse_frameoffset + + , int diffuse_frameendaction + + , vec2 diffuse_uv_scale + + , vec2 diffuse_uv_offset + +, MetalTexture metallic_file , int metallic_layer + + , float metallic_default + + , int metallic_uaddressmode + + , int metallic_vaddressmode + + , int metallic_filtertype + + , int metallic_framerange + + , int metallic_frameoffset + + , int metallic_frameendaction + + , vec2 metallic_uv_scale + + , vec2 metallic_uv_offset + +, MetalTexture roughness_file , int roughness_layer + + , float roughness_default + + , int roughness_uaddressmode + + , int roughness_vaddressmode + + , int roughness_filtertype + + , int roughness_framerange + + , int roughness_frameoffset + + , int roughness_frameendaction + + , vec2 roughness_uv_scale + + , vec2 roughness_uv_offset + +, MetalTexture sss_file , int sss_layer + + , float sss_default + + , int sss_uaddressmode + + , int sss_vaddressmode + + , int sss_filtertype + + , int sss_framerange + + , int sss_frameoffset + + , int sss_frameendaction + + , vec2 sss_uv_scale + + , vec2 sss_uv_offset + +, MetalTexture normal_file , int normal_layer + + , vec3 normal_default + + , int normal_uaddressmode + + , int normal_vaddressmode + + , int normal_filtertype + + , int normal_framerange + + , int normal_frameoffset + + , int normal_frameendaction + + , vec2 normal_uv_scale + + , vec2 normal_uv_offset + + , float mtlxnormalmap2_scale + + , float Queen_B_base + + , float Queen_B_diffuse_roughness + + , float Queen_B_specular + + , vec3 Queen_B_specular_color + + , float Queen_B_specular_IOR + + , float Queen_B_specular_anisotropy + + , float Queen_B_specular_rotation + + , float Queen_B_transmission + + , vec3 Queen_B_transmission_color + + , float Queen_B_transmission_depth + + , vec3 Queen_B_transmission_scatter + + , float Queen_B_transmission_scatter_anisotropy + + , float Queen_B_transmission_dispersion + + , float Queen_B_transmission_extra_roughness + + , float Queen_B_subsurface_scale + + , float Queen_B_subsurface_anisotropy + + , float Queen_B_sheen + + , vec3 Queen_B_sheen_color + + , float Queen_B_sheen_roughness + + , float Queen_B_coat + + , vec3 Queen_B_coat_color + + , float Queen_B_coat_roughness + + , float Queen_B_coat_anisotropy + + , float Queen_B_coat_rotation + + , float Queen_B_coat_IOR + + , float Queen_B_coat_affect_color + + , float Queen_B_coat_affect_roughness + + , float Queen_B_thin_film_thickness + + , float Queen_B_thin_film_IOR + + , float Queen_B_emission + + , vec3 Queen_B_emission_color + + , vec3 Queen_B_opacity + + , bool Queen_B_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, diffuse_file(diffuse_file) + , diffuse_layer(diffuse_layer) + + , diffuse_default(diffuse_default) + + , diffuse_uaddressmode(diffuse_uaddressmode) + + , diffuse_vaddressmode(diffuse_vaddressmode) + + , diffuse_filtertype(diffuse_filtertype) + + , diffuse_framerange(diffuse_framerange) + + , diffuse_frameoffset(diffuse_frameoffset) + + , diffuse_frameendaction(diffuse_frameendaction) + + , diffuse_uv_scale(diffuse_uv_scale) + + , diffuse_uv_offset(diffuse_uv_offset) + +, metallic_file(metallic_file) + , metallic_layer(metallic_layer) + + , metallic_default(metallic_default) + + , metallic_uaddressmode(metallic_uaddressmode) + + , metallic_vaddressmode(metallic_vaddressmode) + + , metallic_filtertype(metallic_filtertype) + + , metallic_framerange(metallic_framerange) + + , metallic_frameoffset(metallic_frameoffset) + + , metallic_frameendaction(metallic_frameendaction) + + , metallic_uv_scale(metallic_uv_scale) + + , metallic_uv_offset(metallic_uv_offset) + +, roughness_file(roughness_file) + , roughness_layer(roughness_layer) + + , roughness_default(roughness_default) + + , roughness_uaddressmode(roughness_uaddressmode) + + , roughness_vaddressmode(roughness_vaddressmode) + + , roughness_filtertype(roughness_filtertype) + + , roughness_framerange(roughness_framerange) + + , roughness_frameoffset(roughness_frameoffset) + + , roughness_frameendaction(roughness_frameendaction) + + , roughness_uv_scale(roughness_uv_scale) + + , roughness_uv_offset(roughness_uv_offset) + +, sss_file(sss_file) + , sss_layer(sss_layer) + + , sss_default(sss_default) + + , sss_uaddressmode(sss_uaddressmode) + + , sss_vaddressmode(sss_vaddressmode) + + , sss_filtertype(sss_filtertype) + + , sss_framerange(sss_framerange) + + , sss_frameoffset(sss_frameoffset) + + , sss_frameendaction(sss_frameendaction) + + , sss_uv_scale(sss_uv_scale) + + , sss_uv_offset(sss_uv_offset) + +, normal_file(normal_file) + , normal_layer(normal_layer) + + , normal_default(normal_default) + + , normal_uaddressmode(normal_uaddressmode) + + , normal_vaddressmode(normal_vaddressmode) + + , normal_filtertype(normal_filtertype) + + , normal_framerange(normal_framerange) + + , normal_frameoffset(normal_frameoffset) + + , normal_frameendaction(normal_frameendaction) + + , normal_uv_scale(normal_uv_scale) + + , normal_uv_offset(normal_uv_offset) + + , mtlxnormalmap2_scale(mtlxnormalmap2_scale) + + , Queen_B_base(Queen_B_base) + + , Queen_B_diffuse_roughness(Queen_B_diffuse_roughness) + + , Queen_B_specular(Queen_B_specular) + + , Queen_B_specular_color(Queen_B_specular_color) + + , Queen_B_specular_IOR(Queen_B_specular_IOR) + + , Queen_B_specular_anisotropy(Queen_B_specular_anisotropy) + + , Queen_B_specular_rotation(Queen_B_specular_rotation) + + , Queen_B_transmission(Queen_B_transmission) + + , Queen_B_transmission_color(Queen_B_transmission_color) + + , Queen_B_transmission_depth(Queen_B_transmission_depth) + + , Queen_B_transmission_scatter(Queen_B_transmission_scatter) + + , Queen_B_transmission_scatter_anisotropy(Queen_B_transmission_scatter_anisotropy) + + , Queen_B_transmission_dispersion(Queen_B_transmission_dispersion) + + , Queen_B_transmission_extra_roughness(Queen_B_transmission_extra_roughness) + + , Queen_B_subsurface_scale(Queen_B_subsurface_scale) + + , Queen_B_subsurface_anisotropy(Queen_B_subsurface_anisotropy) + + , Queen_B_sheen(Queen_B_sheen) + + , Queen_B_sheen_color(Queen_B_sheen_color) + + , Queen_B_sheen_roughness(Queen_B_sheen_roughness) + + , Queen_B_coat(Queen_B_coat) + + , Queen_B_coat_color(Queen_B_coat_color) + + , Queen_B_coat_roughness(Queen_B_coat_roughness) + + , Queen_B_coat_anisotropy(Queen_B_coat_anisotropy) + + , Queen_B_coat_rotation(Queen_B_coat_rotation) + + , Queen_B_coat_IOR(Queen_B_coat_IOR) + + , Queen_B_coat_affect_color(Queen_B_coat_affect_color) + + , Queen_B_coat_affect_roughness(Queen_B_coat_affect_roughness) + + , Queen_B_thin_film_thickness(Queen_B_thin_film_thickness) + + , Queen_B_thin_film_IOR(Queen_B_thin_film_IOR) + + , Queen_B_emission(Queen_B_emission) + + , Queen_B_emission_color(Queen_B_emission_color) + + , Queen_B_opacity(Queen_B_opacity) + + , Queen_B_thin_walled(Queen_B_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture diffuse_file; + int diffuse_layer; + + + vec3 diffuse_default; + + + int diffuse_uaddressmode; + + + int diffuse_vaddressmode; + + + int diffuse_filtertype; + + + int diffuse_framerange; + + + int diffuse_frameoffset; + + + int diffuse_frameendaction; + + + vec2 diffuse_uv_scale; + + + vec2 diffuse_uv_offset; + + +MetalTexture metallic_file; + int metallic_layer; + + + float metallic_default; + + + int metallic_uaddressmode; + + + int metallic_vaddressmode; + + + int metallic_filtertype; + + + int metallic_framerange; + + + int metallic_frameoffset; + + + int metallic_frameendaction; + + + vec2 metallic_uv_scale; + + + vec2 metallic_uv_offset; + + +MetalTexture roughness_file; + int roughness_layer; + + + float roughness_default; + + + int roughness_uaddressmode; + + + int roughness_vaddressmode; + + + int roughness_filtertype; + + + int roughness_framerange; + + + int roughness_frameoffset; + + + int roughness_frameendaction; + + + vec2 roughness_uv_scale; + + + vec2 roughness_uv_offset; + + +MetalTexture sss_file; + int sss_layer; + + + float sss_default; + + + int sss_uaddressmode; + + + int sss_vaddressmode; + + + int sss_filtertype; + + + int sss_framerange; + + + int sss_frameoffset; + + + int sss_frameendaction; + + + vec2 sss_uv_scale; + + + vec2 sss_uv_offset; + + +MetalTexture normal_file; + int normal_layer; + + + vec3 normal_default; + + + int normal_uaddressmode; + + + int normal_vaddressmode; + + + int normal_filtertype; + + + int normal_framerange; + + + int normal_frameoffset; + + + int normal_frameendaction; + + + vec2 normal_uv_scale; + + + vec2 normal_uv_offset; + + + float mtlxnormalmap2_scale; + + + float Queen_B_base; + + + float Queen_B_diffuse_roughness; + + + float Queen_B_specular; + + + vec3 Queen_B_specular_color; + + + float Queen_B_specular_IOR; + + + float Queen_B_specular_anisotropy; + + + float Queen_B_specular_rotation; + + + float Queen_B_transmission; + + + vec3 Queen_B_transmission_color; + + + float Queen_B_transmission_depth; + + + vec3 Queen_B_transmission_scatter; + + + float Queen_B_transmission_scatter_anisotropy; + + + float Queen_B_transmission_dispersion; + + + float Queen_B_transmission_extra_roughness; + + + float Queen_B_subsurface_scale; + + + float Queen_B_subsurface_anisotropy; + + + float Queen_B_sheen; + + + vec3 Queen_B_sheen_color; + + + float Queen_B_sheen_roughness; + + + float Queen_B_coat; + + + vec3 Queen_B_coat_color; + + + float Queen_B_coat_roughness; + + + float Queen_B_coat_anisotropy; + + + float Queen_B_coat_rotation; + + + float Queen_B_coat_IOR; + + + float Queen_B_coat_affect_color; + + + float Queen_B_coat_affect_roughness; + + + float Queen_B_thin_film_thickness; + + + float Queen_B_thin_film_IOR; + + + float Queen_B_emission; + + + vec3 Queen_B_emission_color; + + + vec3 Queen_B_opacity; + + + bool Queen_B_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse_out = vec3(0.0); + mx_image_color3(diffuse_file, diffuse_layer, diffuse_default, geomprop_UV0_out1, diffuse_uaddressmode, diffuse_vaddressmode, diffuse_filtertype, diffuse_framerange, diffuse_frameoffset, diffuse_frameendaction, diffuse_uv_scale, diffuse_uv_offset, diffuse_out); + float metallic_out = 0.0; + mx_image_float(metallic_file, metallic_layer, metallic_default, geomprop_UV0_out1, metallic_uaddressmode, metallic_vaddressmode, metallic_filtertype, metallic_framerange, metallic_frameoffset, metallic_frameendaction, metallic_uv_scale, metallic_uv_offset, metallic_out); + float roughness_out = 0.0; + mx_image_float(roughness_file, roughness_layer, roughness_default, geomprop_UV0_out1, roughness_uaddressmode, roughness_vaddressmode, roughness_filtertype, roughness_framerange, roughness_frameoffset, roughness_frameendaction, roughness_uv_scale, roughness_uv_offset, roughness_out); + float sss_out = 0.0; + mx_image_float(sss_file, sss_layer, sss_default, geomprop_UV0_out1, sss_uaddressmode, sss_vaddressmode, sss_filtertype, sss_framerange, sss_frameoffset, sss_frameendaction, sss_uv_scale, sss_uv_offset, sss_out); + vec3 normal_out = vec3(0.0); + mx_image_vector3(normal_file, normal_layer, normal_default, geomprop_UV0_out1, normal_uaddressmode, normal_vaddressmode, normal_filtertype, normal_framerange, normal_frameoffset, normal_frameendaction, normal_uv_scale, normal_uv_offset, normal_out); + vec3 diffuse_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse_out, diffuse_out_cm_out); + vec3 mtlxnormalmap2_out = vec3(0.0); + mx_normalmap_float(normal_out, mtlxnormalmap2_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap2_out); + surfaceshader Queen_B_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Queen_B_base, diffuse_out_cm_out, Queen_B_diffuse_roughness, metallic_out, Queen_B_specular, Queen_B_specular_color, roughness_out, Queen_B_specular_IOR, Queen_B_specular_anisotropy, Queen_B_specular_rotation, Queen_B_transmission, Queen_B_transmission_color, Queen_B_transmission_depth, Queen_B_transmission_scatter, Queen_B_transmission_scatter_anisotropy, Queen_B_transmission_dispersion, Queen_B_transmission_extra_roughness, sss_out, diffuse_out_cm_out, diffuse_out_cm_out, Queen_B_subsurface_scale, Queen_B_subsurface_anisotropy, Queen_B_sheen, Queen_B_sheen_color, Queen_B_sheen_roughness, Queen_B_coat, Queen_B_coat_color, Queen_B_coat_roughness, Queen_B_coat_anisotropy, Queen_B_coat_rotation, Queen_B_coat_IOR, geomprop_Nworld_out1, Queen_B_coat_affect_color, Queen_B_coat_affect_roughness, Queen_B_thin_film_thickness, Queen_B_thin_film_IOR, Queen_B_emission, Queen_B_emission_color, Queen_B_opacity, Queen_B_thin_walled, mtlxnormalmap2_out, geomprop_Tworld_out1, Queen_B_out); + material M_Queen_B_out = Queen_B_out; + out1 = float4(M_Queen_B_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d diffuse_file_tex [[texture(0)]], sampler diffuse_file_sampler [[sampler(0)]] +, texture2d metallic_file_tex [[texture(1)]], sampler metallic_file_sampler [[sampler(1)]] +, texture2d roughness_file_tex [[texture(2)]], sampler roughness_file_sampler [[sampler(2)]] +, texture2d sss_file_tex [[texture(3)]], sampler sss_file_sampler [[sampler(3)]] +, texture2d normal_file_tex [[texture(4)]], sampler normal_file_sampler [[sampler(4)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(5)]], sampler u_envRadiance_sampler [[sampler(5)]] +, texture2d u_envIrradiance_tex [[texture(6)]], sampler u_envIrradiance_sampler [[sampler(6)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +diffuse_file_tex, diffuse_file_sampler } + , u_pub.diffuse_layer + , u_pub.diffuse_default + , u_pub.diffuse_uaddressmode + , u_pub.diffuse_vaddressmode + , u_pub.diffuse_filtertype + , u_pub.diffuse_framerange + , u_pub.diffuse_frameoffset + , u_pub.diffuse_frameendaction + , u_pub.diffuse_uv_scale + , u_pub.diffuse_uv_offset +, MetalTexture { +metallic_file_tex, metallic_file_sampler } + , u_pub.metallic_layer + , u_pub.metallic_default + , u_pub.metallic_uaddressmode + , u_pub.metallic_vaddressmode + , u_pub.metallic_filtertype + , u_pub.metallic_framerange + , u_pub.metallic_frameoffset + , u_pub.metallic_frameendaction + , u_pub.metallic_uv_scale + , u_pub.metallic_uv_offset +, MetalTexture { +roughness_file_tex, roughness_file_sampler } + , u_pub.roughness_layer + , u_pub.roughness_default + , u_pub.roughness_uaddressmode + , u_pub.roughness_vaddressmode + , u_pub.roughness_filtertype + , u_pub.roughness_framerange + , u_pub.roughness_frameoffset + , u_pub.roughness_frameendaction + , u_pub.roughness_uv_scale + , u_pub.roughness_uv_offset +, MetalTexture { +sss_file_tex, sss_file_sampler } + , u_pub.sss_layer + , u_pub.sss_default + , u_pub.sss_uaddressmode + , u_pub.sss_vaddressmode + , u_pub.sss_filtertype + , u_pub.sss_framerange + , u_pub.sss_frameoffset + , u_pub.sss_frameendaction + , u_pub.sss_uv_scale + , u_pub.sss_uv_offset +, MetalTexture { +normal_file_tex, normal_file_sampler } + , u_pub.normal_layer + , u_pub.normal_default + , u_pub.normal_uaddressmode + , u_pub.normal_vaddressmode + , u_pub.normal_filtertype + , u_pub.normal_framerange + , u_pub.normal_frameoffset + , u_pub.normal_frameendaction + , u_pub.normal_uv_scale + , u_pub.normal_uv_offset + , u_pub.mtlxnormalmap2_scale + , u_pub.Queen_B_base + , u_pub.Queen_B_diffuse_roughness + , u_pub.Queen_B_specular + , u_pub.Queen_B_specular_color + , u_pub.Queen_B_specular_IOR + , u_pub.Queen_B_specular_anisotropy + , u_pub.Queen_B_specular_rotation + , u_pub.Queen_B_transmission + , u_pub.Queen_B_transmission_color + , u_pub.Queen_B_transmission_depth + , u_pub.Queen_B_transmission_scatter + , u_pub.Queen_B_transmission_scatter_anisotropy + , u_pub.Queen_B_transmission_dispersion + , u_pub.Queen_B_transmission_extra_roughness + , u_pub.Queen_B_subsurface_scale + , u_pub.Queen_B_subsurface_anisotropy + , u_pub.Queen_B_sheen + , u_pub.Queen_B_sheen_color + , u_pub.Queen_B_sheen_roughness + , u_pub.Queen_B_coat + , u_pub.Queen_B_coat_color + , u_pub.Queen_B_coat_roughness + , u_pub.Queen_B_coat_anisotropy + , u_pub.Queen_B_coat_rotation + , u_pub.Queen_B_coat_IOR + , u_pub.Queen_B_coat_affect_color + , u_pub.Queen_B_coat_affect_roughness + , u_pub.Queen_B_thin_film_thickness + , u_pub.Queen_B_thin_film_IOR + , u_pub.Queen_B_emission + , u_pub.Queen_B_emission_color + , u_pub.Queen_B_opacity + , u_pub.Queen_B_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Queen_B.msl.vert b/Materials/Examples/StandardSurface/M_Queen_B.msl.vert new file mode 100644 index 0000000000..99743b18ee --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Queen_B.msl.vert @@ -0,0 +1,128 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'diffuse'. Function already called in this scope. + // Omitted node 'metallic'. Function already called in this scope. + // Omitted node 'roughness'. Function already called in this scope. + // Omitted node 'sss'. Function already called in this scope. + // Omitted node 'normal'. Function already called in this scope. + // Omitted node 'diffuse_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap2'. Function already called in this scope. + // Omitted node 'Queen_B'. Function already called in this scope. + // Omitted node 'M_Queen_B'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Queen_B.osl b/Materials/Examples/StandardSurface/M_Queen_B.osl new file mode 100644 index 0000000000..642a31f400 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Queen_B.osl @@ -0,0 +1,699 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Queen_B +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Queen_B" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string diffuse_file = "chess_set/queen_black_base_color.jpg" + [[ + string widget = "filename" + ]], + string diffuse_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string diffuse_layer = "", + color diffuse_default = color(0.000000, 0.000000, 0.000000), + string diffuse_uaddressmode = "periodic", + string diffuse_vaddressmode = "periodic", + string diffuse_filtertype = "linear", + string diffuse_framerange = "", + int diffuse_frameoffset = 0 + [[ + string widget = "number" + ]], + string diffuse_frameendaction = "constant", + string metallic_file = "chess_set/queen_shared_metallic.jpg" + [[ + string widget = "filename" + ]], + string metallic_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string metallic_layer = "", + float metallic_default = 0.000000 + [[ + string widget = "number" + ]], + string metallic_uaddressmode = "periodic", + string metallic_vaddressmode = "periodic", + string metallic_filtertype = "linear", + string metallic_framerange = "", + int metallic_frameoffset = 0 + [[ + string widget = "number" + ]], + string metallic_frameendaction = "constant", + string roughness_file = "chess_set/queen_black_roughness.jpg" + [[ + string widget = "filename" + ]], + string roughness_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string roughness_layer = "", + float roughness_default = 0.000000 + [[ + string widget = "number" + ]], + string roughness_uaddressmode = "periodic", + string roughness_vaddressmode = "periodic", + string roughness_filtertype = "linear", + string roughness_framerange = "", + int roughness_frameoffset = 0 + [[ + string widget = "number" + ]], + string roughness_frameendaction = "constant", + string sss_file = "chess_set/queen_shared_scattering.jpg" + [[ + string widget = "filename" + ]], + string sss_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string sss_layer = "", + float sss_default = 0.000000 + [[ + string widget = "number" + ]], + string sss_uaddressmode = "periodic", + string sss_vaddressmode = "periodic", + string sss_filtertype = "linear", + string sss_framerange = "", + int sss_frameoffset = 0 + [[ + string widget = "number" + ]], + string sss_frameendaction = "constant", + string normal_file = "chess_set/queen_black_normal.jpg" + [[ + string widget = "filename" + ]], + string normal_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string normal_layer = "", + vector normal_default = vector(0.000000, 0.000000, 0.000000), + string normal_uaddressmode = "periodic", + string normal_vaddressmode = "periodic", + string normal_filtertype = "linear", + string normal_framerange = "", + int normal_frameoffset = 0 + [[ + string widget = "number" + ]], + string normal_frameendaction = "constant", + float mtlxnormalmap2_scale = 1.000000 + [[ + string widget = "number" + ]], + float Queen_B_base = 1.000000 + [[ + string widget = "number" + ]], + float Queen_B_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Queen_B_specular = 1.000000 + [[ + string widget = "number" + ]], + color Queen_B_specular_color = color(1.000000, 1.000000, 1.000000), + float Queen_B_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Queen_B_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Queen_B_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Queen_B_transmission = 0.000000 + [[ + string widget = "number" + ]], + color Queen_B_transmission_color = color(1.000000, 1.000000, 1.000000), + float Queen_B_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Queen_B_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Queen_B_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Queen_B_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Queen_B_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Queen_B_subsurface_scale = 0.003000 + [[ + string widget = "number" + ]], + float Queen_B_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Queen_B_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Queen_B_sheen_color = color(1.000000, 1.000000, 1.000000), + float Queen_B_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Queen_B_coat = 0.000000 + [[ + string widget = "number" + ]], + color Queen_B_coat_color = color(1.000000, 1.000000, 1.000000), + float Queen_B_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Queen_B_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Queen_B_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Queen_B_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Queen_B_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Queen_B_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Queen_B_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Queen_B_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Queen_B_emission = 0.000000 + [[ + string widget = "number" + ]], + color Queen_B_emission_color = color(1.000000, 1.000000, 1.000000), + color Queen_B_opacity = color(1.000000, 1.000000, 1.000000), + int Queen_B_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource diffuse_file_ = {diffuse_file, diffuse_file_colorspace}; + textureresource metallic_file_ = {metallic_file, metallic_file_colorspace}; + textureresource roughness_file_ = {roughness_file, roughness_file_colorspace}; + textureresource sss_file_ = {sss_file, sss_file_colorspace}; + textureresource normal_file_ = {normal_file, normal_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color diffuse_out = color(0.0); + mx_image_color3(diffuse_file_, diffuse_layer, diffuse_default, geomprop_UV0_out1, diffuse_uaddressmode, diffuse_vaddressmode, diffuse_filtertype, diffuse_framerange, diffuse_frameoffset, diffuse_frameendaction, diffuse_out); + float metallic_out = 0.0; + mx_image_float(metallic_file_, metallic_layer, metallic_default, geomprop_UV0_out1, metallic_uaddressmode, metallic_vaddressmode, metallic_filtertype, metallic_framerange, metallic_frameoffset, metallic_frameendaction, metallic_out); + float roughness_out = 0.0; + mx_image_float(roughness_file_, roughness_layer, roughness_default, geomprop_UV0_out1, roughness_uaddressmode, roughness_vaddressmode, roughness_filtertype, roughness_framerange, roughness_frameoffset, roughness_frameendaction, roughness_out); + float sss_out = 0.0; + mx_image_float(sss_file_, sss_layer, sss_default, geomprop_UV0_out1, sss_uaddressmode, sss_vaddressmode, sss_filtertype, sss_framerange, sss_frameoffset, sss_frameendaction, sss_out); + vector normal_out = vector(0.0); + mx_image_vector3(normal_file_, normal_layer, normal_default, geomprop_UV0_out1, normal_uaddressmode, normal_vaddressmode, normal_filtertype, normal_framerange, normal_frameoffset, normal_frameendaction, normal_out); + color diffuse_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse_out, diffuse_out_cm_out); + vector mtlxnormalmap2_out = vector(0.0); + mx_normalmap_float(normal_out, mtlxnormalmap2_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap2_out); + surfaceshader Queen_B_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Queen_B_base, diffuse_out_cm_out, Queen_B_diffuse_roughness, metallic_out, Queen_B_specular, Queen_B_specular_color, roughness_out, Queen_B_specular_IOR, Queen_B_specular_anisotropy, Queen_B_specular_rotation, Queen_B_transmission, Queen_B_transmission_color, Queen_B_transmission_depth, Queen_B_transmission_scatter, Queen_B_transmission_scatter_anisotropy, Queen_B_transmission_dispersion, Queen_B_transmission_extra_roughness, sss_out, diffuse_out_cm_out, diffuse_out_cm_out, Queen_B_subsurface_scale, Queen_B_subsurface_anisotropy, Queen_B_sheen, Queen_B_sheen_color, Queen_B_sheen_roughness, Queen_B_coat, Queen_B_coat_color, Queen_B_coat_roughness, Queen_B_coat_anisotropy, Queen_B_coat_rotation, Queen_B_coat_IOR, geomprop_Nworld_out1, Queen_B_coat_affect_color, Queen_B_coat_affect_roughness, Queen_B_thin_film_thickness, Queen_B_thin_film_IOR, Queen_B_emission, Queen_B_emission_color, Queen_B_opacity, Queen_B_thin_walled, mtlxnormalmap2_out, geomprop_Tworld_out1, Queen_B_out); + MATERIAL M_Queen_B_out = mx_surfacematerial(Queen_B_out, backsurfaceshader, displacementshader1); + out = M_Queen_B_out; +} + diff --git a/Materials/Examples/StandardSurface/M_Queen_W.glsl.frag b/Materials/Examples/StandardSurface/M_Queen_W.glsl.frag new file mode 100644 index 0000000000..1f28699c51 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Queen_W.glsl.frag @@ -0,0 +1,2025 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D diffuse1_file; +uniform int diffuse1_layer = 0; +uniform vec3 diffuse1_default = vec3(0.000000, 0.000000, 0.000000); +uniform int diffuse1_uaddressmode = 2; +uniform int diffuse1_vaddressmode = 2; +uniform int diffuse1_filtertype = 1; +uniform int diffuse1_framerange = 0; +uniform int diffuse1_frameoffset = 0; +uniform int diffuse1_frameendaction = 0; +uniform vec2 diffuse1_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 diffuse1_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D metallic1_file; +uniform int metallic1_layer = 0; +uniform float metallic1_default = 0.000000; +uniform int metallic1_uaddressmode = 2; +uniform int metallic1_vaddressmode = 2; +uniform int metallic1_filtertype = 1; +uniform int metallic1_framerange = 0; +uniform int metallic1_frameoffset = 0; +uniform int metallic1_frameendaction = 0; +uniform vec2 metallic1_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 metallic1_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D roughness1_file; +uniform int roughness1_layer = 0; +uniform float roughness1_default = 0.000000; +uniform int roughness1_uaddressmode = 2; +uniform int roughness1_vaddressmode = 2; +uniform int roughness1_filtertype = 1; +uniform int roughness1_framerange = 0; +uniform int roughness1_frameoffset = 0; +uniform int roughness1_frameendaction = 0; +uniform vec2 roughness1_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 roughness1_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D sss1_file; +uniform int sss1_layer = 0; +uniform float sss1_default = 0.000000; +uniform int sss1_uaddressmode = 2; +uniform int sss1_vaddressmode = 2; +uniform int sss1_filtertype = 1; +uniform int sss1_framerange = 0; +uniform int sss1_frameoffset = 0; +uniform int sss1_frameendaction = 0; +uniform vec2 sss1_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 sss1_uv_offset = vec2(0.000000, 0.000000); +uniform sampler2D normal1_file; +uniform int normal1_layer = 0; +uniform vec3 normal1_default = vec3(0.000000, 0.000000, 0.000000); +uniform int normal1_uaddressmode = 2; +uniform int normal1_vaddressmode = 2; +uniform int normal1_filtertype = 1; +uniform int normal1_framerange = 0; +uniform int normal1_frameoffset = 0; +uniform int normal1_frameendaction = 0; +uniform vec2 normal1_uv_scale = vec2(1.000000, 1.000000); +uniform vec2 normal1_uv_offset = vec2(0.000000, 0.000000); +uniform float mtlxnormalmap3_scale = 1.000000; +uniform float Queen_W_base = 1.000000; +uniform float Queen_W_diffuse_roughness = 0.000000; +uniform float Queen_W_specular = 1.000000; +uniform vec3 Queen_W_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Queen_W_specular_IOR = 1.500000; +uniform float Queen_W_specular_anisotropy = 0.000000; +uniform float Queen_W_specular_rotation = 0.000000; +uniform float Queen_W_transmission = 0.000000; +uniform vec3 Queen_W_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Queen_W_transmission_depth = 0.000000; +uniform vec3 Queen_W_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float Queen_W_transmission_scatter_anisotropy = 0.000000; +uniform float Queen_W_transmission_dispersion = 0.000000; +uniform float Queen_W_transmission_extra_roughness = 0.000000; +uniform float Queen_W_subsurface_scale = 0.001000; +uniform float Queen_W_subsurface_anisotropy = 0.000000; +uniform float Queen_W_sheen = 0.000000; +uniform vec3 Queen_W_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Queen_W_sheen_roughness = 0.300000; +uniform float Queen_W_coat = 0.000000; +uniform vec3 Queen_W_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float Queen_W_coat_roughness = 0.100000; +uniform float Queen_W_coat_anisotropy = 0.000000; +uniform float Queen_W_coat_rotation = 0.000000; +uniform float Queen_W_coat_IOR = 1.500000; +uniform float Queen_W_coat_affect_color = 0.000000; +uniform float Queen_W_coat_affect_roughness = 0.000000; +uniform float Queen_W_thin_film_thickness = 0.000000; +uniform float Queen_W_thin_film_IOR = 1.500000; +uniform float Queen_W_emission = 0.000000; +uniform vec3 Queen_W_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 Queen_W_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool Queen_W_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + + +void mx_image_vector3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); +} + +void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, out vec3 result) +{ + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse1_out = vec3(0.0); + mx_image_color3(diffuse1_file, diffuse1_layer, diffuse1_default, geomprop_UV0_out1, diffuse1_uaddressmode, diffuse1_vaddressmode, diffuse1_filtertype, diffuse1_framerange, diffuse1_frameoffset, diffuse1_frameendaction, diffuse1_uv_scale, diffuse1_uv_offset, diffuse1_out); + float metallic1_out = 0.0; + mx_image_float(metallic1_file, metallic1_layer, metallic1_default, geomprop_UV0_out1, metallic1_uaddressmode, metallic1_vaddressmode, metallic1_filtertype, metallic1_framerange, metallic1_frameoffset, metallic1_frameendaction, metallic1_uv_scale, metallic1_uv_offset, metallic1_out); + float roughness1_out = 0.0; + mx_image_float(roughness1_file, roughness1_layer, roughness1_default, geomprop_UV0_out1, roughness1_uaddressmode, roughness1_vaddressmode, roughness1_filtertype, roughness1_framerange, roughness1_frameoffset, roughness1_frameendaction, roughness1_uv_scale, roughness1_uv_offset, roughness1_out); + float sss1_out = 0.0; + mx_image_float(sss1_file, sss1_layer, sss1_default, geomprop_UV0_out1, sss1_uaddressmode, sss1_vaddressmode, sss1_filtertype, sss1_framerange, sss1_frameoffset, sss1_frameendaction, sss1_uv_scale, sss1_uv_offset, sss1_out); + vec3 normal1_out = vec3(0.0); + mx_image_vector3(normal1_file, normal1_layer, normal1_default, geomprop_UV0_out1, normal1_uaddressmode, normal1_vaddressmode, normal1_filtertype, normal1_framerange, normal1_frameoffset, normal1_frameendaction, normal1_uv_scale, normal1_uv_offset, normal1_out); + vec3 diffuse1_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse1_out, diffuse1_out_cm_out); + vec3 mtlxnormalmap3_out = vec3(0.0); + mx_normalmap_float(normal1_out, mtlxnormalmap3_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap3_out); + surfaceshader Queen_W_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(Queen_W_base, diffuse1_out_cm_out, Queen_W_diffuse_roughness, metallic1_out, Queen_W_specular, Queen_W_specular_color, roughness1_out, Queen_W_specular_IOR, Queen_W_specular_anisotropy, Queen_W_specular_rotation, Queen_W_transmission, Queen_W_transmission_color, Queen_W_transmission_depth, Queen_W_transmission_scatter, Queen_W_transmission_scatter_anisotropy, Queen_W_transmission_dispersion, Queen_W_transmission_extra_roughness, sss1_out, diffuse1_out_cm_out, diffuse1_out_cm_out, Queen_W_subsurface_scale, Queen_W_subsurface_anisotropy, Queen_W_sheen, Queen_W_sheen_color, Queen_W_sheen_roughness, Queen_W_coat, Queen_W_coat_color, Queen_W_coat_roughness, Queen_W_coat_anisotropy, Queen_W_coat_rotation, Queen_W_coat_IOR, geomprop_Nworld_out1, Queen_W_coat_affect_color, Queen_W_coat_affect_roughness, Queen_W_thin_film_thickness, Queen_W_thin_film_IOR, Queen_W_emission, Queen_W_emission_color, Queen_W_opacity, Queen_W_thin_walled, mtlxnormalmap3_out, geomprop_Tworld_out1, Queen_W_out); + material M_Queen_W_out = Queen_W_out; + out1 = vec4(M_Queen_W_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/M_Queen_W.glsl.vert b/Materials/Examples/StandardSurface/M_Queen_W.glsl.vert new file mode 100644 index 0000000000..de05e37c59 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Queen_W.glsl.vert @@ -0,0 +1,33 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/M_Queen_W.mdl b/Materials/Examples/StandardSurface/M_Queen_W.mdl new file mode 100644 index 0000000000..7d2336bd7d --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Queen_W.mdl @@ -0,0 +1,539 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material M_Queen_W +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform mx_coordinatespace_type geomprop_Bworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Bworld") + ]], + uniform int geomprop_Bworld_index = 0 + [[ + materialx::core::origin("Bworld") + ]], + uniform texture_2d diffuse1_file = texture_2d("/chess_set/queen_white_base_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_QueenWhite/diffuse1/file") + ]], + uniform string diffuse1_layer = "" + [[ + materialx::core::origin("NG_QueenWhite/diffuse1/layer") + ]], + color diffuse1_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_QueenWhite/diffuse1/default") + ]], + uniform mx_addressmode_type diffuse1_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenWhite/diffuse1/uaddressmode") + ]], + uniform mx_addressmode_type diffuse1_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenWhite/diffuse1/vaddressmode") + ]], + uniform mx_filterlookup_type diffuse1_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_QueenWhite/diffuse1/filtertype") + ]], + uniform string diffuse1_framerange = "" + [[ + materialx::core::origin("NG_QueenWhite/diffuse1/framerange") + ]], + uniform int diffuse1_frameoffset = 0 + [[ + materialx::core::origin("NG_QueenWhite/diffuse1/frameoffset") + ]], + uniform mx_addressmode_type diffuse1_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_QueenWhite/diffuse1/frameendaction") + ]], + uniform texture_2d metallic1_file = texture_2d("/chess_set/queen_shared_metallic.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_QueenWhite/metallic1/file") + ]], + uniform string metallic1_layer = "" + [[ + materialx::core::origin("NG_QueenWhite/metallic1/layer") + ]], + float metallic1_default = 0.000000 + [[ + materialx::core::origin("NG_QueenWhite/metallic1/default") + ]], + uniform mx_addressmode_type metallic1_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenWhite/metallic1/uaddressmode") + ]], + uniform mx_addressmode_type metallic1_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenWhite/metallic1/vaddressmode") + ]], + uniform mx_filterlookup_type metallic1_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_QueenWhite/metallic1/filtertype") + ]], + uniform string metallic1_framerange = "" + [[ + materialx::core::origin("NG_QueenWhite/metallic1/framerange") + ]], + uniform int metallic1_frameoffset = 0 + [[ + materialx::core::origin("NG_QueenWhite/metallic1/frameoffset") + ]], + uniform mx_addressmode_type metallic1_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_QueenWhite/metallic1/frameendaction") + ]], + uniform texture_2d roughness1_file = texture_2d("/chess_set/queen_white_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_QueenWhite/roughness1/file") + ]], + uniform string roughness1_layer = "" + [[ + materialx::core::origin("NG_QueenWhite/roughness1/layer") + ]], + float roughness1_default = 0.000000 + [[ + materialx::core::origin("NG_QueenWhite/roughness1/default") + ]], + uniform mx_addressmode_type roughness1_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenWhite/roughness1/uaddressmode") + ]], + uniform mx_addressmode_type roughness1_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenWhite/roughness1/vaddressmode") + ]], + uniform mx_filterlookup_type roughness1_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_QueenWhite/roughness1/filtertype") + ]], + uniform string roughness1_framerange = "" + [[ + materialx::core::origin("NG_QueenWhite/roughness1/framerange") + ]], + uniform int roughness1_frameoffset = 0 + [[ + materialx::core::origin("NG_QueenWhite/roughness1/frameoffset") + ]], + uniform mx_addressmode_type roughness1_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_QueenWhite/roughness1/frameendaction") + ]], + uniform texture_2d sss1_file = texture_2d("/chess_set/queen_shared_scattering.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_QueenWhite/sss1/file") + ]], + uniform string sss1_layer = "" + [[ + materialx::core::origin("NG_QueenWhite/sss1/layer") + ]], + float sss1_default = 0.000000 + [[ + materialx::core::origin("NG_QueenWhite/sss1/default") + ]], + uniform mx_addressmode_type sss1_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenWhite/sss1/uaddressmode") + ]], + uniform mx_addressmode_type sss1_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenWhite/sss1/vaddressmode") + ]], + uniform mx_filterlookup_type sss1_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_QueenWhite/sss1/filtertype") + ]], + uniform string sss1_framerange = "" + [[ + materialx::core::origin("NG_QueenWhite/sss1/framerange") + ]], + uniform int sss1_frameoffset = 0 + [[ + materialx::core::origin("NG_QueenWhite/sss1/frameoffset") + ]], + uniform mx_addressmode_type sss1_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_QueenWhite/sss1/frameendaction") + ]], + uniform texture_2d normal1_file = texture_2d("/chess_set/queen_white_normal.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_QueenWhite/normal1/file") + ]], + uniform string normal1_layer = "" + [[ + materialx::core::origin("NG_QueenWhite/normal1/layer") + ]], + float3 normal1_default = float3(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_QueenWhite/normal1/default") + ]], + uniform mx_addressmode_type normal1_uaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenWhite/normal1/uaddressmode") + ]], + uniform mx_addressmode_type normal1_vaddressmode = mx_addressmode_type_periodic + [[ + materialx::core::origin("NG_QueenWhite/normal1/vaddressmode") + ]], + uniform mx_filterlookup_type normal1_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_QueenWhite/normal1/filtertype") + ]], + uniform string normal1_framerange = "" + [[ + materialx::core::origin("NG_QueenWhite/normal1/framerange") + ]], + uniform int normal1_frameoffset = 0 + [[ + materialx::core::origin("NG_QueenWhite/normal1/frameoffset") + ]], + uniform mx_addressmode_type normal1_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_QueenWhite/normal1/frameendaction") + ]], + float mtlxnormalmap3_scale = 1.000000 + [[ + materialx::core::origin("NG_QueenWhite/mtlxnormalmap3/scale") + ]], + float Queen_W_base = 1.000000 + [[ + materialx::core::origin("Queen_W/base") + ]], + float Queen_W_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("Queen_W/diffuse_roughness") + ]], + float Queen_W_specular = 1.000000 + [[ + materialx::core::origin("Queen_W/specular") + ]], + color Queen_W_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Queen_W/specular_color") + ]], + uniform float Queen_W_specular_IOR = 1.500000 + [[ + materialx::core::origin("Queen_W/specular_IOR") + ]], + float Queen_W_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("Queen_W/specular_anisotropy") + ]], + float Queen_W_specular_rotation = 0.000000 + [[ + materialx::core::origin("Queen_W/specular_rotation") + ]], + float Queen_W_transmission = 0.000000 + [[ + materialx::core::origin("Queen_W/transmission") + ]], + color Queen_W_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Queen_W/transmission_color") + ]], + float Queen_W_transmission_depth = 0.000000 + [[ + materialx::core::origin("Queen_W/transmission_depth") + ]], + color Queen_W_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("Queen_W/transmission_scatter") + ]], + float Queen_W_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("Queen_W/transmission_scatter_anisotropy") + ]], + float Queen_W_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("Queen_W/transmission_dispersion") + ]], + float Queen_W_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("Queen_W/transmission_extra_roughness") + ]], + float Queen_W_subsurface_scale = 0.001000 + [[ + materialx::core::origin("Queen_W/subsurface_scale") + ]], + float Queen_W_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("Queen_W/subsurface_anisotropy") + ]], + float Queen_W_sheen = 0.000000 + [[ + materialx::core::origin("Queen_W/sheen") + ]], + color Queen_W_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Queen_W/sheen_color") + ]], + float Queen_W_sheen_roughness = 0.300000 + [[ + materialx::core::origin("Queen_W/sheen_roughness") + ]], + float Queen_W_coat = 0.000000 + [[ + materialx::core::origin("Queen_W/coat") + ]], + color Queen_W_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Queen_W/coat_color") + ]], + float Queen_W_coat_roughness = 0.100000 + [[ + materialx::core::origin("Queen_W/coat_roughness") + ]], + float Queen_W_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("Queen_W/coat_anisotropy") + ]], + float Queen_W_coat_rotation = 0.000000 + [[ + materialx::core::origin("Queen_W/coat_rotation") + ]], + uniform float Queen_W_coat_IOR = 1.500000 + [[ + materialx::core::origin("Queen_W/coat_IOR") + ]], + float Queen_W_coat_affect_color = 0.000000 + [[ + materialx::core::origin("Queen_W/coat_affect_color") + ]], + float Queen_W_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("Queen_W/coat_affect_roughness") + ]], + float Queen_W_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("Queen_W/thin_film_thickness") + ]], + float Queen_W_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("Queen_W/thin_film_IOR") + ]], + float Queen_W_emission = 0.000000 + [[ + materialx::core::origin("Queen_W/emission") + ]], + color Queen_W_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Queen_W/emission_color") + ]], + color Queen_W_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("Queen_W/opacity") + ]], + bool Queen_W_thin_walled = false + [[ + materialx::core::origin("Queen_W/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float3 geomprop_Bworld_out1 = materialx::stdlib_1_8::mx_bitangent_vector3(mxp_space:geomprop_Bworld_space, mxp_index:geomprop_Bworld_index); + color diffuse1_out = materialx::stdlib_1_8::mx_image_color3(diffuse1_file, diffuse1_layer, diffuse1_default, geomprop_UV0_out1, diffuse1_uaddressmode, diffuse1_vaddressmode, diffuse1_filtertype, diffuse1_framerange, diffuse1_frameoffset, diffuse1_frameendaction, mxp_flip_v:false); + float metallic1_out = materialx::stdlib_1_8::mx_image_float(metallic1_file, metallic1_layer, metallic1_default, geomprop_UV0_out1, metallic1_uaddressmode, metallic1_vaddressmode, metallic1_filtertype, metallic1_framerange, metallic1_frameoffset, metallic1_frameendaction, mxp_flip_v:false); + float roughness1_out = materialx::stdlib_1_8::mx_image_float(roughness1_file, roughness1_layer, roughness1_default, geomprop_UV0_out1, roughness1_uaddressmode, roughness1_vaddressmode, roughness1_filtertype, roughness1_framerange, roughness1_frameoffset, roughness1_frameendaction, mxp_flip_v:false); + float sss1_out = materialx::stdlib_1_8::mx_image_float(sss1_file, sss1_layer, sss1_default, geomprop_UV0_out1, sss1_uaddressmode, sss1_vaddressmode, sss1_filtertype, sss1_framerange, sss1_frameoffset, sss1_frameendaction, mxp_flip_v:false); + float3 normal1_out = materialx::stdlib_1_8::mx_image_vector3(normal1_file, normal1_layer, normal1_default, geomprop_UV0_out1, normal1_uaddressmode, normal1_vaddressmode, normal1_filtertype, normal1_framerange, normal1_frameoffset, normal1_frameendaction, mxp_flip_v:false); + color diffuse1_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(diffuse1_out); + float3 mtlxnormalmap3_out = materialx::stdlib_1_8::mx_normalmap_float(mxp_in:normal1_out, mxp_scale:mtlxnormalmap3_scale, mxp_normal:geomprop_Nworld_out1, mxp_tangent:geomprop_Tworld_out1, mxp_bitangent:geomprop_Bworld_out1); + material Queen_W_out = NG_standard_surface_surfaceshader_100(Queen_W_base, diffuse1_out_cm_out, Queen_W_diffuse_roughness, metallic1_out, Queen_W_specular, Queen_W_specular_color, roughness1_out, Queen_W_specular_IOR, Queen_W_specular_anisotropy, Queen_W_specular_rotation, Queen_W_transmission, Queen_W_transmission_color, Queen_W_transmission_depth, Queen_W_transmission_scatter, Queen_W_transmission_scatter_anisotropy, Queen_W_transmission_dispersion, Queen_W_transmission_extra_roughness, sss1_out, diffuse1_out_cm_out, diffuse1_out_cm_out, Queen_W_subsurface_scale, Queen_W_subsurface_anisotropy, Queen_W_sheen, Queen_W_sheen_color, Queen_W_sheen_roughness, Queen_W_coat, Queen_W_coat_color, Queen_W_coat_roughness, Queen_W_coat_anisotropy, Queen_W_coat_rotation, Queen_W_coat_IOR, geomprop_Nworld_out1, Queen_W_coat_affect_color, Queen_W_coat_affect_roughness, Queen_W_thin_film_thickness, Queen_W_thin_film_IOR, Queen_W_emission, Queen_W_emission_color, Queen_W_opacity, Queen_W_thin_walled, mtlxnormalmap3_out, geomprop_Tworld_out1); + material M_Queen_W_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: Queen_W_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = M_Queen_W_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/M_Queen_W.msl.frag b/Materials/Examples/StandardSurface/M_Queen_W.msl.frag new file mode 100644 index 0000000000..f3df7141a2 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Queen_W.msl.frag @@ -0,0 +1,3049 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + int diffuse1_layer; + vec3 diffuse1_default; + int diffuse1_uaddressmode; + int diffuse1_vaddressmode; + int diffuse1_filtertype; + int diffuse1_framerange; + int diffuse1_frameoffset; + int diffuse1_frameendaction; + vec2 diffuse1_uv_scale; + vec2 diffuse1_uv_offset; + int metallic1_layer; + float metallic1_default; + int metallic1_uaddressmode; + int metallic1_vaddressmode; + int metallic1_filtertype; + int metallic1_framerange; + int metallic1_frameoffset; + int metallic1_frameendaction; + vec2 metallic1_uv_scale; + vec2 metallic1_uv_offset; + int roughness1_layer; + float roughness1_default; + int roughness1_uaddressmode; + int roughness1_vaddressmode; + int roughness1_filtertype; + int roughness1_framerange; + int roughness1_frameoffset; + int roughness1_frameendaction; + vec2 roughness1_uv_scale; + vec2 roughness1_uv_offset; + int sss1_layer; + float sss1_default; + int sss1_uaddressmode; + int sss1_vaddressmode; + int sss1_filtertype; + int sss1_framerange; + int sss1_frameoffset; + int sss1_frameendaction; + vec2 sss1_uv_scale; + vec2 sss1_uv_offset; + int normal1_layer; + vec3 normal1_default; + int normal1_uaddressmode; + int normal1_vaddressmode; + int normal1_filtertype; + int normal1_framerange; + int normal1_frameoffset; + int normal1_frameendaction; + vec2 normal1_uv_scale; + vec2 normal1_uv_offset; + float mtlxnormalmap3_scale; + float Queen_W_base; + float Queen_W_diffuse_roughness; + float Queen_W_specular; + vec3 Queen_W_specular_color; + float Queen_W_specular_IOR; + float Queen_W_specular_anisotropy; + float Queen_W_specular_rotation; + float Queen_W_transmission; + vec3 Queen_W_transmission_color; + float Queen_W_transmission_depth; + vec3 Queen_W_transmission_scatter; + float Queen_W_transmission_scatter_anisotropy; + float Queen_W_transmission_dispersion; + float Queen_W_transmission_extra_roughness; + float Queen_W_subsurface_scale; + float Queen_W_subsurface_anisotropy; + float Queen_W_sheen; + vec3 Queen_W_sheen_color; + float Queen_W_sheen_roughness; + float Queen_W_coat; + vec3 Queen_W_coat_color; + float Queen_W_coat_roughness; + float Queen_W_coat_anisotropy; + float Queen_W_coat_rotation; + float Queen_W_coat_IOR; + float Queen_W_coat_affect_color; + float Queen_W_coat_affect_roughness; + float Queen_W_thin_film_thickness; + float Queen_W_thin_film_IOR; + float Queen_W_emission; + vec3 Queen_W_emission_color; + vec3 Queen_W_opacity; + bool Queen_W_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 bitangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture diffuse1_file , int diffuse1_layer + + , vec3 diffuse1_default + + , int diffuse1_uaddressmode + + , int diffuse1_vaddressmode + + , int diffuse1_filtertype + + , int diffuse1_framerange + + , int diffuse1_frameoffset + + , int diffuse1_frameendaction + + , vec2 diffuse1_uv_scale + + , vec2 diffuse1_uv_offset + +, MetalTexture metallic1_file , int metallic1_layer + + , float metallic1_default + + , int metallic1_uaddressmode + + , int metallic1_vaddressmode + + , int metallic1_filtertype + + , int metallic1_framerange + + , int metallic1_frameoffset + + , int metallic1_frameendaction + + , vec2 metallic1_uv_scale + + , vec2 metallic1_uv_offset + +, MetalTexture roughness1_file , int roughness1_layer + + , float roughness1_default + + , int roughness1_uaddressmode + + , int roughness1_vaddressmode + + , int roughness1_filtertype + + , int roughness1_framerange + + , int roughness1_frameoffset + + , int roughness1_frameendaction + + , vec2 roughness1_uv_scale + + , vec2 roughness1_uv_offset + +, MetalTexture sss1_file , int sss1_layer + + , float sss1_default + + , int sss1_uaddressmode + + , int sss1_vaddressmode + + , int sss1_filtertype + + , int sss1_framerange + + , int sss1_frameoffset + + , int sss1_frameendaction + + , vec2 sss1_uv_scale + + , vec2 sss1_uv_offset + +, MetalTexture normal1_file , int normal1_layer + + , vec3 normal1_default + + , int normal1_uaddressmode + + , int normal1_vaddressmode + + , int normal1_filtertype + + , int normal1_framerange + + , int normal1_frameoffset + + , int normal1_frameendaction + + , vec2 normal1_uv_scale + + , vec2 normal1_uv_offset + + , float mtlxnormalmap3_scale + + , float Queen_W_base + + , float Queen_W_diffuse_roughness + + , float Queen_W_specular + + , vec3 Queen_W_specular_color + + , float Queen_W_specular_IOR + + , float Queen_W_specular_anisotropy + + , float Queen_W_specular_rotation + + , float Queen_W_transmission + + , vec3 Queen_W_transmission_color + + , float Queen_W_transmission_depth + + , vec3 Queen_W_transmission_scatter + + , float Queen_W_transmission_scatter_anisotropy + + , float Queen_W_transmission_dispersion + + , float Queen_W_transmission_extra_roughness + + , float Queen_W_subsurface_scale + + , float Queen_W_subsurface_anisotropy + + , float Queen_W_sheen + + , vec3 Queen_W_sheen_color + + , float Queen_W_sheen_roughness + + , float Queen_W_coat + + , vec3 Queen_W_coat_color + + , float Queen_W_coat_roughness + + , float Queen_W_coat_anisotropy + + , float Queen_W_coat_rotation + + , float Queen_W_coat_IOR + + , float Queen_W_coat_affect_color + + , float Queen_W_coat_affect_roughness + + , float Queen_W_thin_film_thickness + + , float Queen_W_thin_film_IOR + + , float Queen_W_emission + + , vec3 Queen_W_emission_color + + , vec3 Queen_W_opacity + + , bool Queen_W_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, diffuse1_file(diffuse1_file) + , diffuse1_layer(diffuse1_layer) + + , diffuse1_default(diffuse1_default) + + , diffuse1_uaddressmode(diffuse1_uaddressmode) + + , diffuse1_vaddressmode(diffuse1_vaddressmode) + + , diffuse1_filtertype(diffuse1_filtertype) + + , diffuse1_framerange(diffuse1_framerange) + + , diffuse1_frameoffset(diffuse1_frameoffset) + + , diffuse1_frameendaction(diffuse1_frameendaction) + + , diffuse1_uv_scale(diffuse1_uv_scale) + + , diffuse1_uv_offset(diffuse1_uv_offset) + +, metallic1_file(metallic1_file) + , metallic1_layer(metallic1_layer) + + , metallic1_default(metallic1_default) + + , metallic1_uaddressmode(metallic1_uaddressmode) + + , metallic1_vaddressmode(metallic1_vaddressmode) + + , metallic1_filtertype(metallic1_filtertype) + + , metallic1_framerange(metallic1_framerange) + + , metallic1_frameoffset(metallic1_frameoffset) + + , metallic1_frameendaction(metallic1_frameendaction) + + , metallic1_uv_scale(metallic1_uv_scale) + + , metallic1_uv_offset(metallic1_uv_offset) + +, roughness1_file(roughness1_file) + , roughness1_layer(roughness1_layer) + + , roughness1_default(roughness1_default) + + , roughness1_uaddressmode(roughness1_uaddressmode) + + , roughness1_vaddressmode(roughness1_vaddressmode) + + , roughness1_filtertype(roughness1_filtertype) + + , roughness1_framerange(roughness1_framerange) + + , roughness1_frameoffset(roughness1_frameoffset) + + , roughness1_frameendaction(roughness1_frameendaction) + + , roughness1_uv_scale(roughness1_uv_scale) + + , roughness1_uv_offset(roughness1_uv_offset) + +, sss1_file(sss1_file) + , sss1_layer(sss1_layer) + + , sss1_default(sss1_default) + + , sss1_uaddressmode(sss1_uaddressmode) + + , sss1_vaddressmode(sss1_vaddressmode) + + , sss1_filtertype(sss1_filtertype) + + , sss1_framerange(sss1_framerange) + + , sss1_frameoffset(sss1_frameoffset) + + , sss1_frameendaction(sss1_frameendaction) + + , sss1_uv_scale(sss1_uv_scale) + + , sss1_uv_offset(sss1_uv_offset) + +, normal1_file(normal1_file) + , normal1_layer(normal1_layer) + + , normal1_default(normal1_default) + + , normal1_uaddressmode(normal1_uaddressmode) + + , normal1_vaddressmode(normal1_vaddressmode) + + , normal1_filtertype(normal1_filtertype) + + , normal1_framerange(normal1_framerange) + + , normal1_frameoffset(normal1_frameoffset) + + , normal1_frameendaction(normal1_frameendaction) + + , normal1_uv_scale(normal1_uv_scale) + + , normal1_uv_offset(normal1_uv_offset) + + , mtlxnormalmap3_scale(mtlxnormalmap3_scale) + + , Queen_W_base(Queen_W_base) + + , Queen_W_diffuse_roughness(Queen_W_diffuse_roughness) + + , Queen_W_specular(Queen_W_specular) + + , Queen_W_specular_color(Queen_W_specular_color) + + , Queen_W_specular_IOR(Queen_W_specular_IOR) + + , Queen_W_specular_anisotropy(Queen_W_specular_anisotropy) + + , Queen_W_specular_rotation(Queen_W_specular_rotation) + + , Queen_W_transmission(Queen_W_transmission) + + , Queen_W_transmission_color(Queen_W_transmission_color) + + , Queen_W_transmission_depth(Queen_W_transmission_depth) + + , Queen_W_transmission_scatter(Queen_W_transmission_scatter) + + , Queen_W_transmission_scatter_anisotropy(Queen_W_transmission_scatter_anisotropy) + + , Queen_W_transmission_dispersion(Queen_W_transmission_dispersion) + + , Queen_W_transmission_extra_roughness(Queen_W_transmission_extra_roughness) + + , Queen_W_subsurface_scale(Queen_W_subsurface_scale) + + , Queen_W_subsurface_anisotropy(Queen_W_subsurface_anisotropy) + + , Queen_W_sheen(Queen_W_sheen) + + , Queen_W_sheen_color(Queen_W_sheen_color) + + , Queen_W_sheen_roughness(Queen_W_sheen_roughness) + + , Queen_W_coat(Queen_W_coat) + + , Queen_W_coat_color(Queen_W_coat_color) + + , Queen_W_coat_roughness(Queen_W_coat_roughness) + + , Queen_W_coat_anisotropy(Queen_W_coat_anisotropy) + + , Queen_W_coat_rotation(Queen_W_coat_rotation) + + , Queen_W_coat_IOR(Queen_W_coat_IOR) + + , Queen_W_coat_affect_color(Queen_W_coat_affect_color) + + , Queen_W_coat_affect_roughness(Queen_W_coat_affect_roughness) + + , Queen_W_thin_film_thickness(Queen_W_thin_film_thickness) + + , Queen_W_thin_film_IOR(Queen_W_thin_film_IOR) + + , Queen_W_emission(Queen_W_emission) + + , Queen_W_emission_color(Queen_W_emission_color) + + , Queen_W_opacity(Queen_W_opacity) + + , Queen_W_thin_walled(Queen_W_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture diffuse1_file; + int diffuse1_layer; + + + vec3 diffuse1_default; + + + int diffuse1_uaddressmode; + + + int diffuse1_vaddressmode; + + + int diffuse1_filtertype; + + + int diffuse1_framerange; + + + int diffuse1_frameoffset; + + + int diffuse1_frameendaction; + + + vec2 diffuse1_uv_scale; + + + vec2 diffuse1_uv_offset; + + +MetalTexture metallic1_file; + int metallic1_layer; + + + float metallic1_default; + + + int metallic1_uaddressmode; + + + int metallic1_vaddressmode; + + + int metallic1_filtertype; + + + int metallic1_framerange; + + + int metallic1_frameoffset; + + + int metallic1_frameendaction; + + + vec2 metallic1_uv_scale; + + + vec2 metallic1_uv_offset; + + +MetalTexture roughness1_file; + int roughness1_layer; + + + float roughness1_default; + + + int roughness1_uaddressmode; + + + int roughness1_vaddressmode; + + + int roughness1_filtertype; + + + int roughness1_framerange; + + + int roughness1_frameoffset; + + + int roughness1_frameendaction; + + + vec2 roughness1_uv_scale; + + + vec2 roughness1_uv_offset; + + +MetalTexture sss1_file; + int sss1_layer; + + + float sss1_default; + + + int sss1_uaddressmode; + + + int sss1_vaddressmode; + + + int sss1_filtertype; + + + int sss1_framerange; + + + int sss1_frameoffset; + + + int sss1_frameendaction; + + + vec2 sss1_uv_scale; + + + vec2 sss1_uv_offset; + + +MetalTexture normal1_file; + int normal1_layer; + + + vec3 normal1_default; + + + int normal1_uaddressmode; + + + int normal1_vaddressmode; + + + int normal1_filtertype; + + + int normal1_framerange; + + + int normal1_frameoffset; + + + int normal1_frameendaction; + + + vec2 normal1_uv_scale; + + + vec2 normal1_uv_offset; + + + float mtlxnormalmap3_scale; + + + float Queen_W_base; + + + float Queen_W_diffuse_roughness; + + + float Queen_W_specular; + + + vec3 Queen_W_specular_color; + + + float Queen_W_specular_IOR; + + + float Queen_W_specular_anisotropy; + + + float Queen_W_specular_rotation; + + + float Queen_W_transmission; + + + vec3 Queen_W_transmission_color; + + + float Queen_W_transmission_depth; + + + vec3 Queen_W_transmission_scatter; + + + float Queen_W_transmission_scatter_anisotropy; + + + float Queen_W_transmission_dispersion; + + + float Queen_W_transmission_extra_roughness; + + + float Queen_W_subsurface_scale; + + + float Queen_W_subsurface_anisotropy; + + + float Queen_W_sheen; + + + vec3 Queen_W_sheen_color; + + + float Queen_W_sheen_roughness; + + + float Queen_W_coat; + + + vec3 Queen_W_coat_color; + + + float Queen_W_coat_roughness; + + + float Queen_W_coat_anisotropy; + + + float Queen_W_coat_rotation; + + + float Queen_W_coat_IOR; + + + float Queen_W_coat_affect_color; + + + float Queen_W_coat_affect_roughness; + + + float Queen_W_thin_film_thickness; + + + float Queen_W_thin_film_IOR; + + + float Queen_W_emission; + + + vec3 Queen_W_emission_color; + + + vec3 Queen_W_opacity; + + + bool Queen_W_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + + void mx_image_vector3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_normalmap_vector2(vec3 value, vec2 normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + value = (dot(value, value) == 0.0) ? vec3(0.0, 0.0, 1.0) : value * 2.0 - 1.0; + value = T * value.x * normal_scale.x + + B * value.y * normal_scale.y + + N * value.z; + result = normalize(value); + } + + void mx_normalmap_float(vec3 value, float normal_scale, vec3 N, vec3 T, vec3 B, thread vec3& result) + { + mx_normalmap_vector2(value, vec2(normal_scale), N, T, B, result); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 geomprop_Bworld_out1 = normalize(vd.bitangentWorld); + vec3 diffuse1_out = vec3(0.0); + mx_image_color3(diffuse1_file, diffuse1_layer, diffuse1_default, geomprop_UV0_out1, diffuse1_uaddressmode, diffuse1_vaddressmode, diffuse1_filtertype, diffuse1_framerange, diffuse1_frameoffset, diffuse1_frameendaction, diffuse1_uv_scale, diffuse1_uv_offset, diffuse1_out); + float metallic1_out = 0.0; + mx_image_float(metallic1_file, metallic1_layer, metallic1_default, geomprop_UV0_out1, metallic1_uaddressmode, metallic1_vaddressmode, metallic1_filtertype, metallic1_framerange, metallic1_frameoffset, metallic1_frameendaction, metallic1_uv_scale, metallic1_uv_offset, metallic1_out); + float roughness1_out = 0.0; + mx_image_float(roughness1_file, roughness1_layer, roughness1_default, geomprop_UV0_out1, roughness1_uaddressmode, roughness1_vaddressmode, roughness1_filtertype, roughness1_framerange, roughness1_frameoffset, roughness1_frameendaction, roughness1_uv_scale, roughness1_uv_offset, roughness1_out); + float sss1_out = 0.0; + mx_image_float(sss1_file, sss1_layer, sss1_default, geomprop_UV0_out1, sss1_uaddressmode, sss1_vaddressmode, sss1_filtertype, sss1_framerange, sss1_frameoffset, sss1_frameendaction, sss1_uv_scale, sss1_uv_offset, sss1_out); + vec3 normal1_out = vec3(0.0); + mx_image_vector3(normal1_file, normal1_layer, normal1_default, geomprop_UV0_out1, normal1_uaddressmode, normal1_vaddressmode, normal1_filtertype, normal1_framerange, normal1_frameoffset, normal1_frameendaction, normal1_uv_scale, normal1_uv_offset, normal1_out); + vec3 diffuse1_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse1_out, diffuse1_out_cm_out); + vec3 mtlxnormalmap3_out = vec3(0.0); + mx_normalmap_float(normal1_out, mtlxnormalmap3_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap3_out); + surfaceshader Queen_W_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(Queen_W_base, diffuse1_out_cm_out, Queen_W_diffuse_roughness, metallic1_out, Queen_W_specular, Queen_W_specular_color, roughness1_out, Queen_W_specular_IOR, Queen_W_specular_anisotropy, Queen_W_specular_rotation, Queen_W_transmission, Queen_W_transmission_color, Queen_W_transmission_depth, Queen_W_transmission_scatter, Queen_W_transmission_scatter_anisotropy, Queen_W_transmission_dispersion, Queen_W_transmission_extra_roughness, sss1_out, diffuse1_out_cm_out, diffuse1_out_cm_out, Queen_W_subsurface_scale, Queen_W_subsurface_anisotropy, Queen_W_sheen, Queen_W_sheen_color, Queen_W_sheen_roughness, Queen_W_coat, Queen_W_coat_color, Queen_W_coat_roughness, Queen_W_coat_anisotropy, Queen_W_coat_rotation, Queen_W_coat_IOR, geomprop_Nworld_out1, Queen_W_coat_affect_color, Queen_W_coat_affect_roughness, Queen_W_thin_film_thickness, Queen_W_thin_film_IOR, Queen_W_emission, Queen_W_emission_color, Queen_W_opacity, Queen_W_thin_walled, mtlxnormalmap3_out, geomprop_Tworld_out1, Queen_W_out); + material M_Queen_W_out = Queen_W_out; + out1 = float4(M_Queen_W_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d diffuse1_file_tex [[texture(0)]], sampler diffuse1_file_sampler [[sampler(0)]] +, texture2d metallic1_file_tex [[texture(1)]], sampler metallic1_file_sampler [[sampler(1)]] +, texture2d roughness1_file_tex [[texture(2)]], sampler roughness1_file_sampler [[sampler(2)]] +, texture2d sss1_file_tex [[texture(3)]], sampler sss1_file_sampler [[sampler(3)]] +, texture2d normal1_file_tex [[texture(4)]], sampler normal1_file_sampler [[sampler(4)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(5)]], sampler u_envRadiance_sampler [[sampler(5)]] +, texture2d u_envIrradiance_tex [[texture(6)]], sampler u_envIrradiance_sampler [[sampler(6)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +diffuse1_file_tex, diffuse1_file_sampler } + , u_pub.diffuse1_layer + , u_pub.diffuse1_default + , u_pub.diffuse1_uaddressmode + , u_pub.diffuse1_vaddressmode + , u_pub.diffuse1_filtertype + , u_pub.diffuse1_framerange + , u_pub.diffuse1_frameoffset + , u_pub.diffuse1_frameendaction + , u_pub.diffuse1_uv_scale + , u_pub.diffuse1_uv_offset +, MetalTexture { +metallic1_file_tex, metallic1_file_sampler } + , u_pub.metallic1_layer + , u_pub.metallic1_default + , u_pub.metallic1_uaddressmode + , u_pub.metallic1_vaddressmode + , u_pub.metallic1_filtertype + , u_pub.metallic1_framerange + , u_pub.metallic1_frameoffset + , u_pub.metallic1_frameendaction + , u_pub.metallic1_uv_scale + , u_pub.metallic1_uv_offset +, MetalTexture { +roughness1_file_tex, roughness1_file_sampler } + , u_pub.roughness1_layer + , u_pub.roughness1_default + , u_pub.roughness1_uaddressmode + , u_pub.roughness1_vaddressmode + , u_pub.roughness1_filtertype + , u_pub.roughness1_framerange + , u_pub.roughness1_frameoffset + , u_pub.roughness1_frameendaction + , u_pub.roughness1_uv_scale + , u_pub.roughness1_uv_offset +, MetalTexture { +sss1_file_tex, sss1_file_sampler } + , u_pub.sss1_layer + , u_pub.sss1_default + , u_pub.sss1_uaddressmode + , u_pub.sss1_vaddressmode + , u_pub.sss1_filtertype + , u_pub.sss1_framerange + , u_pub.sss1_frameoffset + , u_pub.sss1_frameendaction + , u_pub.sss1_uv_scale + , u_pub.sss1_uv_offset +, MetalTexture { +normal1_file_tex, normal1_file_sampler } + , u_pub.normal1_layer + , u_pub.normal1_default + , u_pub.normal1_uaddressmode + , u_pub.normal1_vaddressmode + , u_pub.normal1_filtertype + , u_pub.normal1_framerange + , u_pub.normal1_frameoffset + , u_pub.normal1_frameendaction + , u_pub.normal1_uv_scale + , u_pub.normal1_uv_offset + , u_pub.mtlxnormalmap3_scale + , u_pub.Queen_W_base + , u_pub.Queen_W_diffuse_roughness + , u_pub.Queen_W_specular + , u_pub.Queen_W_specular_color + , u_pub.Queen_W_specular_IOR + , u_pub.Queen_W_specular_anisotropy + , u_pub.Queen_W_specular_rotation + , u_pub.Queen_W_transmission + , u_pub.Queen_W_transmission_color + , u_pub.Queen_W_transmission_depth + , u_pub.Queen_W_transmission_scatter + , u_pub.Queen_W_transmission_scatter_anisotropy + , u_pub.Queen_W_transmission_dispersion + , u_pub.Queen_W_transmission_extra_roughness + , u_pub.Queen_W_subsurface_scale + , u_pub.Queen_W_subsurface_anisotropy + , u_pub.Queen_W_sheen + , u_pub.Queen_W_sheen_color + , u_pub.Queen_W_sheen_roughness + , u_pub.Queen_W_coat + , u_pub.Queen_W_coat_color + , u_pub.Queen_W_coat_roughness + , u_pub.Queen_W_coat_anisotropy + , u_pub.Queen_W_coat_rotation + , u_pub.Queen_W_coat_IOR + , u_pub.Queen_W_coat_affect_color + , u_pub.Queen_W_coat_affect_roughness + , u_pub.Queen_W_thin_film_thickness + , u_pub.Queen_W_thin_film_IOR + , u_pub.Queen_W_emission + , u_pub.Queen_W_emission_color + , u_pub.Queen_W_opacity + , u_pub.Queen_W_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/M_Queen_W.msl.vert b/Materials/Examples/StandardSurface/M_Queen_W.msl.vert new file mode 100644 index 0000000000..292064615c --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Queen_W.msl.vert @@ -0,0 +1,128 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 bitangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.bitangentWorld = cross(vd.normalWorld, vd.tangentWorld); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'geomprop_Bworld'. Function already called in this scope. + // Omitted node 'diffuse1'. Function already called in this scope. + // Omitted node 'metallic1'. Function already called in this scope. + // Omitted node 'roughness1'. Function already called in this scope. + // Omitted node 'sss1'. Function already called in this scope. + // Omitted node 'normal1'. Function already called in this scope. + // Omitted node 'diffuse1_out_cm'. Function already called in this scope. + // Omitted node 'mtlxnormalmap3'. Function already called in this scope. + // Omitted node 'Queen_W'. Function already called in this scope. + // Omitted node 'M_Queen_W'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/M_Queen_W.osl b/Materials/Examples/StandardSurface/M_Queen_W.osl new file mode 100644 index 0000000000..72502ca010 --- /dev/null +++ b/Materials/Examples/StandardSurface/M_Queen_W.osl @@ -0,0 +1,699 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + + +void mx_image_vector3(textureresource file, string layer, vector default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output vector out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_normalmap_vector2(vector value, vector2 normal_scale, vector N, vector T, vector B, output vector result) +{ + vector decodedValue; + if (value == vector(0.0)) + { + decodedValue = vector(0.0, 0.0, 1.0); + } + else + { + decodedValue = value * 2.0 - 1.0; + } + + result = normalize(T * decodedValue[0] * normal_scale.x + B * decodedValue[1] * normal_scale.y + N * decodedValue[2]); +} + +void mx_normalmap_float(vector value, float normal_scale, vector N, vector T, vector B, output vector result) +{ + mx_normalmap_vector2(value, vector2(normal_scale, normal_scale), N, T, B, result); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader M_Queen_W +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "M_Queen_W" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string geomprop_Bworld_space = "world", + int geomprop_Bworld_index = 0 + [[ + string widget = "number" + ]], + string diffuse1_file = "chess_set/queen_white_base_color.jpg" + [[ + string widget = "filename" + ]], + string diffuse1_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string diffuse1_layer = "", + color diffuse1_default = color(0.000000, 0.000000, 0.000000), + string diffuse1_uaddressmode = "periodic", + string diffuse1_vaddressmode = "periodic", + string diffuse1_filtertype = "linear", + string diffuse1_framerange = "", + int diffuse1_frameoffset = 0 + [[ + string widget = "number" + ]], + string diffuse1_frameendaction = "constant", + string metallic1_file = "chess_set/queen_shared_metallic.jpg" + [[ + string widget = "filename" + ]], + string metallic1_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string metallic1_layer = "", + float metallic1_default = 0.000000 + [[ + string widget = "number" + ]], + string metallic1_uaddressmode = "periodic", + string metallic1_vaddressmode = "periodic", + string metallic1_filtertype = "linear", + string metallic1_framerange = "", + int metallic1_frameoffset = 0 + [[ + string widget = "number" + ]], + string metallic1_frameendaction = "constant", + string roughness1_file = "chess_set/queen_white_roughness.jpg" + [[ + string widget = "filename" + ]], + string roughness1_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string roughness1_layer = "", + float roughness1_default = 0.000000 + [[ + string widget = "number" + ]], + string roughness1_uaddressmode = "periodic", + string roughness1_vaddressmode = "periodic", + string roughness1_filtertype = "linear", + string roughness1_framerange = "", + int roughness1_frameoffset = 0 + [[ + string widget = "number" + ]], + string roughness1_frameendaction = "constant", + string sss1_file = "chess_set/queen_shared_scattering.jpg" + [[ + string widget = "filename" + ]], + string sss1_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string sss1_layer = "", + float sss1_default = 0.000000 + [[ + string widget = "number" + ]], + string sss1_uaddressmode = "periodic", + string sss1_vaddressmode = "periodic", + string sss1_filtertype = "linear", + string sss1_framerange = "", + int sss1_frameoffset = 0 + [[ + string widget = "number" + ]], + string sss1_frameendaction = "constant", + string normal1_file = "chess_set/queen_white_normal.jpg" + [[ + string widget = "filename" + ]], + string normal1_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + string normal1_layer = "", + vector normal1_default = vector(0.000000, 0.000000, 0.000000), + string normal1_uaddressmode = "periodic", + string normal1_vaddressmode = "periodic", + string normal1_filtertype = "linear", + string normal1_framerange = "", + int normal1_frameoffset = 0 + [[ + string widget = "number" + ]], + string normal1_frameendaction = "constant", + float mtlxnormalmap3_scale = 1.000000 + [[ + string widget = "number" + ]], + float Queen_W_base = 1.000000 + [[ + string widget = "number" + ]], + float Queen_W_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Queen_W_specular = 1.000000 + [[ + string widget = "number" + ]], + color Queen_W_specular_color = color(1.000000, 1.000000, 1.000000), + float Queen_W_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Queen_W_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Queen_W_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Queen_W_transmission = 0.000000 + [[ + string widget = "number" + ]], + color Queen_W_transmission_color = color(1.000000, 1.000000, 1.000000), + float Queen_W_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color Queen_W_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float Queen_W_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Queen_W_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float Queen_W_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Queen_W_subsurface_scale = 0.001000 + [[ + string widget = "number" + ]], + float Queen_W_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Queen_W_sheen = 0.000000 + [[ + string widget = "number" + ]], + color Queen_W_sheen_color = color(1.000000, 1.000000, 1.000000), + float Queen_W_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float Queen_W_coat = 0.000000 + [[ + string widget = "number" + ]], + color Queen_W_coat_color = color(1.000000, 1.000000, 1.000000), + float Queen_W_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float Queen_W_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float Queen_W_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float Queen_W_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Queen_W_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float Queen_W_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float Queen_W_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float Queen_W_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float Queen_W_emission = 0.000000 + [[ + string widget = "number" + ]], + color Queen_W_emission_color = color(1.000000, 1.000000, 1.000000), + color Queen_W_opacity = color(1.000000, 1.000000, 1.000000), + int Queen_W_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource diffuse1_file_ = {diffuse1_file, diffuse1_file_colorspace}; + textureresource metallic1_file_ = {metallic1_file, metallic1_file_colorspace}; + textureresource roughness1_file_ = {roughness1_file, roughness1_file_colorspace}; + textureresource sss1_file_ = {sss1_file, sss1_file_colorspace}; + textureresource normal1_file_ = {normal1_file, normal1_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + vector geomprop_Bworld_out1 = transform(geomprop_Bworld_space, normalize(dPdv)); + color diffuse1_out = color(0.0); + mx_image_color3(diffuse1_file_, diffuse1_layer, diffuse1_default, geomprop_UV0_out1, diffuse1_uaddressmode, diffuse1_vaddressmode, diffuse1_filtertype, diffuse1_framerange, diffuse1_frameoffset, diffuse1_frameendaction, diffuse1_out); + float metallic1_out = 0.0; + mx_image_float(metallic1_file_, metallic1_layer, metallic1_default, geomprop_UV0_out1, metallic1_uaddressmode, metallic1_vaddressmode, metallic1_filtertype, metallic1_framerange, metallic1_frameoffset, metallic1_frameendaction, metallic1_out); + float roughness1_out = 0.0; + mx_image_float(roughness1_file_, roughness1_layer, roughness1_default, geomprop_UV0_out1, roughness1_uaddressmode, roughness1_vaddressmode, roughness1_filtertype, roughness1_framerange, roughness1_frameoffset, roughness1_frameendaction, roughness1_out); + float sss1_out = 0.0; + mx_image_float(sss1_file_, sss1_layer, sss1_default, geomprop_UV0_out1, sss1_uaddressmode, sss1_vaddressmode, sss1_filtertype, sss1_framerange, sss1_frameoffset, sss1_frameendaction, sss1_out); + vector normal1_out = vector(0.0); + mx_image_vector3(normal1_file_, normal1_layer, normal1_default, geomprop_UV0_out1, normal1_uaddressmode, normal1_vaddressmode, normal1_filtertype, normal1_framerange, normal1_frameoffset, normal1_frameendaction, normal1_out); + color diffuse1_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(diffuse1_out, diffuse1_out_cm_out); + vector mtlxnormalmap3_out = vector(0.0); + mx_normalmap_float(normal1_out, mtlxnormalmap3_scale, geomprop_Nworld_out1, geomprop_Tworld_out1, geomprop_Bworld_out1, mtlxnormalmap3_out); + surfaceshader Queen_W_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(Queen_W_base, diffuse1_out_cm_out, Queen_W_diffuse_roughness, metallic1_out, Queen_W_specular, Queen_W_specular_color, roughness1_out, Queen_W_specular_IOR, Queen_W_specular_anisotropy, Queen_W_specular_rotation, Queen_W_transmission, Queen_W_transmission_color, Queen_W_transmission_depth, Queen_W_transmission_scatter, Queen_W_transmission_scatter_anisotropy, Queen_W_transmission_dispersion, Queen_W_transmission_extra_roughness, sss1_out, diffuse1_out_cm_out, diffuse1_out_cm_out, Queen_W_subsurface_scale, Queen_W_subsurface_anisotropy, Queen_W_sheen, Queen_W_sheen_color, Queen_W_sheen_roughness, Queen_W_coat, Queen_W_coat_color, Queen_W_coat_roughness, Queen_W_coat_anisotropy, Queen_W_coat_rotation, Queen_W_coat_IOR, geomprop_Nworld_out1, Queen_W_coat_affect_color, Queen_W_coat_affect_roughness, Queen_W_thin_film_thickness, Queen_W_thin_film_IOR, Queen_W_emission, Queen_W_emission_color, Queen_W_opacity, Queen_W_thin_walled, mtlxnormalmap3_out, geomprop_Tworld_out1, Queen_W_out); + MATERIAL M_Queen_W_out = mx_surfacematerial(Queen_W_out, backsurfaceshader, displacementshader1); + out = M_Queen_W_out; +} + diff --git a/Materials/Examples/StandardSurface/Marble_3D.glsl.frag b/Materials/Examples/StandardSurface/Marble_3D.glsl.frag new file mode 100644 index 0000000000..ab321426fb --- /dev/null +++ b/Materials/Examples/StandardSurface/Marble_3D.glsl.frag @@ -0,0 +1,2538 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform vec3 add_xyz_in2 = vec3(1.000000, 1.000000, 1.000000); +uniform float scale_pos_in2 = 4.000000; +uniform float scale_xyz_in2 = 6.000000; +uniform float noise_amplitude = 1.000000; +uniform int noise_octaves = 3; +uniform float noise_lacunarity = 2.000000; +uniform float noise_diminish = 0.500000; +uniform float scale_noise_in2 = 3.000000; +uniform float scale_in2 = 0.500000; +uniform float bias_in2 = 0.500000; +uniform float power_in2 = 3.000000; +uniform vec3 color_mix_fg = vec3(0.100000, 0.100000, 0.300000); +uniform vec3 color_mix_bg = vec3(0.800000, 0.800000, 0.800000); +uniform float SR_marble1_base = 1.000000; +uniform float SR_marble1_diffuse_roughness = 0.000000; +uniform float SR_marble1_metalness = 0.000000; +uniform float SR_marble1_specular = 1.000000; +uniform vec3 SR_marble1_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_marble1_specular_roughness = 0.100000; +uniform float SR_marble1_specular_IOR = 1.500000; +uniform float SR_marble1_specular_anisotropy = 0.000000; +uniform float SR_marble1_specular_rotation = 0.000000; +uniform float SR_marble1_transmission = 0.000000; +uniform vec3 SR_marble1_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_marble1_transmission_depth = 0.000000; +uniform vec3 SR_marble1_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_marble1_transmission_scatter_anisotropy = 0.000000; +uniform float SR_marble1_transmission_dispersion = 0.000000; +uniform float SR_marble1_transmission_extra_roughness = 0.000000; +uniform float SR_marble1_subsurface = 0.400000; +uniform vec3 SR_marble1_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_marble1_subsurface_scale = 1.000000; +uniform float SR_marble1_subsurface_anisotropy = 0.000000; +uniform float SR_marble1_sheen = 0.000000; +uniform vec3 SR_marble1_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_marble1_sheen_roughness = 0.300000; +uniform float SR_marble1_coat = 0.000000; +uniform vec3 SR_marble1_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_marble1_coat_roughness = 0.100000; +uniform float SR_marble1_coat_anisotropy = 0.000000; +uniform float SR_marble1_coat_rotation = 0.000000; +uniform float SR_marble1_coat_IOR = 1.500000; +uniform float SR_marble1_coat_affect_color = 0.000000; +uniform float SR_marble1_coat_affect_roughness = 0.000000; +uniform float SR_marble1_thin_film_thickness = 0.000000; +uniform float SR_marble1_thin_film_IOR = 1.500000; +uniform float SR_marble1_emission = 0.000000; +uniform vec3 SR_marble1_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_marble1_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_marble1_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionObject; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +/* +Noise Library. + +This library is a modified version of the noise library found in +Open Shading Language: +github.com/imageworks/OpenShadingLanguage/blob/master/src/include/OSL/oslnoise.h + +It contains the subset of noise types needed to implement the MaterialX +standard library. The modifications are mainly conversions from C++ to GLSL. +Produced results should be identical to the OSL noise functions. + +Original copyright notice: +------------------------------------------------------------------------ +Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of Sony Pictures Imageworks nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +------------------------------------------------------------------------ +*/ + +float mx_select(bool b, float t, float f) +{ + return b ? t : f; +} + +float mx_negate_if(float val, bool b) +{ + return b ? -val : val; +} + +int mx_floor(float x) +{ + return int(floor(x)); +} + +// return mx_floor as well as the fractional remainder +float mx_floorfrac(float x, out int i) +{ + i = mx_floor(x); + return x - float(i); +} + +float mx_bilerp(float v0, float v1, float v2, float v3, float s, float t) +{ + float s1 = 1.0 - s; + return (1.0 - t) * (v0*s1 + v1*s) + t * (v2*s1 + v3*s); +} +vec3 mx_bilerp(vec3 v0, vec3 v1, vec3 v2, vec3 v3, float s, float t) +{ + float s1 = 1.0 - s; + return (1.0 - t) * (v0*s1 + v1*s) + t * (v2*s1 + v3*s); +} +float mx_trilerp(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7, float s, float t, float r) +{ + float s1 = 1.0 - s; + float t1 = 1.0 - t; + float r1 = 1.0 - r; + return (r1*(t1*(v0*s1 + v1*s) + t*(v2*s1 + v3*s)) + + r*(t1*(v4*s1 + v5*s) + t*(v6*s1 + v7*s))); +} +vec3 mx_trilerp(vec3 v0, vec3 v1, vec3 v2, vec3 v3, vec3 v4, vec3 v5, vec3 v6, vec3 v7, float s, float t, float r) +{ + float s1 = 1.0 - s; + float t1 = 1.0 - t; + float r1 = 1.0 - r; + return (r1*(t1*(v0*s1 + v1*s) + t*(v2*s1 + v3*s)) + + r*(t1*(v4*s1 + v5*s) + t*(v6*s1 + v7*s))); +} + +// 2 and 3 dimensional gradient functions - perform a dot product against a +// randomly chosen vector. Note that the gradient vector is not normalized, but +// this only affects the overal "scale" of the result, so we simply account for +// the scale by multiplying in the corresponding "perlin" function. +float mx_gradient_float(uint hash, float x, float y) +{ + // 8 possible directions (+-1,+-2) and (+-2,+-1) + uint h = hash & 7u; + float u = mx_select(h<4u, x, y); + float v = 2.0 * mx_select(h<4u, y, x); + // compute the dot product with (x,y). + return mx_negate_if(u, bool(h&1u)) + mx_negate_if(v, bool(h&2u)); +} +float mx_gradient_float(uint hash, float x, float y, float z) +{ + // use vectors pointing to the edges of the cube + uint h = hash & 15u; + float u = mx_select(h<8u, x, y); + float v = mx_select(h<4u, y, mx_select((h==12u)||(h==14u), x, z)); + return mx_negate_if(u, bool(h&1u)) + mx_negate_if(v, bool(h&2u)); +} +vec3 mx_gradient_vec3(uvec3 hash, float x, float y) +{ + return vec3(mx_gradient_float(hash.x, x, y), mx_gradient_float(hash.y, x, y), mx_gradient_float(hash.z, x, y)); +} +vec3 mx_gradient_vec3(uvec3 hash, float x, float y, float z) +{ + return vec3(mx_gradient_float(hash.x, x, y, z), mx_gradient_float(hash.y, x, y, z), mx_gradient_float(hash.z, x, y, z)); +} +// Scaling factors to normalize the result of gradients above. +// These factors were experimentally calculated to be: +// 2D: 0.6616 +// 3D: 0.9820 +float mx_gradient_scale2d(float v) { return 0.6616 * v; } +float mx_gradient_scale3d(float v) { return 0.9820 * v; } +vec3 mx_gradient_scale2d(vec3 v) { return 0.6616 * v; } +vec3 mx_gradient_scale3d(vec3 v) { return 0.9820 * v; } + +/// Bitwise circular rotation left by k bits (for 32 bit unsigned integers) +uint mx_rotl32(uint x, int k) +{ + return (x<>(32-k)); +} + +void mx_bjmix(inout uint a, inout uint b, inout uint c) +{ + a -= c; a ^= mx_rotl32(c, 4); c += b; + b -= a; b ^= mx_rotl32(a, 6); a += c; + c -= b; c ^= mx_rotl32(b, 8); b += a; + a -= c; a ^= mx_rotl32(c,16); c += b; + b -= a; b ^= mx_rotl32(a,19); a += c; + c -= b; c ^= mx_rotl32(b, 4); b += a; +} + +// Mix up and combine the bits of a, b, and c (doesn't change them, but +// returns a hash of those three original values). +uint mx_bjfinal(uint a, uint b, uint c) +{ + c ^= b; c -= mx_rotl32(b,14); + a ^= c; a -= mx_rotl32(c,11); + b ^= a; b -= mx_rotl32(a,25); + c ^= b; c -= mx_rotl32(b,16); + a ^= c; a -= mx_rotl32(c,4); + b ^= a; b -= mx_rotl32(a,14); + c ^= b; c -= mx_rotl32(b,24); + return c; +} + +// Convert a 32 bit integer into a floating point number in [0,1] +float mx_bits_to_01(uint bits) +{ + return float(bits) / float(uint(0xffffffff)); +} + +float mx_fade(float t) +{ + return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); +} + +uint mx_hash_int(int x) +{ + uint len = 1u; + uint seed = uint(0xdeadbeef) + (len << 2u) + 13u; + return mx_bjfinal(seed+uint(x), seed, seed); +} + +uint mx_hash_int(int x, int y) +{ + uint len = 2u; + uint a, b, c; + a = b = c = uint(0xdeadbeef) + (len << 2u) + 13u; + a += uint(x); + b += uint(y); + return mx_bjfinal(a, b, c); +} + +uint mx_hash_int(int x, int y, int z) +{ + uint len = 3u; + uint a, b, c; + a = b = c = uint(0xdeadbeef) + (len << 2u) + 13u; + a += uint(x); + b += uint(y); + c += uint(z); + return mx_bjfinal(a, b, c); +} + +uint mx_hash_int(int x, int y, int z, int xx) +{ + uint len = 4u; + uint a, b, c; + a = b = c = uint(0xdeadbeef) + (len << 2u) + 13u; + a += uint(x); + b += uint(y); + c += uint(z); + mx_bjmix(a, b, c); + a += uint(xx); + return mx_bjfinal(a, b, c); +} + +uint mx_hash_int(int x, int y, int z, int xx, int yy) +{ + uint len = 5u; + uint a, b, c; + a = b = c = uint(0xdeadbeef) + (len << 2u) + 13u; + a += uint(x); + b += uint(y); + c += uint(z); + mx_bjmix(a, b, c); + a += uint(xx); + b += uint(yy); + return mx_bjfinal(a, b, c); +} + +uvec3 mx_hash_vec3(int x, int y) +{ + uint h = mx_hash_int(x, y); + // we only need the low-order bits to be random, so split out + // the 32 bit result into 3 parts for each channel + uvec3 result; + result.x = (h ) & 0xFFu; + result.y = (h >> 8 ) & 0xFFu; + result.z = (h >> 16) & 0xFFu; + return result; +} + +uvec3 mx_hash_vec3(int x, int y, int z) +{ + uint h = mx_hash_int(x, y, z); + // we only need the low-order bits to be random, so split out + // the 32 bit result into 3 parts for each channel + uvec3 result; + result.x = (h ) & 0xFFu; + result.y = (h >> 8 ) & 0xFFu; + result.z = (h >> 16) & 0xFFu; + return result; +} + +float mx_perlin_noise_float(vec2 p) +{ + int X, Y; + float fx = mx_floorfrac(p.x, X); + float fy = mx_floorfrac(p.y, Y); + float u = mx_fade(fx); + float v = mx_fade(fy); + float result = mx_bilerp( + mx_gradient_float(mx_hash_int(X , Y ), fx , fy ), + mx_gradient_float(mx_hash_int(X+1, Y ), fx-1.0, fy ), + mx_gradient_float(mx_hash_int(X , Y+1), fx , fy-1.0), + mx_gradient_float(mx_hash_int(X+1, Y+1), fx-1.0, fy-1.0), + u, v); + return mx_gradient_scale2d(result); +} + +float mx_perlin_noise_float(vec3 p) +{ + int X, Y, Z; + float fx = mx_floorfrac(p.x, X); + float fy = mx_floorfrac(p.y, Y); + float fz = mx_floorfrac(p.z, Z); + float u = mx_fade(fx); + float v = mx_fade(fy); + float w = mx_fade(fz); + float result = mx_trilerp( + mx_gradient_float(mx_hash_int(X , Y , Z ), fx , fy , fz ), + mx_gradient_float(mx_hash_int(X+1, Y , Z ), fx-1.0, fy , fz ), + mx_gradient_float(mx_hash_int(X , Y+1, Z ), fx , fy-1.0, fz ), + mx_gradient_float(mx_hash_int(X+1, Y+1, Z ), fx-1.0, fy-1.0, fz ), + mx_gradient_float(mx_hash_int(X , Y , Z+1), fx , fy , fz-1.0), + mx_gradient_float(mx_hash_int(X+1, Y , Z+1), fx-1.0, fy , fz-1.0), + mx_gradient_float(mx_hash_int(X , Y+1, Z+1), fx , fy-1.0, fz-1.0), + mx_gradient_float(mx_hash_int(X+1, Y+1, Z+1), fx-1.0, fy-1.0, fz-1.0), + u, v, w); + return mx_gradient_scale3d(result); +} + +vec3 mx_perlin_noise_vec3(vec2 p) +{ + int X, Y; + float fx = mx_floorfrac(p.x, X); + float fy = mx_floorfrac(p.y, Y); + float u = mx_fade(fx); + float v = mx_fade(fy); + vec3 result = mx_bilerp( + mx_gradient_vec3(mx_hash_vec3(X , Y ), fx , fy ), + mx_gradient_vec3(mx_hash_vec3(X+1, Y ), fx-1.0, fy ), + mx_gradient_vec3(mx_hash_vec3(X , Y+1), fx , fy-1.0), + mx_gradient_vec3(mx_hash_vec3(X+1, Y+1), fx-1.0, fy-1.0), + u, v); + return mx_gradient_scale2d(result); +} + +vec3 mx_perlin_noise_vec3(vec3 p) +{ + int X, Y, Z; + float fx = mx_floorfrac(p.x, X); + float fy = mx_floorfrac(p.y, Y); + float fz = mx_floorfrac(p.z, Z); + float u = mx_fade(fx); + float v = mx_fade(fy); + float w = mx_fade(fz); + vec3 result = mx_trilerp( + mx_gradient_vec3(mx_hash_vec3(X , Y , Z ), fx , fy , fz ), + mx_gradient_vec3(mx_hash_vec3(X+1, Y , Z ), fx-1.0, fy , fz ), + mx_gradient_vec3(mx_hash_vec3(X , Y+1, Z ), fx , fy-1.0, fz ), + mx_gradient_vec3(mx_hash_vec3(X+1, Y+1, Z ), fx-1.0, fy-1.0, fz ), + mx_gradient_vec3(mx_hash_vec3(X , Y , Z+1), fx , fy , fz-1.0), + mx_gradient_vec3(mx_hash_vec3(X+1, Y , Z+1), fx-1.0, fy , fz-1.0), + mx_gradient_vec3(mx_hash_vec3(X , Y+1, Z+1), fx , fy-1.0, fz-1.0), + mx_gradient_vec3(mx_hash_vec3(X+1, Y+1, Z+1), fx-1.0, fy-1.0, fz-1.0), + u, v, w); + return mx_gradient_scale3d(result); +} + +float mx_cell_noise_float(float p) +{ + int ix = mx_floor(p); + return mx_bits_to_01(mx_hash_int(ix)); +} + +float mx_cell_noise_float(vec2 p) +{ + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + return mx_bits_to_01(mx_hash_int(ix, iy)); +} + +float mx_cell_noise_float(vec3 p) +{ + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + int iz = mx_floor(p.z); + return mx_bits_to_01(mx_hash_int(ix, iy, iz)); +} + +float mx_cell_noise_float(vec4 p) +{ + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + int iz = mx_floor(p.z); + int iw = mx_floor(p.w); + return mx_bits_to_01(mx_hash_int(ix, iy, iz, iw)); +} + +vec3 mx_cell_noise_vec3(float p) +{ + int ix = mx_floor(p); + return vec3( + mx_bits_to_01(mx_hash_int(ix, 0)), + mx_bits_to_01(mx_hash_int(ix, 1)), + mx_bits_to_01(mx_hash_int(ix, 2)) + ); +} + +vec3 mx_cell_noise_vec3(vec2 p) +{ + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + return vec3( + mx_bits_to_01(mx_hash_int(ix, iy, 0)), + mx_bits_to_01(mx_hash_int(ix, iy, 1)), + mx_bits_to_01(mx_hash_int(ix, iy, 2)) + ); +} + +vec3 mx_cell_noise_vec3(vec3 p) +{ + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + int iz = mx_floor(p.z); + return vec3( + mx_bits_to_01(mx_hash_int(ix, iy, iz, 0)), + mx_bits_to_01(mx_hash_int(ix, iy, iz, 1)), + mx_bits_to_01(mx_hash_int(ix, iy, iz, 2)) + ); +} + +vec3 mx_cell_noise_vec3(vec4 p) +{ + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + int iz = mx_floor(p.z); + int iw = mx_floor(p.w); + return vec3( + mx_bits_to_01(mx_hash_int(ix, iy, iz, iw, 0)), + mx_bits_to_01(mx_hash_int(ix, iy, iz, iw, 1)), + mx_bits_to_01(mx_hash_int(ix, iy, iz, iw, 2)) + ); +} + +float mx_fractal_noise_float(vec3 p, int octaves, float lacunarity, float diminish) +{ + float result = 0.0; + float amplitude = 1.0; + for (int i = 0; i < octaves; ++i) + { + result += amplitude * mx_perlin_noise_float(p); + amplitude *= diminish; + p *= lacunarity; + } + return result; +} + +vec3 mx_fractal_noise_vec3(vec3 p, int octaves, float lacunarity, float diminish) +{ + vec3 result = vec3(0.0); + float amplitude = 1.0; + for (int i = 0; i < octaves; ++i) + { + result += amplitude * mx_perlin_noise_vec3(p); + amplitude *= diminish; + p *= lacunarity; + } + return result; +} + +vec2 mx_fractal_noise_vec2(vec3 p, int octaves, float lacunarity, float diminish) +{ + return vec2(mx_fractal_noise_float(p, octaves, lacunarity, diminish), + mx_fractal_noise_float(p+vec3(19, 193, 17), octaves, lacunarity, diminish)); +} + +vec4 mx_fractal_noise_vec4(vec3 p, int octaves, float lacunarity, float diminish) +{ + vec3 c = mx_fractal_noise_vec3(p, octaves, lacunarity, diminish); + float f = mx_fractal_noise_float(p+vec3(19, 193, 17), octaves, lacunarity, diminish); + return vec4(c, f); +} + +float mx_worley_distance(vec2 p, int x, int y, int xoff, int yoff, float jitter, int metric) +{ + vec3 tmp = mx_cell_noise_vec3(vec2(x+xoff, y+yoff)); + vec2 off = vec2(tmp.x, tmp.y); + + off -= 0.5f; + off *= jitter; + off += 0.5f; + + vec2 cellpos = vec2(float(x), float(y)) + off; + vec2 diff = cellpos - p; + if (metric == 2) + return abs(diff.x) + abs(diff.y); // Manhattan distance + if (metric == 3) + return max(abs(diff.x), abs(diff.y)); // Chebyshev distance + // Either Euclidian or Distance^2 + return dot(diff, diff); +} + +float mx_worley_distance(vec3 p, int x, int y, int z, int xoff, int yoff, int zoff, float jitter, int metric) +{ + vec3 off = mx_cell_noise_vec3(vec3(x+xoff, y+yoff, z+zoff)); + + off -= 0.5f; + off *= jitter; + off += 0.5f; + + vec3 cellpos = vec3(float(x), float(y), float(z)) + off; + vec3 diff = cellpos - p; + if (metric == 2) + return abs(diff.x) + abs(diff.y) + abs(diff.z); // Manhattan distance + if (metric == 3) + return max(max(abs(diff.x), abs(diff.y)), abs(diff.z)); // Chebyshev distance + // Either Euclidian or Distance^2 + return dot(diff, diff); +} + +float mx_worley_noise_float(vec2 p, float jitter, int metric) +{ + int X, Y; + vec2 localpos = vec2(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y)); + float sqdist = 1e6f; // Some big number for jitter > 1 (not all GPUs may be IEEE) + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + float dist = mx_worley_distance(localpos, x, y, X, Y, jitter, metric); + sqdist = min(sqdist, dist); + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; +} + +vec2 mx_worley_noise_vec2(vec2 p, float jitter, int metric) +{ + int X, Y; + vec2 localpos = vec2(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y)); + vec2 sqdist = vec2(1e6f, 1e6f); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + float dist = mx_worley_distance(localpos, x, y, X, Y, jitter, metric); + if (dist < sqdist.x) + { + sqdist.y = sqdist.x; + sqdist.x = dist; + } + else if (dist < sqdist.y) + { + sqdist.y = dist; + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; +} + +vec3 mx_worley_noise_vec3(vec2 p, float jitter, int metric) +{ + int X, Y; + vec2 localpos = vec2(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y)); + vec3 sqdist = vec3(1e6f, 1e6f, 1e6f); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + float dist = mx_worley_distance(localpos, x, y, X, Y, jitter, metric); + if (dist < sqdist.x) + { + sqdist.z = sqdist.y; + sqdist.y = sqdist.x; + sqdist.x = dist; + } + else if (dist < sqdist.y) + { + sqdist.z = sqdist.y; + sqdist.y = dist; + } + else if (dist < sqdist.z) + { + sqdist.z = dist; + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; +} + +float mx_worley_noise_float(vec3 p, float jitter, int metric) +{ + int X, Y, Z; + vec3 localpos = vec3(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y), mx_floorfrac(p.z, Z)); + float sqdist = 1e6f; + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + for (int z = -1; z <= 1; ++z) + { + float dist = mx_worley_distance(localpos, x, y, z, X, Y, Z, jitter, metric); + sqdist = min(sqdist, dist); + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; +} + +vec2 mx_worley_noise_vec2(vec3 p, float jitter, int metric) +{ + int X, Y, Z; + vec3 localpos = vec3(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y), mx_floorfrac(p.z, Z)); + vec2 sqdist = vec2(1e6f, 1e6f); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + for (int z = -1; z <= 1; ++z) + { + float dist = mx_worley_distance(localpos, x, y, z, X, Y, Z, jitter, metric); + if (dist < sqdist.x) + { + sqdist.y = sqdist.x; + sqdist.x = dist; + } + else if (dist < sqdist.y) + { + sqdist.y = dist; + } + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; +} + +vec3 mx_worley_noise_vec3(vec3 p, float jitter, int metric) +{ + int X, Y, Z; + vec3 localpos = vec3(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y), mx_floorfrac(p.z, Z)); + vec3 sqdist = vec3(1e6f, 1e6f, 1e6f); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + for (int z = -1; z <= 1; ++z) + { + float dist = mx_worley_distance(localpos, x, y, z, X, Y, Z, jitter, metric); + if (dist < sqdist.x) + { + sqdist.z = sqdist.y; + sqdist.y = sqdist.x; + sqdist.x = dist; + } + else if (dist < sqdist.y) + { + sqdist.z = sqdist.y; + sqdist.y = dist; + } + else if (dist < sqdist.z) + { + sqdist.z = dist; + } + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; +} + +void mx_fractal3d_float(float amplitude, int octaves, float lacunarity, float diminish, vec3 position, out float result) +{ + float value = mx_fractal_noise_float(position, octaves, lacunarity, diminish); + result = value * amplitude; +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec3 obj_pos_out = vd.positionObject; + float add_xyz_out = dot(obj_pos_out, add_xyz_in2); + vec3 scale_pos_out = obj_pos_out * scale_pos_in2; + float scale_xyz_out = add_xyz_out * scale_xyz_in2; + float noise_out = 0.0; + mx_fractal3d_float(noise_amplitude, noise_octaves, noise_lacunarity, noise_diminish, scale_pos_out, noise_out); + float scale_noise_out = noise_out * scale_noise_in2; + float sum_out = scale_xyz_out + scale_noise_out; + float sin_out = mx_sin(sum_out); + float scale_out = sin_out * scale_in2; + float bias_out = scale_out + bias_in2; + float power_out = pow(bias_out, power_in2); + vec3 color_mix_out = mix(color_mix_bg, color_mix_fg, power_out); + surfaceshader SR_marble1_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_marble1_base, color_mix_out, SR_marble1_diffuse_roughness, SR_marble1_metalness, SR_marble1_specular, SR_marble1_specular_color, SR_marble1_specular_roughness, SR_marble1_specular_IOR, SR_marble1_specular_anisotropy, SR_marble1_specular_rotation, SR_marble1_transmission, SR_marble1_transmission_color, SR_marble1_transmission_depth, SR_marble1_transmission_scatter, SR_marble1_transmission_scatter_anisotropy, SR_marble1_transmission_dispersion, SR_marble1_transmission_extra_roughness, SR_marble1_subsurface, color_mix_out, SR_marble1_subsurface_radius, SR_marble1_subsurface_scale, SR_marble1_subsurface_anisotropy, SR_marble1_sheen, SR_marble1_sheen_color, SR_marble1_sheen_roughness, SR_marble1_coat, SR_marble1_coat_color, SR_marble1_coat_roughness, SR_marble1_coat_anisotropy, SR_marble1_coat_rotation, SR_marble1_coat_IOR, geomprop_Nworld_out1, SR_marble1_coat_affect_color, SR_marble1_coat_affect_roughness, SR_marble1_thin_film_thickness, SR_marble1_thin_film_IOR, SR_marble1_emission, SR_marble1_emission_color, SR_marble1_opacity, SR_marble1_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_marble1_out); + material Marble_3D_out = SR_marble1_out; + out1 = vec4(Marble_3D_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Marble_3D.glsl.vert b/Materials/Examples/StandardSurface/Marble_3D.glsl.vert new file mode 100644 index 0000000000..3cbd72ff83 --- /dev/null +++ b/Materials/Examples/StandardSurface/Marble_3D.glsl.vert @@ -0,0 +1,30 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionObject; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionObject = i_position; + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Marble_3D.mdl b/Materials/Examples/StandardSurface/Marble_3D.mdl new file mode 100644 index 0000000000..d51f8dfde2 --- /dev/null +++ b/Materials/Examples/StandardSurface/Marble_3D.mdl @@ -0,0 +1,377 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Marble_3D +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform mx_coordinatespace_type obj_pos_space = mx_coordinatespace_type_object + [[ + materialx::core::origin("NG_marble1/obj_pos/space") + ]], + float3 add_xyz_in2 = float3(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("NG_marble1/add_xyz/in2") + ]], + float scale_pos_in2 = 4.000000 + [[ + materialx::core::origin("NG_marble1/noise_scale_2") + ]], + float scale_xyz_in2 = 6.000000 + [[ + materialx::core::origin("NG_marble1/noise_scale_1") + ]], + float noise_amplitude = 1.000000 + [[ + materialx::core::origin("NG_marble1/noise/amplitude") + ]], + int noise_octaves = 3 + [[ + materialx::core::origin("NG_marble1/noise_octaves") + ]], + float noise_lacunarity = 2.000000 + [[ + materialx::core::origin("NG_marble1/noise/lacunarity") + ]], + float noise_diminish = 0.500000 + [[ + materialx::core::origin("NG_marble1/noise/diminish") + ]], + float scale_noise_in2 = 3.000000 + [[ + materialx::core::origin("NG_marble1/scale_noise/in2") + ]], + float scale_in2 = 0.500000 + [[ + materialx::core::origin("NG_marble1/scale/in2") + ]], + float bias_in2 = 0.500000 + [[ + materialx::core::origin("NG_marble1/bias/in2") + ]], + float power_in2 = 3.000000 + [[ + materialx::core::origin("NG_marble1/noise_power") + ]], + color color_mix_fg = color(0.100000, 0.100000, 0.300000) + [[ + materialx::core::origin("NG_marble1/base_color_2") + ]], + color color_mix_bg = color(0.800000, 0.800000, 0.800000) + [[ + materialx::core::origin("NG_marble1/base_color_1") + ]], + float SR_marble1_base = 1.000000 + [[ + materialx::core::origin("SR_marble1/base") + ]], + float SR_marble1_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_marble1/diffuse_roughness") + ]], + float SR_marble1_metalness = 0.000000 + [[ + materialx::core::origin("SR_marble1/metalness") + ]], + float SR_marble1_specular = 1.000000 + [[ + materialx::core::origin("SR_marble1/specular") + ]], + color SR_marble1_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_marble1/specular_color") + ]], + float SR_marble1_specular_roughness = 0.100000 + [[ + materialx::core::origin("SR_marble1/specular_roughness") + ]], + uniform float SR_marble1_specular_IOR = 1.500000 + [[ + materialx::core::origin("SR_marble1/specular_IOR") + ]], + float SR_marble1_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_marble1/specular_anisotropy") + ]], + float SR_marble1_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_marble1/specular_rotation") + ]], + float SR_marble1_transmission = 0.000000 + [[ + materialx::core::origin("SR_marble1/transmission") + ]], + color SR_marble1_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_marble1/transmission_color") + ]], + float SR_marble1_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_marble1/transmission_depth") + ]], + color SR_marble1_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_marble1/transmission_scatter") + ]], + float SR_marble1_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_marble1/transmission_scatter_anisotropy") + ]], + float SR_marble1_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_marble1/transmission_dispersion") + ]], + float SR_marble1_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_marble1/transmission_extra_roughness") + ]], + float SR_marble1_subsurface = 0.400000 + [[ + materialx::core::origin("SR_marble1/subsurface") + ]], + color SR_marble1_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_marble1/subsurface_radius") + ]], + float SR_marble1_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_marble1/subsurface_scale") + ]], + float SR_marble1_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_marble1/subsurface_anisotropy") + ]], + float SR_marble1_sheen = 0.000000 + [[ + materialx::core::origin("SR_marble1/sheen") + ]], + color SR_marble1_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_marble1/sheen_color") + ]], + float SR_marble1_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_marble1/sheen_roughness") + ]], + float SR_marble1_coat = 0.000000 + [[ + materialx::core::origin("SR_marble1/coat") + ]], + color SR_marble1_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_marble1/coat_color") + ]], + float SR_marble1_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_marble1/coat_roughness") + ]], + float SR_marble1_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_marble1/coat_anisotropy") + ]], + float SR_marble1_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_marble1/coat_rotation") + ]], + uniform float SR_marble1_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_marble1/coat_IOR") + ]], + float SR_marble1_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_marble1/coat_affect_color") + ]], + float SR_marble1_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_marble1/coat_affect_roughness") + ]], + float SR_marble1_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_marble1/thin_film_thickness") + ]], + float SR_marble1_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_marble1/thin_film_IOR") + ]], + float SR_marble1_emission = 0.000000 + [[ + materialx::core::origin("SR_marble1/emission") + ]], + color SR_marble1_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_marble1/emission_color") + ]], + color SR_marble1_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_marble1/opacity") + ]], + bool SR_marble1_thin_walled = false + [[ + materialx::core::origin("SR_marble1/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float3 obj_pos_out = materialx::stdlib_1_8::mx_position_vector3(mxp_space:obj_pos_space); + float add_xyz_out = math::dot(obj_pos_out, add_xyz_in2); + float3 scale_pos_out = obj_pos_out * scale_pos_in2; + float scale_xyz_out = add_xyz_out * scale_xyz_in2; + float noise_out = materialx::stdlib_1_8::mx_fractal3d_float(mxp_amplitude:noise_amplitude, mxp_octaves:noise_octaves, mxp_lacunarity:noise_lacunarity, mxp_diminish:noise_diminish, mxp_position:scale_pos_out); + float scale_noise_out = noise_out * scale_noise_in2; + float sum_out = scale_xyz_out + scale_noise_out; + float sin_out = math::sin(sum_out); + float scale_out = sin_out * scale_in2; + float bias_out = scale_out + bias_in2; + float power_out = math::pow(bias_out, power_in2); + color color_mix_out = math::lerp(color_mix_bg, color_mix_fg, power_out); + material SR_marble1_out = NG_standard_surface_surfaceshader_100(SR_marble1_base, color_mix_out, SR_marble1_diffuse_roughness, SR_marble1_metalness, SR_marble1_specular, SR_marble1_specular_color, SR_marble1_specular_roughness, SR_marble1_specular_IOR, SR_marble1_specular_anisotropy, SR_marble1_specular_rotation, SR_marble1_transmission, SR_marble1_transmission_color, SR_marble1_transmission_depth, SR_marble1_transmission_scatter, SR_marble1_transmission_scatter_anisotropy, SR_marble1_transmission_dispersion, SR_marble1_transmission_extra_roughness, SR_marble1_subsurface, color_mix_out, SR_marble1_subsurface_radius, SR_marble1_subsurface_scale, SR_marble1_subsurface_anisotropy, SR_marble1_sheen, SR_marble1_sheen_color, SR_marble1_sheen_roughness, SR_marble1_coat, SR_marble1_coat_color, SR_marble1_coat_roughness, SR_marble1_coat_anisotropy, SR_marble1_coat_rotation, SR_marble1_coat_IOR, geomprop_Nworld_out1, SR_marble1_coat_affect_color, SR_marble1_coat_affect_roughness, SR_marble1_thin_film_thickness, SR_marble1_thin_film_IOR, SR_marble1_emission, SR_marble1_emission_color, SR_marble1_opacity, SR_marble1_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Marble_3D_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_marble1_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Marble_3D_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Marble_3D.msl.frag b/Materials/Examples/StandardSurface/Marble_3D.msl.frag new file mode 100644 index 0000000000..7da495ca1d --- /dev/null +++ b/Materials/Examples/StandardSurface/Marble_3D.msl.frag @@ -0,0 +1,3262 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + vec3 add_xyz_in2; + float scale_pos_in2; + float scale_xyz_in2; + float noise_amplitude; + int noise_octaves; + float noise_lacunarity; + float noise_diminish; + float scale_noise_in2; + float scale_in2; + float bias_in2; + float power_in2; + vec3 color_mix_fg; + vec3 color_mix_bg; + float SR_marble1_base; + float SR_marble1_diffuse_roughness; + float SR_marble1_metalness; + float SR_marble1_specular; + vec3 SR_marble1_specular_color; + float SR_marble1_specular_roughness; + float SR_marble1_specular_IOR; + float SR_marble1_specular_anisotropy; + float SR_marble1_specular_rotation; + float SR_marble1_transmission; + vec3 SR_marble1_transmission_color; + float SR_marble1_transmission_depth; + vec3 SR_marble1_transmission_scatter; + float SR_marble1_transmission_scatter_anisotropy; + float SR_marble1_transmission_dispersion; + float SR_marble1_transmission_extra_roughness; + float SR_marble1_subsurface; + vec3 SR_marble1_subsurface_radius; + float SR_marble1_subsurface_scale; + float SR_marble1_subsurface_anisotropy; + float SR_marble1_sheen; + vec3 SR_marble1_sheen_color; + float SR_marble1_sheen_roughness; + float SR_marble1_coat; + vec3 SR_marble1_coat_color; + float SR_marble1_coat_roughness; + float SR_marble1_coat_anisotropy; + float SR_marble1_coat_rotation; + float SR_marble1_coat_IOR; + float SR_marble1_coat_affect_color; + float SR_marble1_coat_affect_roughness; + float SR_marble1_thin_film_thickness; + float SR_marble1_thin_film_IOR; + float SR_marble1_emission; + vec3 SR_marble1_emission_color; + vec3 SR_marble1_opacity; + bool SR_marble1_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionObject ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , vec3 add_xyz_in2 + + , float scale_pos_in2 + + , float scale_xyz_in2 + + , float noise_amplitude + + , int noise_octaves + + , float noise_lacunarity + + , float noise_diminish + + , float scale_noise_in2 + + , float scale_in2 + + , float bias_in2 + + , float power_in2 + + , vec3 color_mix_fg + + , vec3 color_mix_bg + + , float SR_marble1_base + + , float SR_marble1_diffuse_roughness + + , float SR_marble1_metalness + + , float SR_marble1_specular + + , vec3 SR_marble1_specular_color + + , float SR_marble1_specular_roughness + + , float SR_marble1_specular_IOR + + , float SR_marble1_specular_anisotropy + + , float SR_marble1_specular_rotation + + , float SR_marble1_transmission + + , vec3 SR_marble1_transmission_color + + , float SR_marble1_transmission_depth + + , vec3 SR_marble1_transmission_scatter + + , float SR_marble1_transmission_scatter_anisotropy + + , float SR_marble1_transmission_dispersion + + , float SR_marble1_transmission_extra_roughness + + , float SR_marble1_subsurface + + , vec3 SR_marble1_subsurface_radius + + , float SR_marble1_subsurface_scale + + , float SR_marble1_subsurface_anisotropy + + , float SR_marble1_sheen + + , vec3 SR_marble1_sheen_color + + , float SR_marble1_sheen_roughness + + , float SR_marble1_coat + + , vec3 SR_marble1_coat_color + + , float SR_marble1_coat_roughness + + , float SR_marble1_coat_anisotropy + + , float SR_marble1_coat_rotation + + , float SR_marble1_coat_IOR + + , float SR_marble1_coat_affect_color + + , float SR_marble1_coat_affect_roughness + + , float SR_marble1_thin_film_thickness + + , float SR_marble1_thin_film_IOR + + , float SR_marble1_emission + + , vec3 SR_marble1_emission_color + + , vec3 SR_marble1_opacity + + , bool SR_marble1_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , add_xyz_in2(add_xyz_in2) + + , scale_pos_in2(scale_pos_in2) + + , scale_xyz_in2(scale_xyz_in2) + + , noise_amplitude(noise_amplitude) + + , noise_octaves(noise_octaves) + + , noise_lacunarity(noise_lacunarity) + + , noise_diminish(noise_diminish) + + , scale_noise_in2(scale_noise_in2) + + , scale_in2(scale_in2) + + , bias_in2(bias_in2) + + , power_in2(power_in2) + + , color_mix_fg(color_mix_fg) + + , color_mix_bg(color_mix_bg) + + , SR_marble1_base(SR_marble1_base) + + , SR_marble1_diffuse_roughness(SR_marble1_diffuse_roughness) + + , SR_marble1_metalness(SR_marble1_metalness) + + , SR_marble1_specular(SR_marble1_specular) + + , SR_marble1_specular_color(SR_marble1_specular_color) + + , SR_marble1_specular_roughness(SR_marble1_specular_roughness) + + , SR_marble1_specular_IOR(SR_marble1_specular_IOR) + + , SR_marble1_specular_anisotropy(SR_marble1_specular_anisotropy) + + , SR_marble1_specular_rotation(SR_marble1_specular_rotation) + + , SR_marble1_transmission(SR_marble1_transmission) + + , SR_marble1_transmission_color(SR_marble1_transmission_color) + + , SR_marble1_transmission_depth(SR_marble1_transmission_depth) + + , SR_marble1_transmission_scatter(SR_marble1_transmission_scatter) + + , SR_marble1_transmission_scatter_anisotropy(SR_marble1_transmission_scatter_anisotropy) + + , SR_marble1_transmission_dispersion(SR_marble1_transmission_dispersion) + + , SR_marble1_transmission_extra_roughness(SR_marble1_transmission_extra_roughness) + + , SR_marble1_subsurface(SR_marble1_subsurface) + + , SR_marble1_subsurface_radius(SR_marble1_subsurface_radius) + + , SR_marble1_subsurface_scale(SR_marble1_subsurface_scale) + + , SR_marble1_subsurface_anisotropy(SR_marble1_subsurface_anisotropy) + + , SR_marble1_sheen(SR_marble1_sheen) + + , SR_marble1_sheen_color(SR_marble1_sheen_color) + + , SR_marble1_sheen_roughness(SR_marble1_sheen_roughness) + + , SR_marble1_coat(SR_marble1_coat) + + , SR_marble1_coat_color(SR_marble1_coat_color) + + , SR_marble1_coat_roughness(SR_marble1_coat_roughness) + + , SR_marble1_coat_anisotropy(SR_marble1_coat_anisotropy) + + , SR_marble1_coat_rotation(SR_marble1_coat_rotation) + + , SR_marble1_coat_IOR(SR_marble1_coat_IOR) + + , SR_marble1_coat_affect_color(SR_marble1_coat_affect_color) + + , SR_marble1_coat_affect_roughness(SR_marble1_coat_affect_roughness) + + , SR_marble1_thin_film_thickness(SR_marble1_thin_film_thickness) + + , SR_marble1_thin_film_IOR(SR_marble1_thin_film_IOR) + + , SR_marble1_emission(SR_marble1_emission) + + , SR_marble1_emission_color(SR_marble1_emission_color) + + , SR_marble1_opacity(SR_marble1_opacity) + + , SR_marble1_thin_walled(SR_marble1_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + vec3 add_xyz_in2; + + + float scale_pos_in2; + + + float scale_xyz_in2; + + + float noise_amplitude; + + + int noise_octaves; + + + float noise_lacunarity; + + + float noise_diminish; + + + float scale_noise_in2; + + + float scale_in2; + + + float bias_in2; + + + float power_in2; + + + vec3 color_mix_fg; + + + vec3 color_mix_bg; + + + float SR_marble1_base; + + + float SR_marble1_diffuse_roughness; + + + float SR_marble1_metalness; + + + float SR_marble1_specular; + + + vec3 SR_marble1_specular_color; + + + float SR_marble1_specular_roughness; + + + float SR_marble1_specular_IOR; + + + float SR_marble1_specular_anisotropy; + + + float SR_marble1_specular_rotation; + + + float SR_marble1_transmission; + + + vec3 SR_marble1_transmission_color; + + + float SR_marble1_transmission_depth; + + + vec3 SR_marble1_transmission_scatter; + + + float SR_marble1_transmission_scatter_anisotropy; + + + float SR_marble1_transmission_dispersion; + + + float SR_marble1_transmission_extra_roughness; + + + float SR_marble1_subsurface; + + + vec3 SR_marble1_subsurface_radius; + + + float SR_marble1_subsurface_scale; + + + float SR_marble1_subsurface_anisotropy; + + + float SR_marble1_sheen; + + + vec3 SR_marble1_sheen_color; + + + float SR_marble1_sheen_roughness; + + + float SR_marble1_coat; + + + vec3 SR_marble1_coat_color; + + + float SR_marble1_coat_roughness; + + + float SR_marble1_coat_anisotropy; + + + float SR_marble1_coat_rotation; + + + float SR_marble1_coat_IOR; + + + float SR_marble1_coat_affect_color; + + + float SR_marble1_coat_affect_roughness; + + + float SR_marble1_thin_film_thickness; + + + float SR_marble1_thin_film_IOR; + + + float SR_marble1_emission; + + + vec3 SR_marble1_emission_color; + + + vec3 SR_marble1_opacity; + + + bool SR_marble1_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + /* + Noise Library. + + This library is a modified version of the noise library found in + Open Shading Language: + github.com/imageworks/OpenShadingLanguage/blob/master/src/include/OSL/oslnoise.h + + It contains the subset of noise types needed to implement the MaterialX + standard library. The modifications are mainly conversions from C++ to GLSL. + Produced results should be identical to the OSL noise functions. + + Original copyright notice: + ------------------------------------------------------------------------ + Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. + All Rights Reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Sony Pictures Imageworks nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ------------------------------------------------------------------------ + */ + + float mx_select(bool b, float t, float f) + { + return b ? t : f; + } + + float mx_negate_if(float val, bool b) + { + return b ? -val : val; + } + + int mx_floor(float x) + { + return int(floor(x)); + } + + // return mx_floor as well as the fractional remainder + float mx_floorfrac(float x, thread int& i) + { + i = mx_floor(x); + return x - float(i); + } + + float mx_bilerp(float v0, float v1, float v2, float v3, float s, float t) + { + float s1 = 1.0 - s; + return (1.0 - t) * (v0*s1 + v1*s) + t * (v2*s1 + v3*s); + } + vec3 mx_bilerp(vec3 v0, vec3 v1, vec3 v2, vec3 v3, float s, float t) + { + float s1 = 1.0 - s; + return (1.0 - t) * (v0*s1 + v1*s) + t * (v2*s1 + v3*s); + } + float mx_trilerp(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7, float s, float t, float r) + { + float s1 = 1.0 - s; + float t1 = 1.0 - t; + float r1 = 1.0 - r; + return (r1*(t1*(v0*s1 + v1*s) + t*(v2*s1 + v3*s)) + + r*(t1*(v4*s1 + v5*s) + t*(v6*s1 + v7*s))); + } + vec3 mx_trilerp(vec3 v0, vec3 v1, vec3 v2, vec3 v3, vec3 v4, vec3 v5, vec3 v6, vec3 v7, float s, float t, float r) + { + float s1 = 1.0 - s; + float t1 = 1.0 - t; + float r1 = 1.0 - r; + return (r1*(t1*(v0*s1 + v1*s) + t*(v2*s1 + v3*s)) + + r*(t1*(v4*s1 + v5*s) + t*(v6*s1 + v7*s))); + } + + // 2 and 3 dimensional gradient functions - perform a dot product against a + // randomly chosen vector. Note that the gradient vector is not normalized, but + // this only affects the overal "scale" of the result, so we simply account for + // the scale by multiplying in the corresponding "perlin" function. + float mx_gradient_float(uint hash, float x, float y) + { + // 8 possible directions (+-1,+-2) and (+-2,+-1) + uint h = hash & 7u; + float u = mx_select(h<4u, x, y); + float v = 2.0 * mx_select(h<4u, y, x); + // compute the dot product with (x,y). + return mx_negate_if(u, bool(h&1u)) + mx_negate_if(v, bool(h&2u)); + } + float mx_gradient_float(uint hash, float x, float y, float z) + { + // use vectors pointing to the edges of the cube + uint h = hash & 15u; + float u = mx_select(h<8u, x, y); + float v = mx_select(h<4u, y, mx_select((h==12u)||(h==14u), x, z)); + return mx_negate_if(u, bool(h&1u)) + mx_negate_if(v, bool(h&2u)); + } + vec3 mx_gradient_vec3(uvec3 hash, float x, float y) + { + return vec3(mx_gradient_float(hash.x, x, y), mx_gradient_float(hash.y, x, y), mx_gradient_float(hash.z, x, y)); + } + vec3 mx_gradient_vec3(uvec3 hash, float x, float y, float z) + { + return vec3(mx_gradient_float(hash.x, x, y, z), mx_gradient_float(hash.y, x, y, z), mx_gradient_float(hash.z, x, y, z)); + } + // Scaling factors to normalize the result of gradients above. + // These factors were experimentally calculated to be: + // 2D: 0.6616 + // 3D: 0.9820 + float mx_gradient_scale2d(float v) { return 0.6616 * v; } + float mx_gradient_scale3d(float v) { return 0.9820 * v; } + vec3 mx_gradient_scale2d(vec3 v) { return 0.6616 * v; } + vec3 mx_gradient_scale3d(vec3 v) { return 0.9820 * v; } + + /// Bitwise circular rotation left by k bits (for 32 bit unsigned integers) + uint mx_rotl32(uint x, int k) + { + return (x<>(32-k)); + } + + void mx_bjmix(thread uint& a, thread uint& b, thread uint& c) + { + a -= c; a ^= mx_rotl32(c, 4); c += b; + b -= a; b ^= mx_rotl32(a, 6); a += c; + c -= b; c ^= mx_rotl32(b, 8); b += a; + a -= c; a ^= mx_rotl32(c,16); c += b; + b -= a; b ^= mx_rotl32(a,19); a += c; + c -= b; c ^= mx_rotl32(b, 4); b += a; + } + + // Mix up and combine the bits of a, b, and c (doesn't change them, but + // returns a hash of those three original values). + uint mx_bjfinal(uint a, uint b, uint c) + { + c ^= b; c -= mx_rotl32(b,14); + a ^= c; a -= mx_rotl32(c,11); + b ^= a; b -= mx_rotl32(a,25); + c ^= b; c -= mx_rotl32(b,16); + a ^= c; a -= mx_rotl32(c,4); + b ^= a; b -= mx_rotl32(a,14); + c ^= b; c -= mx_rotl32(b,24); + return c; + } + + // Convert a 32 bit integer into a floating point number in [0,1] + float mx_bits_to_01(uint bits) + { + return float(bits) / float(uint(0xffffffff)); + } + + float mx_fade(float t) + { + return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); + } + + uint mx_hash_int(int x) + { + uint len = 1u; + uint seed = uint(0xdeadbeef) + (len << 2u) + 13u; + return mx_bjfinal(seed+uint(x), seed, seed); + } + + uint mx_hash_int(int x, int y) + { + uint len = 2u; + uint a, b, c; + a = b = c = uint(0xdeadbeef) + (len << 2u) + 13u; + a += uint(x); + b += uint(y); + return mx_bjfinal(a, b, c); + } + + uint mx_hash_int(int x, int y, int z) + { + uint len = 3u; + uint a, b, c; + a = b = c = uint(0xdeadbeef) + (len << 2u) + 13u; + a += uint(x); + b += uint(y); + c += uint(z); + return mx_bjfinal(a, b, c); + } + + uint mx_hash_int(int x, int y, int z, int xx) + { + uint len = 4u; + uint a, b, c; + a = b = c = uint(0xdeadbeef) + (len << 2u) + 13u; + a += uint(x); + b += uint(y); + c += uint(z); + mx_bjmix(a, b, c); + a += uint(xx); + return mx_bjfinal(a, b, c); + } + + uint mx_hash_int(int x, int y, int z, int xx, int yy) + { + uint len = 5u; + uint a, b, c; + a = b = c = uint(0xdeadbeef) + (len << 2u) + 13u; + a += uint(x); + b += uint(y); + c += uint(z); + mx_bjmix(a, b, c); + a += uint(xx); + b += uint(yy); + return mx_bjfinal(a, b, c); + } + + uvec3 mx_hash_vec3(int x, int y) + { + uint h = mx_hash_int(x, y); + // we only need the low-order bits to be random, so split out + // the 32 bit result into 3 parts for each channel + uvec3 result; + result.x = (h ) & 0xFFu; + result.y = (h >> 8 ) & 0xFFu; + result.z = (h >> 16) & 0xFFu; + return result; + } + + uvec3 mx_hash_vec3(int x, int y, int z) + { + uint h = mx_hash_int(x, y, z); + // we only need the low-order bits to be random, so split out + // the 32 bit result into 3 parts for each channel + uvec3 result; + result.x = (h ) & 0xFFu; + result.y = (h >> 8 ) & 0xFFu; + result.z = (h >> 16) & 0xFFu; + return result; + } + + float mx_perlin_noise_float(vec2 p) + { + int X, Y; + float fx = mx_floorfrac(p.x, X); + float fy = mx_floorfrac(p.y, Y); + float u = mx_fade(fx); + float v = mx_fade(fy); + float result = mx_bilerp( + mx_gradient_float(mx_hash_int(X , Y ), fx , fy ), + mx_gradient_float(mx_hash_int(X+1, Y ), fx-1.0, fy ), + mx_gradient_float(mx_hash_int(X , Y+1), fx , fy-1.0), + mx_gradient_float(mx_hash_int(X+1, Y+1), fx-1.0, fy-1.0), + u, v); + return mx_gradient_scale2d(result); + } + + float mx_perlin_noise_float(vec3 p) + { + int X, Y, Z; + float fx = mx_floorfrac(p.x, X); + float fy = mx_floorfrac(p.y, Y); + float fz = mx_floorfrac(p.z, Z); + float u = mx_fade(fx); + float v = mx_fade(fy); + float w = mx_fade(fz); + float result = mx_trilerp( + mx_gradient_float(mx_hash_int(X , Y , Z ), fx , fy , fz ), + mx_gradient_float(mx_hash_int(X+1, Y , Z ), fx-1.0, fy , fz ), + mx_gradient_float(mx_hash_int(X , Y+1, Z ), fx , fy-1.0, fz ), + mx_gradient_float(mx_hash_int(X+1, Y+1, Z ), fx-1.0, fy-1.0, fz ), + mx_gradient_float(mx_hash_int(X , Y , Z+1), fx , fy , fz-1.0), + mx_gradient_float(mx_hash_int(X+1, Y , Z+1), fx-1.0, fy , fz-1.0), + mx_gradient_float(mx_hash_int(X , Y+1, Z+1), fx , fy-1.0, fz-1.0), + mx_gradient_float(mx_hash_int(X+1, Y+1, Z+1), fx-1.0, fy-1.0, fz-1.0), + u, v, w); + return mx_gradient_scale3d(result); + } + + vec3 mx_perlin_noise_vec3(vec2 p) + { + int X, Y; + float fx = mx_floorfrac(p.x, X); + float fy = mx_floorfrac(p.y, Y); + float u = mx_fade(fx); + float v = mx_fade(fy); + vec3 result = mx_bilerp( + mx_gradient_vec3(mx_hash_vec3(X , Y ), fx , fy ), + mx_gradient_vec3(mx_hash_vec3(X+1, Y ), fx-1.0, fy ), + mx_gradient_vec3(mx_hash_vec3(X , Y+1), fx , fy-1.0), + mx_gradient_vec3(mx_hash_vec3(X+1, Y+1), fx-1.0, fy-1.0), + u, v); + return mx_gradient_scale2d(result); + } + + vec3 mx_perlin_noise_vec3(vec3 p) + { + int X, Y, Z; + float fx = mx_floorfrac(p.x, X); + float fy = mx_floorfrac(p.y, Y); + float fz = mx_floorfrac(p.z, Z); + float u = mx_fade(fx); + float v = mx_fade(fy); + float w = mx_fade(fz); + vec3 result = mx_trilerp( + mx_gradient_vec3(mx_hash_vec3(X , Y , Z ), fx , fy , fz ), + mx_gradient_vec3(mx_hash_vec3(X+1, Y , Z ), fx-1.0, fy , fz ), + mx_gradient_vec3(mx_hash_vec3(X , Y+1, Z ), fx , fy-1.0, fz ), + mx_gradient_vec3(mx_hash_vec3(X+1, Y+1, Z ), fx-1.0, fy-1.0, fz ), + mx_gradient_vec3(mx_hash_vec3(X , Y , Z+1), fx , fy , fz-1.0), + mx_gradient_vec3(mx_hash_vec3(X+1, Y , Z+1), fx-1.0, fy , fz-1.0), + mx_gradient_vec3(mx_hash_vec3(X , Y+1, Z+1), fx , fy-1.0, fz-1.0), + mx_gradient_vec3(mx_hash_vec3(X+1, Y+1, Z+1), fx-1.0, fy-1.0, fz-1.0), + u, v, w); + return mx_gradient_scale3d(result); + } + + float mx_cell_noise_float(float p) + { + int ix = mx_floor(p); + return mx_bits_to_01(mx_hash_int(ix)); + } + + float mx_cell_noise_float(vec2 p) + { + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + return mx_bits_to_01(mx_hash_int(ix, iy)); + } + + float mx_cell_noise_float(vec3 p) + { + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + int iz = mx_floor(p.z); + return mx_bits_to_01(mx_hash_int(ix, iy, iz)); + } + + float mx_cell_noise_float(vec4 p) + { + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + int iz = mx_floor(p.z); + int iw = mx_floor(p.w); + return mx_bits_to_01(mx_hash_int(ix, iy, iz, iw)); + } + + vec3 mx_cell_noise_vec3(float p) + { + int ix = mx_floor(p); + return vec3( + mx_bits_to_01(mx_hash_int(ix, 0)), + mx_bits_to_01(mx_hash_int(ix, 1)), + mx_bits_to_01(mx_hash_int(ix, 2)) + ); + } + + vec3 mx_cell_noise_vec3(vec2 p) + { + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + return vec3( + mx_bits_to_01(mx_hash_int(ix, iy, 0)), + mx_bits_to_01(mx_hash_int(ix, iy, 1)), + mx_bits_to_01(mx_hash_int(ix, iy, 2)) + ); + } + + vec3 mx_cell_noise_vec3(vec3 p) + { + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + int iz = mx_floor(p.z); + return vec3( + mx_bits_to_01(mx_hash_int(ix, iy, iz, 0)), + mx_bits_to_01(mx_hash_int(ix, iy, iz, 1)), + mx_bits_to_01(mx_hash_int(ix, iy, iz, 2)) + ); + } + + vec3 mx_cell_noise_vec3(vec4 p) + { + int ix = mx_floor(p.x); + int iy = mx_floor(p.y); + int iz = mx_floor(p.z); + int iw = mx_floor(p.w); + return vec3( + mx_bits_to_01(mx_hash_int(ix, iy, iz, iw, 0)), + mx_bits_to_01(mx_hash_int(ix, iy, iz, iw, 1)), + mx_bits_to_01(mx_hash_int(ix, iy, iz, iw, 2)) + ); + } + + float mx_fractal_noise_float(vec3 p, int octaves, float lacunarity, float diminish) + { + float result = 0.0; + float amplitude = 1.0; + for (int i = 0; i < octaves; ++i) + { + result += amplitude * mx_perlin_noise_float(p); + amplitude *= diminish; + p *= lacunarity; + } + return result; + } + + vec3 mx_fractal_noise_vec3(vec3 p, int octaves, float lacunarity, float diminish) + { + vec3 result = vec3(0.0); + float amplitude = 1.0; + for (int i = 0; i < octaves; ++i) + { + result += amplitude * mx_perlin_noise_vec3(p); + amplitude *= diminish; + p *= lacunarity; + } + return result; + } + + vec2 mx_fractal_noise_vec2(vec3 p, int octaves, float lacunarity, float diminish) + { + return vec2(mx_fractal_noise_float(p, octaves, lacunarity, diminish), + mx_fractal_noise_float(p+vec3(19, 193, 17), octaves, lacunarity, diminish)); + } + + vec4 mx_fractal_noise_vec4(vec3 p, int octaves, float lacunarity, float diminish) + { + vec3 c = mx_fractal_noise_vec3(p, octaves, lacunarity, diminish); + float f = mx_fractal_noise_float(p+vec3(19, 193, 17), octaves, lacunarity, diminish); + return vec4(c, f); + } + + float mx_worley_distance(vec2 p, int x, int y, int xoff, int yoff, float jitter, int metric) + { + vec3 tmp = mx_cell_noise_vec3(vec2(x+xoff, y+yoff)); + vec2 off = vec2(tmp.x, tmp.y); + + off -= 0.5f; + off *= jitter; + off += 0.5f; + + vec2 cellpos = vec2(float(x), float(y)) + off; + vec2 diff = cellpos - p; + if (metric == 2) + return abs(diff.x) + abs(diff.y); // Manhattan distance + if (metric == 3) + return max(abs(diff.x), abs(diff.y)); // Chebyshev distance + // Either Euclidian or Distance^2 + return dot(diff, diff); + } + + float mx_worley_distance(vec3 p, int x, int y, int z, int xoff, int yoff, int zoff, float jitter, int metric) + { + vec3 off = mx_cell_noise_vec3(vec3(x+xoff, y+yoff, z+zoff)); + + off -= 0.5f; + off *= jitter; + off += 0.5f; + + vec3 cellpos = vec3(float(x), float(y), float(z)) + off; + vec3 diff = cellpos - p; + if (metric == 2) + return abs(diff.x) + abs(diff.y) + abs(diff.z); // Manhattan distance + if (metric == 3) + return max(max(abs(diff.x), abs(diff.y)), abs(diff.z)); // Chebyshev distance + // Either Euclidian or Distance^2 + return dot(diff, diff); + } + + float mx_worley_noise_float(vec2 p, float jitter, int metric) + { + int X, Y; + vec2 localpos = vec2(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y)); + float sqdist = 1e6f; // Some big number for jitter > 1 (not all GPUs may be IEEE) + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + float dist = mx_worley_distance(localpos, x, y, X, Y, jitter, metric); + sqdist = min(sqdist, dist); + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; + } + + vec2 mx_worley_noise_vec2(vec2 p, float jitter, int metric) + { + int X, Y; + vec2 localpos = vec2(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y)); + vec2 sqdist = vec2(1e6f, 1e6f); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + float dist = mx_worley_distance(localpos, x, y, X, Y, jitter, metric); + if (dist < sqdist.x) + { + sqdist.y = sqdist.x; + sqdist.x = dist; + } + else if (dist < sqdist.y) + { + sqdist.y = dist; + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; + } + + vec3 mx_worley_noise_vec3(vec2 p, float jitter, int metric) + { + int X, Y; + vec2 localpos = vec2(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y)); + vec3 sqdist = vec3(1e6f, 1e6f, 1e6f); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + float dist = mx_worley_distance(localpos, x, y, X, Y, jitter, metric); + if (dist < sqdist.x) + { + sqdist.z = sqdist.y; + sqdist.y = sqdist.x; + sqdist.x = dist; + } + else if (dist < sqdist.y) + { + sqdist.z = sqdist.y; + sqdist.y = dist; + } + else if (dist < sqdist.z) + { + sqdist.z = dist; + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; + } + + float mx_worley_noise_float(vec3 p, float jitter, int metric) + { + int X, Y, Z; + vec3 localpos = vec3(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y), mx_floorfrac(p.z, Z)); + float sqdist = 1e6f; + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + for (int z = -1; z <= 1; ++z) + { + float dist = mx_worley_distance(localpos, x, y, z, X, Y, Z, jitter, metric); + sqdist = min(sqdist, dist); + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; + } + + vec2 mx_worley_noise_vec2(vec3 p, float jitter, int metric) + { + int X, Y, Z; + vec3 localpos = vec3(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y), mx_floorfrac(p.z, Z)); + vec2 sqdist = vec2(1e6f, 1e6f); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + for (int z = -1; z <= 1; ++z) + { + float dist = mx_worley_distance(localpos, x, y, z, X, Y, Z, jitter, metric); + if (dist < sqdist.x) + { + sqdist.y = sqdist.x; + sqdist.x = dist; + } + else if (dist < sqdist.y) + { + sqdist.y = dist; + } + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; + } + + vec3 mx_worley_noise_vec3(vec3 p, float jitter, int metric) + { + int X, Y, Z; + vec3 localpos = vec3(mx_floorfrac(p.x, X), mx_floorfrac(p.y, Y), mx_floorfrac(p.z, Z)); + vec3 sqdist = vec3(1e6f, 1e6f, 1e6f); + for (int x = -1; x <= 1; ++x) + { + for (int y = -1; y <= 1; ++y) + { + for (int z = -1; z <= 1; ++z) + { + float dist = mx_worley_distance(localpos, x, y, z, X, Y, Z, jitter, metric); + if (dist < sqdist.x) + { + sqdist.z = sqdist.y; + sqdist.y = sqdist.x; + sqdist.x = dist; + } + else if (dist < sqdist.y) + { + sqdist.z = sqdist.y; + sqdist.y = dist; + } + else if (dist < sqdist.z) + { + sqdist.z = dist; + } + } + } + } + if (metric == 0) + sqdist = sqrt(sqdist); + return sqdist; + } + + void mx_fractal3d_float(float amplitude, int octaves, float lacunarity, float diminish, vec3 position, thread float& result) + { + float value = mx_fractal_noise_float(position, octaves, lacunarity, diminish); + result = value * amplitude; + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec3 obj_pos_out = vd.positionObject; + float add_xyz_out = dot(obj_pos_out, add_xyz_in2); + vec3 scale_pos_out = obj_pos_out * scale_pos_in2; + float scale_xyz_out = add_xyz_out * scale_xyz_in2; + float noise_out = 0.0; + mx_fractal3d_float(noise_amplitude, noise_octaves, noise_lacunarity, noise_diminish, scale_pos_out, noise_out); + float scale_noise_out = noise_out * scale_noise_in2; + float sum_out = scale_xyz_out + scale_noise_out; + float sin_out = mx_sin(sum_out); + float scale_out = sin_out * scale_in2; + float bias_out = scale_out + bias_in2; + float power_out = pow(bias_out, power_in2); + vec3 color_mix_out = mix(color_mix_bg, color_mix_fg, power_out); + surfaceshader SR_marble1_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_marble1_base, color_mix_out, SR_marble1_diffuse_roughness, SR_marble1_metalness, SR_marble1_specular, SR_marble1_specular_color, SR_marble1_specular_roughness, SR_marble1_specular_IOR, SR_marble1_specular_anisotropy, SR_marble1_specular_rotation, SR_marble1_transmission, SR_marble1_transmission_color, SR_marble1_transmission_depth, SR_marble1_transmission_scatter, SR_marble1_transmission_scatter_anisotropy, SR_marble1_transmission_dispersion, SR_marble1_transmission_extra_roughness, SR_marble1_subsurface, color_mix_out, SR_marble1_subsurface_radius, SR_marble1_subsurface_scale, SR_marble1_subsurface_anisotropy, SR_marble1_sheen, SR_marble1_sheen_color, SR_marble1_sheen_roughness, SR_marble1_coat, SR_marble1_coat_color, SR_marble1_coat_roughness, SR_marble1_coat_anisotropy, SR_marble1_coat_rotation, SR_marble1_coat_IOR, geomprop_Nworld_out1, SR_marble1_coat_affect_color, SR_marble1_coat_affect_roughness, SR_marble1_thin_film_thickness, SR_marble1_thin_film_IOR, SR_marble1_emission, SR_marble1_emission_color, SR_marble1_opacity, SR_marble1_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_marble1_out); + material Marble_3D_out = SR_marble1_out; + out1 = float4(Marble_3D_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.add_xyz_in2 + , u_pub.scale_pos_in2 + , u_pub.scale_xyz_in2 + , u_pub.noise_amplitude + , u_pub.noise_octaves + , u_pub.noise_lacunarity + , u_pub.noise_diminish + , u_pub.scale_noise_in2 + , u_pub.scale_in2 + , u_pub.bias_in2 + , u_pub.power_in2 + , u_pub.color_mix_fg + , u_pub.color_mix_bg + , u_pub.SR_marble1_base + , u_pub.SR_marble1_diffuse_roughness + , u_pub.SR_marble1_metalness + , u_pub.SR_marble1_specular + , u_pub.SR_marble1_specular_color + , u_pub.SR_marble1_specular_roughness + , u_pub.SR_marble1_specular_IOR + , u_pub.SR_marble1_specular_anisotropy + , u_pub.SR_marble1_specular_rotation + , u_pub.SR_marble1_transmission + , u_pub.SR_marble1_transmission_color + , u_pub.SR_marble1_transmission_depth + , u_pub.SR_marble1_transmission_scatter + , u_pub.SR_marble1_transmission_scatter_anisotropy + , u_pub.SR_marble1_transmission_dispersion + , u_pub.SR_marble1_transmission_extra_roughness + , u_pub.SR_marble1_subsurface + , u_pub.SR_marble1_subsurface_radius + , u_pub.SR_marble1_subsurface_scale + , u_pub.SR_marble1_subsurface_anisotropy + , u_pub.SR_marble1_sheen + , u_pub.SR_marble1_sheen_color + , u_pub.SR_marble1_sheen_roughness + , u_pub.SR_marble1_coat + , u_pub.SR_marble1_coat_color + , u_pub.SR_marble1_coat_roughness + , u_pub.SR_marble1_coat_anisotropy + , u_pub.SR_marble1_coat_rotation + , u_pub.SR_marble1_coat_IOR + , u_pub.SR_marble1_coat_affect_color + , u_pub.SR_marble1_coat_affect_roughness + , u_pub.SR_marble1_thin_film_thickness + , u_pub.SR_marble1_thin_film_IOR + , u_pub.SR_marble1_emission + , u_pub.SR_marble1_emission_color + , u_pub.SR_marble1_opacity + , u_pub.SR_marble1_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Marble_3D.msl.vert b/Materials/Examples/StandardSurface/Marble_3D.msl.vert new file mode 100644 index 0000000000..2ff3bcc37a --- /dev/null +++ b/Materials/Examples/StandardSurface/Marble_3D.msl.vert @@ -0,0 +1,124 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionObject; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionObject = i_position; + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'obj_pos'. Function already called in this scope. + // Omitted node 'add_xyz'. Function already called in this scope. + // Omitted node 'scale_pos'. Function already called in this scope. + // Omitted node 'scale_xyz'. Function already called in this scope. + // Omitted node 'noise'. Function already called in this scope. + // Omitted node 'scale_noise'. Function already called in this scope. + // Omitted node 'sum'. Function already called in this scope. + // Omitted node 'sin'. Function already called in this scope. + // Omitted node 'scale'. Function already called in this scope. + // Omitted node 'bias'. Function already called in this scope. + // Omitted node 'power'. Function already called in this scope. + // Omitted node 'color_mix'. Function already called in this scope. + // Omitted node 'SR_marble1'. Function already called in this scope. + // Omitted node 'Marble_3D'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Marble_3D.osl b/Materials/Examples/StandardSurface/Marble_3D.osl new file mode 100644 index 0000000000..fdee646db1 --- /dev/null +++ b/Materials/Examples/StandardSurface/Marble_3D.osl @@ -0,0 +1,518 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_fractal3d_float(float amplitude, int octaves, float lacunarity, float diminish, vector position, output float result) +{ + float f = mx_fbm(position, octaves, lacunarity, diminish, "snoise"); + result = f * amplitude; +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Marble_3D +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Marble_3D" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + string obj_pos_space = "object", + vector add_xyz_in2 = vector(1.000000, 1.000000, 1.000000), + float scale_pos_in2 = 4.000000 + [[ + string widget = "number" + ]], + float scale_xyz_in2 = 6.000000 + [[ + string widget = "number" + ]], + float noise_amplitude = 1.000000 + [[ + string widget = "number" + ]], + int noise_octaves = 3 + [[ + string widget = "number" + ]], + float noise_lacunarity = 2.000000 + [[ + string widget = "number" + ]], + float noise_diminish = 0.500000 + [[ + string widget = "number" + ]], + float scale_noise_in2 = 3.000000 + [[ + string widget = "number" + ]], + float scale_in2 = 0.500000 + [[ + string widget = "number" + ]], + float bias_in2 = 0.500000 + [[ + string widget = "number" + ]], + float power_in2 = 3.000000 + [[ + string widget = "number" + ]], + color color_mix_fg = color(0.100000, 0.100000, 0.300000), + color color_mix_bg = color(0.800000, 0.800000, 0.800000), + float SR_marble1_base = 1.000000 + [[ + string widget = "number" + ]], + float SR_marble1_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_metalness = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_specular = 1.000000 + [[ + string widget = "number" + ]], + color SR_marble1_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_marble1_specular_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_marble1_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_marble1_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_marble1_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_marble1_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_marble1_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_marble1_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_subsurface = 0.400000 + [[ + string widget = "number" + ]], + color SR_marble1_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_marble1_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_marble1_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_marble1_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_marble1_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_marble1_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_marble1_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_marble1_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_marble1_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_marble1_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_marble1_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_marble1_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_marble1_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_marble1_opacity = color(1.000000, 1.000000, 1.000000), + int SR_marble1_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector obj_pos_out = transform(obj_pos_space, P); + float add_xyz_out = dot(obj_pos_out, add_xyz_in2); + vector scale_pos_out = obj_pos_out * scale_pos_in2; + float scale_xyz_out = add_xyz_out * scale_xyz_in2; + float noise_out = 0.0; + mx_fractal3d_float(noise_amplitude, noise_octaves, noise_lacunarity, noise_diminish, scale_pos_out, noise_out); + float scale_noise_out = noise_out * scale_noise_in2; + float sum_out = scale_xyz_out + scale_noise_out; + float sin_out = sin(sum_out); + float scale_out = sin_out * scale_in2; + float bias_out = scale_out + bias_in2; + float power_out = pow(bias_out, power_in2); + color color_mix_out = mix(color_mix_bg, color_mix_fg, power_out); + surfaceshader SR_marble1_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_marble1_base, color_mix_out, SR_marble1_diffuse_roughness, SR_marble1_metalness, SR_marble1_specular, SR_marble1_specular_color, SR_marble1_specular_roughness, SR_marble1_specular_IOR, SR_marble1_specular_anisotropy, SR_marble1_specular_rotation, SR_marble1_transmission, SR_marble1_transmission_color, SR_marble1_transmission_depth, SR_marble1_transmission_scatter, SR_marble1_transmission_scatter_anisotropy, SR_marble1_transmission_dispersion, SR_marble1_transmission_extra_roughness, SR_marble1_subsurface, color_mix_out, SR_marble1_subsurface_radius, SR_marble1_subsurface_scale, SR_marble1_subsurface_anisotropy, SR_marble1_sheen, SR_marble1_sheen_color, SR_marble1_sheen_roughness, SR_marble1_coat, SR_marble1_coat_color, SR_marble1_coat_roughness, SR_marble1_coat_anisotropy, SR_marble1_coat_rotation, SR_marble1_coat_IOR, geomprop_Nworld_out1, SR_marble1_coat_affect_color, SR_marble1_coat_affect_roughness, SR_marble1_thin_film_thickness, SR_marble1_thin_film_IOR, SR_marble1_emission, SR_marble1_emission_color, SR_marble1_opacity, SR_marble1_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_marble1_out); + MATERIAL Marble_3D_out = mx_surfacematerial(SR_marble1_out, backsurfaceshader, displacementshader1); + out = Marble_3D_out; +} + diff --git a/Materials/Examples/StandardSurface/Metal_Brushed.glsl.frag b/Materials/Examples/StandardSurface/Metal_Brushed.glsl.frag new file mode 100644 index 0000000000..c24bfb64f9 --- /dev/null +++ b/Materials/Examples/StandardSurface/Metal_Brushed.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_metal_brushed_base = 1.000000; +uniform vec3 SR_metal_brushed_base_color = vec3(0.500000, 0.500000, 0.500000); +uniform float SR_metal_brushed_diffuse_roughness = 0.000000; +uniform float SR_metal_brushed_metalness = 1.000000; +uniform float SR_metal_brushed_specular = 0.000000; +uniform vec3 SR_metal_brushed_specular_color = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_metal_brushed_specular_roughness = 0.250000; +uniform float SR_metal_brushed_specular_IOR = 1.520000; +uniform float SR_metal_brushed_specular_anisotropy = 0.650000; +uniform float SR_metal_brushed_specular_rotation = 0.000000; +uniform float SR_metal_brushed_transmission = 0.000000; +uniform vec3 SR_metal_brushed_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_metal_brushed_transmission_depth = 0.000000; +uniform vec3 SR_metal_brushed_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_metal_brushed_transmission_scatter_anisotropy = 0.000000; +uniform float SR_metal_brushed_transmission_dispersion = 0.000000; +uniform float SR_metal_brushed_transmission_extra_roughness = 0.000000; +uniform float SR_metal_brushed_subsurface = 0.000000; +uniform vec3 SR_metal_brushed_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_metal_brushed_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_metal_brushed_subsurface_scale = 1.000000; +uniform float SR_metal_brushed_subsurface_anisotropy = 0.000000; +uniform float SR_metal_brushed_sheen = 0.000000; +uniform vec3 SR_metal_brushed_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_metal_brushed_sheen_roughness = 0.300000; +uniform float SR_metal_brushed_coat = 0.000000; +uniform vec3 SR_metal_brushed_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_metal_brushed_coat_roughness = 0.100000; +uniform float SR_metal_brushed_coat_anisotropy = 0.000000; +uniform float SR_metal_brushed_coat_rotation = 0.000000; +uniform float SR_metal_brushed_coat_IOR = 1.500000; +uniform float SR_metal_brushed_coat_affect_color = 0.000000; +uniform float SR_metal_brushed_coat_affect_roughness = 0.000000; +uniform float SR_metal_brushed_thin_film_thickness = 0.000000; +uniform float SR_metal_brushed_thin_film_IOR = 1.500000; +uniform float SR_metal_brushed_emission = 0.000000; +uniform vec3 SR_metal_brushed_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_metal_brushed_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_metal_brushed_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_metal_brushed_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_metal_brushed_base, SR_metal_brushed_base_color, SR_metal_brushed_diffuse_roughness, SR_metal_brushed_metalness, SR_metal_brushed_specular, SR_metal_brushed_specular_color, SR_metal_brushed_specular_roughness, SR_metal_brushed_specular_IOR, SR_metal_brushed_specular_anisotropy, SR_metal_brushed_specular_rotation, SR_metal_brushed_transmission, SR_metal_brushed_transmission_color, SR_metal_brushed_transmission_depth, SR_metal_brushed_transmission_scatter, SR_metal_brushed_transmission_scatter_anisotropy, SR_metal_brushed_transmission_dispersion, SR_metal_brushed_transmission_extra_roughness, SR_metal_brushed_subsurface, SR_metal_brushed_subsurface_color, SR_metal_brushed_subsurface_radius, SR_metal_brushed_subsurface_scale, SR_metal_brushed_subsurface_anisotropy, SR_metal_brushed_sheen, SR_metal_brushed_sheen_color, SR_metal_brushed_sheen_roughness, SR_metal_brushed_coat, SR_metal_brushed_coat_color, SR_metal_brushed_coat_roughness, SR_metal_brushed_coat_anisotropy, SR_metal_brushed_coat_rotation, SR_metal_brushed_coat_IOR, geomprop_Nworld_out1, SR_metal_brushed_coat_affect_color, SR_metal_brushed_coat_affect_roughness, SR_metal_brushed_thin_film_thickness, SR_metal_brushed_thin_film_IOR, SR_metal_brushed_emission, SR_metal_brushed_emission_color, SR_metal_brushed_opacity, SR_metal_brushed_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_metal_brushed_out); + material Metal_Brushed_out = SR_metal_brushed_out; + out1 = vec4(Metal_Brushed_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Metal_Brushed.glsl.vert b/Materials/Examples/StandardSurface/Metal_Brushed.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/Metal_Brushed.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Metal_Brushed.mdl b/Materials/Examples/StandardSurface/Metal_Brushed.mdl new file mode 100644 index 0000000000..6d9704e2aa --- /dev/null +++ b/Materials/Examples/StandardSurface/Metal_Brushed.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Metal_Brushed +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_metal_brushed_base = 1.000000 + [[ + materialx::core::origin("SR_metal_brushed/base") + ]], + color SR_metal_brushed_base_color = color(0.500000, 0.500000, 0.500000) + [[ + materialx::core::origin("SR_metal_brushed/base_color") + ]], + float SR_metal_brushed_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/diffuse_roughness") + ]], + float SR_metal_brushed_metalness = 1.000000 + [[ + materialx::core::origin("SR_metal_brushed/metalness") + ]], + float SR_metal_brushed_specular = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/specular") + ]], + color SR_metal_brushed_specular_color = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_metal_brushed/specular_color") + ]], + float SR_metal_brushed_specular_roughness = 0.250000 + [[ + materialx::core::origin("SR_metal_brushed/specular_roughness") + ]], + uniform float SR_metal_brushed_specular_IOR = 1.520000 + [[ + materialx::core::origin("SR_metal_brushed/specular_IOR") + ]], + float SR_metal_brushed_specular_anisotropy = 0.650000 + [[ + materialx::core::origin("SR_metal_brushed/specular_anisotropy") + ]], + float SR_metal_brushed_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/specular_rotation") + ]], + float SR_metal_brushed_transmission = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/transmission") + ]], + color SR_metal_brushed_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_metal_brushed/transmission_color") + ]], + float SR_metal_brushed_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/transmission_depth") + ]], + color SR_metal_brushed_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_metal_brushed/transmission_scatter") + ]], + float SR_metal_brushed_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/transmission_scatter_anisotropy") + ]], + float SR_metal_brushed_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/transmission_dispersion") + ]], + float SR_metal_brushed_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/transmission_extra_roughness") + ]], + float SR_metal_brushed_subsurface = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/subsurface") + ]], + color SR_metal_brushed_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_metal_brushed/subsurface_color") + ]], + color SR_metal_brushed_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_metal_brushed/subsurface_radius") + ]], + float SR_metal_brushed_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_metal_brushed/subsurface_scale") + ]], + float SR_metal_brushed_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/subsurface_anisotropy") + ]], + float SR_metal_brushed_sheen = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/sheen") + ]], + color SR_metal_brushed_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_metal_brushed/sheen_color") + ]], + float SR_metal_brushed_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_metal_brushed/sheen_roughness") + ]], + float SR_metal_brushed_coat = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/coat") + ]], + color SR_metal_brushed_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_metal_brushed/coat_color") + ]], + float SR_metal_brushed_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_metal_brushed/coat_roughness") + ]], + float SR_metal_brushed_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/coat_anisotropy") + ]], + float SR_metal_brushed_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/coat_rotation") + ]], + uniform float SR_metal_brushed_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_metal_brushed/coat_IOR") + ]], + float SR_metal_brushed_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/coat_affect_color") + ]], + float SR_metal_brushed_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/coat_affect_roughness") + ]], + float SR_metal_brushed_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/thin_film_thickness") + ]], + float SR_metal_brushed_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_metal_brushed/thin_film_IOR") + ]], + float SR_metal_brushed_emission = 0.000000 + [[ + materialx::core::origin("SR_metal_brushed/emission") + ]], + color SR_metal_brushed_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_metal_brushed/emission_color") + ]], + color SR_metal_brushed_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_metal_brushed/opacity") + ]], + bool SR_metal_brushed_thin_walled = false + [[ + materialx::core::origin("SR_metal_brushed/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_metal_brushed_out = NG_standard_surface_surfaceshader_100(SR_metal_brushed_base, SR_metal_brushed_base_color, SR_metal_brushed_diffuse_roughness, SR_metal_brushed_metalness, SR_metal_brushed_specular, SR_metal_brushed_specular_color, SR_metal_brushed_specular_roughness, SR_metal_brushed_specular_IOR, SR_metal_brushed_specular_anisotropy, SR_metal_brushed_specular_rotation, SR_metal_brushed_transmission, SR_metal_brushed_transmission_color, SR_metal_brushed_transmission_depth, SR_metal_brushed_transmission_scatter, SR_metal_brushed_transmission_scatter_anisotropy, SR_metal_brushed_transmission_dispersion, SR_metal_brushed_transmission_extra_roughness, SR_metal_brushed_subsurface, SR_metal_brushed_subsurface_color, SR_metal_brushed_subsurface_radius, SR_metal_brushed_subsurface_scale, SR_metal_brushed_subsurface_anisotropy, SR_metal_brushed_sheen, SR_metal_brushed_sheen_color, SR_metal_brushed_sheen_roughness, SR_metal_brushed_coat, SR_metal_brushed_coat_color, SR_metal_brushed_coat_roughness, SR_metal_brushed_coat_anisotropy, SR_metal_brushed_coat_rotation, SR_metal_brushed_coat_IOR, geomprop_Nworld_out1, SR_metal_brushed_coat_affect_color, SR_metal_brushed_coat_affect_roughness, SR_metal_brushed_thin_film_thickness, SR_metal_brushed_thin_film_IOR, SR_metal_brushed_emission, SR_metal_brushed_emission_color, SR_metal_brushed_opacity, SR_metal_brushed_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Metal_Brushed_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_metal_brushed_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Metal_Brushed_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Metal_Brushed.msl.frag b/Materials/Examples/StandardSurface/Metal_Brushed.msl.frag new file mode 100644 index 0000000000..d57d0ace01 --- /dev/null +++ b/Materials/Examples/StandardSurface/Metal_Brushed.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_metal_brushed_base; + vec3 SR_metal_brushed_base_color; + float SR_metal_brushed_diffuse_roughness; + float SR_metal_brushed_metalness; + float SR_metal_brushed_specular; + vec3 SR_metal_brushed_specular_color; + float SR_metal_brushed_specular_roughness; + float SR_metal_brushed_specular_IOR; + float SR_metal_brushed_specular_anisotropy; + float SR_metal_brushed_specular_rotation; + float SR_metal_brushed_transmission; + vec3 SR_metal_brushed_transmission_color; + float SR_metal_brushed_transmission_depth; + vec3 SR_metal_brushed_transmission_scatter; + float SR_metal_brushed_transmission_scatter_anisotropy; + float SR_metal_brushed_transmission_dispersion; + float SR_metal_brushed_transmission_extra_roughness; + float SR_metal_brushed_subsurface; + vec3 SR_metal_brushed_subsurface_color; + vec3 SR_metal_brushed_subsurface_radius; + float SR_metal_brushed_subsurface_scale; + float SR_metal_brushed_subsurface_anisotropy; + float SR_metal_brushed_sheen; + vec3 SR_metal_brushed_sheen_color; + float SR_metal_brushed_sheen_roughness; + float SR_metal_brushed_coat; + vec3 SR_metal_brushed_coat_color; + float SR_metal_brushed_coat_roughness; + float SR_metal_brushed_coat_anisotropy; + float SR_metal_brushed_coat_rotation; + float SR_metal_brushed_coat_IOR; + float SR_metal_brushed_coat_affect_color; + float SR_metal_brushed_coat_affect_roughness; + float SR_metal_brushed_thin_film_thickness; + float SR_metal_brushed_thin_film_IOR; + float SR_metal_brushed_emission; + vec3 SR_metal_brushed_emission_color; + vec3 SR_metal_brushed_opacity; + bool SR_metal_brushed_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_metal_brushed_base + + , vec3 SR_metal_brushed_base_color + + , float SR_metal_brushed_diffuse_roughness + + , float SR_metal_brushed_metalness + + , float SR_metal_brushed_specular + + , vec3 SR_metal_brushed_specular_color + + , float SR_metal_brushed_specular_roughness + + , float SR_metal_brushed_specular_IOR + + , float SR_metal_brushed_specular_anisotropy + + , float SR_metal_brushed_specular_rotation + + , float SR_metal_brushed_transmission + + , vec3 SR_metal_brushed_transmission_color + + , float SR_metal_brushed_transmission_depth + + , vec3 SR_metal_brushed_transmission_scatter + + , float SR_metal_brushed_transmission_scatter_anisotropy + + , float SR_metal_brushed_transmission_dispersion + + , float SR_metal_brushed_transmission_extra_roughness + + , float SR_metal_brushed_subsurface + + , vec3 SR_metal_brushed_subsurface_color + + , vec3 SR_metal_brushed_subsurface_radius + + , float SR_metal_brushed_subsurface_scale + + , float SR_metal_brushed_subsurface_anisotropy + + , float SR_metal_brushed_sheen + + , vec3 SR_metal_brushed_sheen_color + + , float SR_metal_brushed_sheen_roughness + + , float SR_metal_brushed_coat + + , vec3 SR_metal_brushed_coat_color + + , float SR_metal_brushed_coat_roughness + + , float SR_metal_brushed_coat_anisotropy + + , float SR_metal_brushed_coat_rotation + + , float SR_metal_brushed_coat_IOR + + , float SR_metal_brushed_coat_affect_color + + , float SR_metal_brushed_coat_affect_roughness + + , float SR_metal_brushed_thin_film_thickness + + , float SR_metal_brushed_thin_film_IOR + + , float SR_metal_brushed_emission + + , vec3 SR_metal_brushed_emission_color + + , vec3 SR_metal_brushed_opacity + + , bool SR_metal_brushed_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_metal_brushed_base(SR_metal_brushed_base) + + , SR_metal_brushed_base_color(SR_metal_brushed_base_color) + + , SR_metal_brushed_diffuse_roughness(SR_metal_brushed_diffuse_roughness) + + , SR_metal_brushed_metalness(SR_metal_brushed_metalness) + + , SR_metal_brushed_specular(SR_metal_brushed_specular) + + , SR_metal_brushed_specular_color(SR_metal_brushed_specular_color) + + , SR_metal_brushed_specular_roughness(SR_metal_brushed_specular_roughness) + + , SR_metal_brushed_specular_IOR(SR_metal_brushed_specular_IOR) + + , SR_metal_brushed_specular_anisotropy(SR_metal_brushed_specular_anisotropy) + + , SR_metal_brushed_specular_rotation(SR_metal_brushed_specular_rotation) + + , SR_metal_brushed_transmission(SR_metal_brushed_transmission) + + , SR_metal_brushed_transmission_color(SR_metal_brushed_transmission_color) + + , SR_metal_brushed_transmission_depth(SR_metal_brushed_transmission_depth) + + , SR_metal_brushed_transmission_scatter(SR_metal_brushed_transmission_scatter) + + , SR_metal_brushed_transmission_scatter_anisotropy(SR_metal_brushed_transmission_scatter_anisotropy) + + , SR_metal_brushed_transmission_dispersion(SR_metal_brushed_transmission_dispersion) + + , SR_metal_brushed_transmission_extra_roughness(SR_metal_brushed_transmission_extra_roughness) + + , SR_metal_brushed_subsurface(SR_metal_brushed_subsurface) + + , SR_metal_brushed_subsurface_color(SR_metal_brushed_subsurface_color) + + , SR_metal_brushed_subsurface_radius(SR_metal_brushed_subsurface_radius) + + , SR_metal_brushed_subsurface_scale(SR_metal_brushed_subsurface_scale) + + , SR_metal_brushed_subsurface_anisotropy(SR_metal_brushed_subsurface_anisotropy) + + , SR_metal_brushed_sheen(SR_metal_brushed_sheen) + + , SR_metal_brushed_sheen_color(SR_metal_brushed_sheen_color) + + , SR_metal_brushed_sheen_roughness(SR_metal_brushed_sheen_roughness) + + , SR_metal_brushed_coat(SR_metal_brushed_coat) + + , SR_metal_brushed_coat_color(SR_metal_brushed_coat_color) + + , SR_metal_brushed_coat_roughness(SR_metal_brushed_coat_roughness) + + , SR_metal_brushed_coat_anisotropy(SR_metal_brushed_coat_anisotropy) + + , SR_metal_brushed_coat_rotation(SR_metal_brushed_coat_rotation) + + , SR_metal_brushed_coat_IOR(SR_metal_brushed_coat_IOR) + + , SR_metal_brushed_coat_affect_color(SR_metal_brushed_coat_affect_color) + + , SR_metal_brushed_coat_affect_roughness(SR_metal_brushed_coat_affect_roughness) + + , SR_metal_brushed_thin_film_thickness(SR_metal_brushed_thin_film_thickness) + + , SR_metal_brushed_thin_film_IOR(SR_metal_brushed_thin_film_IOR) + + , SR_metal_brushed_emission(SR_metal_brushed_emission) + + , SR_metal_brushed_emission_color(SR_metal_brushed_emission_color) + + , SR_metal_brushed_opacity(SR_metal_brushed_opacity) + + , SR_metal_brushed_thin_walled(SR_metal_brushed_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_metal_brushed_base; + + + vec3 SR_metal_brushed_base_color; + + + float SR_metal_brushed_diffuse_roughness; + + + float SR_metal_brushed_metalness; + + + float SR_metal_brushed_specular; + + + vec3 SR_metal_brushed_specular_color; + + + float SR_metal_brushed_specular_roughness; + + + float SR_metal_brushed_specular_IOR; + + + float SR_metal_brushed_specular_anisotropy; + + + float SR_metal_brushed_specular_rotation; + + + float SR_metal_brushed_transmission; + + + vec3 SR_metal_brushed_transmission_color; + + + float SR_metal_brushed_transmission_depth; + + + vec3 SR_metal_brushed_transmission_scatter; + + + float SR_metal_brushed_transmission_scatter_anisotropy; + + + float SR_metal_brushed_transmission_dispersion; + + + float SR_metal_brushed_transmission_extra_roughness; + + + float SR_metal_brushed_subsurface; + + + vec3 SR_metal_brushed_subsurface_color; + + + vec3 SR_metal_brushed_subsurface_radius; + + + float SR_metal_brushed_subsurface_scale; + + + float SR_metal_brushed_subsurface_anisotropy; + + + float SR_metal_brushed_sheen; + + + vec3 SR_metal_brushed_sheen_color; + + + float SR_metal_brushed_sheen_roughness; + + + float SR_metal_brushed_coat; + + + vec3 SR_metal_brushed_coat_color; + + + float SR_metal_brushed_coat_roughness; + + + float SR_metal_brushed_coat_anisotropy; + + + float SR_metal_brushed_coat_rotation; + + + float SR_metal_brushed_coat_IOR; + + + float SR_metal_brushed_coat_affect_color; + + + float SR_metal_brushed_coat_affect_roughness; + + + float SR_metal_brushed_thin_film_thickness; + + + float SR_metal_brushed_thin_film_IOR; + + + float SR_metal_brushed_emission; + + + vec3 SR_metal_brushed_emission_color; + + + vec3 SR_metal_brushed_opacity; + + + bool SR_metal_brushed_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_metal_brushed_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_metal_brushed_base, SR_metal_brushed_base_color, SR_metal_brushed_diffuse_roughness, SR_metal_brushed_metalness, SR_metal_brushed_specular, SR_metal_brushed_specular_color, SR_metal_brushed_specular_roughness, SR_metal_brushed_specular_IOR, SR_metal_brushed_specular_anisotropy, SR_metal_brushed_specular_rotation, SR_metal_brushed_transmission, SR_metal_brushed_transmission_color, SR_metal_brushed_transmission_depth, SR_metal_brushed_transmission_scatter, SR_metal_brushed_transmission_scatter_anisotropy, SR_metal_brushed_transmission_dispersion, SR_metal_brushed_transmission_extra_roughness, SR_metal_brushed_subsurface, SR_metal_brushed_subsurface_color, SR_metal_brushed_subsurface_radius, SR_metal_brushed_subsurface_scale, SR_metal_brushed_subsurface_anisotropy, SR_metal_brushed_sheen, SR_metal_brushed_sheen_color, SR_metal_brushed_sheen_roughness, SR_metal_brushed_coat, SR_metal_brushed_coat_color, SR_metal_brushed_coat_roughness, SR_metal_brushed_coat_anisotropy, SR_metal_brushed_coat_rotation, SR_metal_brushed_coat_IOR, geomprop_Nworld_out1, SR_metal_brushed_coat_affect_color, SR_metal_brushed_coat_affect_roughness, SR_metal_brushed_thin_film_thickness, SR_metal_brushed_thin_film_IOR, SR_metal_brushed_emission, SR_metal_brushed_emission_color, SR_metal_brushed_opacity, SR_metal_brushed_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_metal_brushed_out); + material Metal_Brushed_out = SR_metal_brushed_out; + out1 = float4(Metal_Brushed_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_metal_brushed_base + , u_pub.SR_metal_brushed_base_color + , u_pub.SR_metal_brushed_diffuse_roughness + , u_pub.SR_metal_brushed_metalness + , u_pub.SR_metal_brushed_specular + , u_pub.SR_metal_brushed_specular_color + , u_pub.SR_metal_brushed_specular_roughness + , u_pub.SR_metal_brushed_specular_IOR + , u_pub.SR_metal_brushed_specular_anisotropy + , u_pub.SR_metal_brushed_specular_rotation + , u_pub.SR_metal_brushed_transmission + , u_pub.SR_metal_brushed_transmission_color + , u_pub.SR_metal_brushed_transmission_depth + , u_pub.SR_metal_brushed_transmission_scatter + , u_pub.SR_metal_brushed_transmission_scatter_anisotropy + , u_pub.SR_metal_brushed_transmission_dispersion + , u_pub.SR_metal_brushed_transmission_extra_roughness + , u_pub.SR_metal_brushed_subsurface + , u_pub.SR_metal_brushed_subsurface_color + , u_pub.SR_metal_brushed_subsurface_radius + , u_pub.SR_metal_brushed_subsurface_scale + , u_pub.SR_metal_brushed_subsurface_anisotropy + , u_pub.SR_metal_brushed_sheen + , u_pub.SR_metal_brushed_sheen_color + , u_pub.SR_metal_brushed_sheen_roughness + , u_pub.SR_metal_brushed_coat + , u_pub.SR_metal_brushed_coat_color + , u_pub.SR_metal_brushed_coat_roughness + , u_pub.SR_metal_brushed_coat_anisotropy + , u_pub.SR_metal_brushed_coat_rotation + , u_pub.SR_metal_brushed_coat_IOR + , u_pub.SR_metal_brushed_coat_affect_color + , u_pub.SR_metal_brushed_coat_affect_roughness + , u_pub.SR_metal_brushed_thin_film_thickness + , u_pub.SR_metal_brushed_thin_film_IOR + , u_pub.SR_metal_brushed_emission + , u_pub.SR_metal_brushed_emission_color + , u_pub.SR_metal_brushed_opacity + , u_pub.SR_metal_brushed_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Metal_Brushed.msl.vert b/Materials/Examples/StandardSurface/Metal_Brushed.msl.vert new file mode 100644 index 0000000000..59f0a2fbb7 --- /dev/null +++ b/Materials/Examples/StandardSurface/Metal_Brushed.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_metal_brushed'. Function already called in this scope. + // Omitted node 'Metal_Brushed'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Metal_Brushed.osl b/Materials/Examples/StandardSurface/Metal_Brushed.osl new file mode 100644 index 0000000000..ad9f7b4062 --- /dev/null +++ b/Materials/Examples/StandardSurface/Metal_Brushed.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Metal_Brushed +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Metal_Brushed" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_metal_brushed_base = 1.000000 + [[ + string widget = "number" + ]], + color SR_metal_brushed_base_color = color(0.500000, 0.500000, 0.500000), + float SR_metal_brushed_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_metalness = 1.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_specular = 0.000000 + [[ + string widget = "number" + ]], + color SR_metal_brushed_specular_color = color(0.000000, 0.000000, 0.000000), + float SR_metal_brushed_specular_roughness = 0.250000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_specular_IOR = 1.520000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_specular_anisotropy = 0.650000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_metal_brushed_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_metal_brushed_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_metal_brushed_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_metal_brushed_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_metal_brushed_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_metal_brushed_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_metal_brushed_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_metal_brushed_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_metal_brushed_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_metal_brushed_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_metal_brushed_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_metal_brushed_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_metal_brushed_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_metal_brushed_opacity = color(1.000000, 1.000000, 1.000000), + int SR_metal_brushed_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_metal_brushed_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_metal_brushed_base, SR_metal_brushed_base_color, SR_metal_brushed_diffuse_roughness, SR_metal_brushed_metalness, SR_metal_brushed_specular, SR_metal_brushed_specular_color, SR_metal_brushed_specular_roughness, SR_metal_brushed_specular_IOR, SR_metal_brushed_specular_anisotropy, SR_metal_brushed_specular_rotation, SR_metal_brushed_transmission, SR_metal_brushed_transmission_color, SR_metal_brushed_transmission_depth, SR_metal_brushed_transmission_scatter, SR_metal_brushed_transmission_scatter_anisotropy, SR_metal_brushed_transmission_dispersion, SR_metal_brushed_transmission_extra_roughness, SR_metal_brushed_subsurface, SR_metal_brushed_subsurface_color, SR_metal_brushed_subsurface_radius, SR_metal_brushed_subsurface_scale, SR_metal_brushed_subsurface_anisotropy, SR_metal_brushed_sheen, SR_metal_brushed_sheen_color, SR_metal_brushed_sheen_roughness, SR_metal_brushed_coat, SR_metal_brushed_coat_color, SR_metal_brushed_coat_roughness, SR_metal_brushed_coat_anisotropy, SR_metal_brushed_coat_rotation, SR_metal_brushed_coat_IOR, geomprop_Nworld_out1, SR_metal_brushed_coat_affect_color, SR_metal_brushed_coat_affect_roughness, SR_metal_brushed_thin_film_thickness, SR_metal_brushed_thin_film_IOR, SR_metal_brushed_emission, SR_metal_brushed_emission_color, SR_metal_brushed_opacity, SR_metal_brushed_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_metal_brushed_out); + MATERIAL Metal_Brushed_out = mx_surfacematerial(SR_metal_brushed_out, backsurfaceshader, displacementshader1); + out = Metal_Brushed_out; +} + diff --git a/Materials/Examples/StandardSurface/Plastic.glsl.frag b/Materials/Examples/StandardSurface/Plastic.glsl.frag new file mode 100644 index 0000000000..9ca463207c --- /dev/null +++ b/Materials/Examples/StandardSurface/Plastic.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_plastic_base = 1.000000; +uniform vec3 SR_plastic_base_color = vec3(0.104704, 0.241883, 0.818000); +uniform float SR_plastic_diffuse_roughness = 0.000000; +uniform float SR_plastic_metalness = 0.000000; +uniform float SR_plastic_specular = 1.000000; +uniform vec3 SR_plastic_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_plastic_specular_roughness = 0.324675; +uniform float SR_plastic_specular_IOR = 1.500000; +uniform float SR_plastic_specular_anisotropy = 0.000000; +uniform float SR_plastic_specular_rotation = 0.000000; +uniform float SR_plastic_transmission = 0.000000; +uniform vec3 SR_plastic_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_plastic_transmission_depth = 0.000000; +uniform vec3 SR_plastic_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_plastic_transmission_scatter_anisotropy = 0.000000; +uniform float SR_plastic_transmission_dispersion = 0.000000; +uniform float SR_plastic_transmission_extra_roughness = 0.000000; +uniform float SR_plastic_subsurface = 0.000000; +uniform vec3 SR_plastic_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_plastic_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_plastic_subsurface_scale = 1.000000; +uniform float SR_plastic_subsurface_anisotropy = 0.000000; +uniform float SR_plastic_sheen = 0.000000; +uniform vec3 SR_plastic_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_plastic_sheen_roughness = 0.300000; +uniform float SR_plastic_coat = 0.000000; +uniform vec3 SR_plastic_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_plastic_coat_roughness = 0.100000; +uniform float SR_plastic_coat_anisotropy = 0.000000; +uniform float SR_plastic_coat_rotation = 0.000000; +uniform float SR_plastic_coat_IOR = 1.500000; +uniform float SR_plastic_coat_affect_color = 0.000000; +uniform float SR_plastic_coat_affect_roughness = 0.000000; +uniform float SR_plastic_thin_film_thickness = 0.000000; +uniform float SR_plastic_thin_film_IOR = 1.500000; +uniform float SR_plastic_emission = 0.000000; +uniform vec3 SR_plastic_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_plastic_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_plastic_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_plastic_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_plastic_base, SR_plastic_base_color, SR_plastic_diffuse_roughness, SR_plastic_metalness, SR_plastic_specular, SR_plastic_specular_color, SR_plastic_specular_roughness, SR_plastic_specular_IOR, SR_plastic_specular_anisotropy, SR_plastic_specular_rotation, SR_plastic_transmission, SR_plastic_transmission_color, SR_plastic_transmission_depth, SR_plastic_transmission_scatter, SR_plastic_transmission_scatter_anisotropy, SR_plastic_transmission_dispersion, SR_plastic_transmission_extra_roughness, SR_plastic_subsurface, SR_plastic_subsurface_color, SR_plastic_subsurface_radius, SR_plastic_subsurface_scale, SR_plastic_subsurface_anisotropy, SR_plastic_sheen, SR_plastic_sheen_color, SR_plastic_sheen_roughness, SR_plastic_coat, SR_plastic_coat_color, SR_plastic_coat_roughness, SR_plastic_coat_anisotropy, SR_plastic_coat_rotation, SR_plastic_coat_IOR, geomprop_Nworld_out1, SR_plastic_coat_affect_color, SR_plastic_coat_affect_roughness, SR_plastic_thin_film_thickness, SR_plastic_thin_film_IOR, SR_plastic_emission, SR_plastic_emission_color, SR_plastic_opacity, SR_plastic_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_plastic_out); + material Plastic_out = SR_plastic_out; + out1 = vec4(Plastic_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Plastic.glsl.vert b/Materials/Examples/StandardSurface/Plastic.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/Plastic.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Plastic.mdl b/Materials/Examples/StandardSurface/Plastic.mdl new file mode 100644 index 0000000000..49581eb8d3 --- /dev/null +++ b/Materials/Examples/StandardSurface/Plastic.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Plastic +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_plastic_base = 1.000000 + [[ + materialx::core::origin("SR_plastic/base") + ]], + color SR_plastic_base_color = color(0.104704, 0.241883, 0.818000) + [[ + materialx::core::origin("SR_plastic/base_color") + ]], + float SR_plastic_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_plastic/diffuse_roughness") + ]], + float SR_plastic_metalness = 0.000000 + [[ + materialx::core::origin("SR_plastic/metalness") + ]], + float SR_plastic_specular = 1.000000 + [[ + materialx::core::origin("SR_plastic/specular") + ]], + color SR_plastic_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_plastic/specular_color") + ]], + float SR_plastic_specular_roughness = 0.324675 + [[ + materialx::core::origin("SR_plastic/specular_roughness") + ]], + uniform float SR_plastic_specular_IOR = 1.500000 + [[ + materialx::core::origin("SR_plastic/specular_IOR") + ]], + float SR_plastic_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_plastic/specular_anisotropy") + ]], + float SR_plastic_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_plastic/specular_rotation") + ]], + float SR_plastic_transmission = 0.000000 + [[ + materialx::core::origin("SR_plastic/transmission") + ]], + color SR_plastic_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_plastic/transmission_color") + ]], + float SR_plastic_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_plastic/transmission_depth") + ]], + color SR_plastic_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_plastic/transmission_scatter") + ]], + float SR_plastic_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_plastic/transmission_scatter_anisotropy") + ]], + float SR_plastic_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_plastic/transmission_dispersion") + ]], + float SR_plastic_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_plastic/transmission_extra_roughness") + ]], + float SR_plastic_subsurface = 0.000000 + [[ + materialx::core::origin("SR_plastic/subsurface") + ]], + color SR_plastic_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_plastic/subsurface_color") + ]], + color SR_plastic_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_plastic/subsurface_radius") + ]], + float SR_plastic_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_plastic/subsurface_scale") + ]], + float SR_plastic_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_plastic/subsurface_anisotropy") + ]], + float SR_plastic_sheen = 0.000000 + [[ + materialx::core::origin("SR_plastic/sheen") + ]], + color SR_plastic_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_plastic/sheen_color") + ]], + float SR_plastic_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_plastic/sheen_roughness") + ]], + float SR_plastic_coat = 0.000000 + [[ + materialx::core::origin("SR_plastic/coat") + ]], + color SR_plastic_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_plastic/coat_color") + ]], + float SR_plastic_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_plastic/coat_roughness") + ]], + float SR_plastic_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_plastic/coat_anisotropy") + ]], + float SR_plastic_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_plastic/coat_rotation") + ]], + uniform float SR_plastic_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_plastic/coat_IOR") + ]], + float SR_plastic_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_plastic/coat_affect_color") + ]], + float SR_plastic_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_plastic/coat_affect_roughness") + ]], + float SR_plastic_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_plastic/thin_film_thickness") + ]], + float SR_plastic_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_plastic/thin_film_IOR") + ]], + float SR_plastic_emission = 0.000000 + [[ + materialx::core::origin("SR_plastic/emission") + ]], + color SR_plastic_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_plastic/emission_color") + ]], + color SR_plastic_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_plastic/opacity") + ]], + bool SR_plastic_thin_walled = false + [[ + materialx::core::origin("SR_plastic/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_plastic_out = NG_standard_surface_surfaceshader_100(SR_plastic_base, SR_plastic_base_color, SR_plastic_diffuse_roughness, SR_plastic_metalness, SR_plastic_specular, SR_plastic_specular_color, SR_plastic_specular_roughness, SR_plastic_specular_IOR, SR_plastic_specular_anisotropy, SR_plastic_specular_rotation, SR_plastic_transmission, SR_plastic_transmission_color, SR_plastic_transmission_depth, SR_plastic_transmission_scatter, SR_plastic_transmission_scatter_anisotropy, SR_plastic_transmission_dispersion, SR_plastic_transmission_extra_roughness, SR_plastic_subsurface, SR_plastic_subsurface_color, SR_plastic_subsurface_radius, SR_plastic_subsurface_scale, SR_plastic_subsurface_anisotropy, SR_plastic_sheen, SR_plastic_sheen_color, SR_plastic_sheen_roughness, SR_plastic_coat, SR_plastic_coat_color, SR_plastic_coat_roughness, SR_plastic_coat_anisotropy, SR_plastic_coat_rotation, SR_plastic_coat_IOR, geomprop_Nworld_out1, SR_plastic_coat_affect_color, SR_plastic_coat_affect_roughness, SR_plastic_thin_film_thickness, SR_plastic_thin_film_IOR, SR_plastic_emission, SR_plastic_emission_color, SR_plastic_opacity, SR_plastic_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Plastic_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_plastic_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Plastic_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Plastic.msl.frag b/Materials/Examples/StandardSurface/Plastic.msl.frag new file mode 100644 index 0000000000..076b3ddeaf --- /dev/null +++ b/Materials/Examples/StandardSurface/Plastic.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_plastic_base; + vec3 SR_plastic_base_color; + float SR_plastic_diffuse_roughness; + float SR_plastic_metalness; + float SR_plastic_specular; + vec3 SR_plastic_specular_color; + float SR_plastic_specular_roughness; + float SR_plastic_specular_IOR; + float SR_plastic_specular_anisotropy; + float SR_plastic_specular_rotation; + float SR_plastic_transmission; + vec3 SR_plastic_transmission_color; + float SR_plastic_transmission_depth; + vec3 SR_plastic_transmission_scatter; + float SR_plastic_transmission_scatter_anisotropy; + float SR_plastic_transmission_dispersion; + float SR_plastic_transmission_extra_roughness; + float SR_plastic_subsurface; + vec3 SR_plastic_subsurface_color; + vec3 SR_plastic_subsurface_radius; + float SR_plastic_subsurface_scale; + float SR_plastic_subsurface_anisotropy; + float SR_plastic_sheen; + vec3 SR_plastic_sheen_color; + float SR_plastic_sheen_roughness; + float SR_plastic_coat; + vec3 SR_plastic_coat_color; + float SR_plastic_coat_roughness; + float SR_plastic_coat_anisotropy; + float SR_plastic_coat_rotation; + float SR_plastic_coat_IOR; + float SR_plastic_coat_affect_color; + float SR_plastic_coat_affect_roughness; + float SR_plastic_thin_film_thickness; + float SR_plastic_thin_film_IOR; + float SR_plastic_emission; + vec3 SR_plastic_emission_color; + vec3 SR_plastic_opacity; + bool SR_plastic_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_plastic_base + + , vec3 SR_plastic_base_color + + , float SR_plastic_diffuse_roughness + + , float SR_plastic_metalness + + , float SR_plastic_specular + + , vec3 SR_plastic_specular_color + + , float SR_plastic_specular_roughness + + , float SR_plastic_specular_IOR + + , float SR_plastic_specular_anisotropy + + , float SR_plastic_specular_rotation + + , float SR_plastic_transmission + + , vec3 SR_plastic_transmission_color + + , float SR_plastic_transmission_depth + + , vec3 SR_plastic_transmission_scatter + + , float SR_plastic_transmission_scatter_anisotropy + + , float SR_plastic_transmission_dispersion + + , float SR_plastic_transmission_extra_roughness + + , float SR_plastic_subsurface + + , vec3 SR_plastic_subsurface_color + + , vec3 SR_plastic_subsurface_radius + + , float SR_plastic_subsurface_scale + + , float SR_plastic_subsurface_anisotropy + + , float SR_plastic_sheen + + , vec3 SR_plastic_sheen_color + + , float SR_plastic_sheen_roughness + + , float SR_plastic_coat + + , vec3 SR_plastic_coat_color + + , float SR_plastic_coat_roughness + + , float SR_plastic_coat_anisotropy + + , float SR_plastic_coat_rotation + + , float SR_plastic_coat_IOR + + , float SR_plastic_coat_affect_color + + , float SR_plastic_coat_affect_roughness + + , float SR_plastic_thin_film_thickness + + , float SR_plastic_thin_film_IOR + + , float SR_plastic_emission + + , vec3 SR_plastic_emission_color + + , vec3 SR_plastic_opacity + + , bool SR_plastic_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_plastic_base(SR_plastic_base) + + , SR_plastic_base_color(SR_plastic_base_color) + + , SR_plastic_diffuse_roughness(SR_plastic_diffuse_roughness) + + , SR_plastic_metalness(SR_plastic_metalness) + + , SR_plastic_specular(SR_plastic_specular) + + , SR_plastic_specular_color(SR_plastic_specular_color) + + , SR_plastic_specular_roughness(SR_plastic_specular_roughness) + + , SR_plastic_specular_IOR(SR_plastic_specular_IOR) + + , SR_plastic_specular_anisotropy(SR_plastic_specular_anisotropy) + + , SR_plastic_specular_rotation(SR_plastic_specular_rotation) + + , SR_plastic_transmission(SR_plastic_transmission) + + , SR_plastic_transmission_color(SR_plastic_transmission_color) + + , SR_plastic_transmission_depth(SR_plastic_transmission_depth) + + , SR_plastic_transmission_scatter(SR_plastic_transmission_scatter) + + , SR_plastic_transmission_scatter_anisotropy(SR_plastic_transmission_scatter_anisotropy) + + , SR_plastic_transmission_dispersion(SR_plastic_transmission_dispersion) + + , SR_plastic_transmission_extra_roughness(SR_plastic_transmission_extra_roughness) + + , SR_plastic_subsurface(SR_plastic_subsurface) + + , SR_plastic_subsurface_color(SR_plastic_subsurface_color) + + , SR_plastic_subsurface_radius(SR_plastic_subsurface_radius) + + , SR_plastic_subsurface_scale(SR_plastic_subsurface_scale) + + , SR_plastic_subsurface_anisotropy(SR_plastic_subsurface_anisotropy) + + , SR_plastic_sheen(SR_plastic_sheen) + + , SR_plastic_sheen_color(SR_plastic_sheen_color) + + , SR_plastic_sheen_roughness(SR_plastic_sheen_roughness) + + , SR_plastic_coat(SR_plastic_coat) + + , SR_plastic_coat_color(SR_plastic_coat_color) + + , SR_plastic_coat_roughness(SR_plastic_coat_roughness) + + , SR_plastic_coat_anisotropy(SR_plastic_coat_anisotropy) + + , SR_plastic_coat_rotation(SR_plastic_coat_rotation) + + , SR_plastic_coat_IOR(SR_plastic_coat_IOR) + + , SR_plastic_coat_affect_color(SR_plastic_coat_affect_color) + + , SR_plastic_coat_affect_roughness(SR_plastic_coat_affect_roughness) + + , SR_plastic_thin_film_thickness(SR_plastic_thin_film_thickness) + + , SR_plastic_thin_film_IOR(SR_plastic_thin_film_IOR) + + , SR_plastic_emission(SR_plastic_emission) + + , SR_plastic_emission_color(SR_plastic_emission_color) + + , SR_plastic_opacity(SR_plastic_opacity) + + , SR_plastic_thin_walled(SR_plastic_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_plastic_base; + + + vec3 SR_plastic_base_color; + + + float SR_plastic_diffuse_roughness; + + + float SR_plastic_metalness; + + + float SR_plastic_specular; + + + vec3 SR_plastic_specular_color; + + + float SR_plastic_specular_roughness; + + + float SR_plastic_specular_IOR; + + + float SR_plastic_specular_anisotropy; + + + float SR_plastic_specular_rotation; + + + float SR_plastic_transmission; + + + vec3 SR_plastic_transmission_color; + + + float SR_plastic_transmission_depth; + + + vec3 SR_plastic_transmission_scatter; + + + float SR_plastic_transmission_scatter_anisotropy; + + + float SR_plastic_transmission_dispersion; + + + float SR_plastic_transmission_extra_roughness; + + + float SR_plastic_subsurface; + + + vec3 SR_plastic_subsurface_color; + + + vec3 SR_plastic_subsurface_radius; + + + float SR_plastic_subsurface_scale; + + + float SR_plastic_subsurface_anisotropy; + + + float SR_plastic_sheen; + + + vec3 SR_plastic_sheen_color; + + + float SR_plastic_sheen_roughness; + + + float SR_plastic_coat; + + + vec3 SR_plastic_coat_color; + + + float SR_plastic_coat_roughness; + + + float SR_plastic_coat_anisotropy; + + + float SR_plastic_coat_rotation; + + + float SR_plastic_coat_IOR; + + + float SR_plastic_coat_affect_color; + + + float SR_plastic_coat_affect_roughness; + + + float SR_plastic_thin_film_thickness; + + + float SR_plastic_thin_film_IOR; + + + float SR_plastic_emission; + + + vec3 SR_plastic_emission_color; + + + vec3 SR_plastic_opacity; + + + bool SR_plastic_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_plastic_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_plastic_base, SR_plastic_base_color, SR_plastic_diffuse_roughness, SR_plastic_metalness, SR_plastic_specular, SR_plastic_specular_color, SR_plastic_specular_roughness, SR_plastic_specular_IOR, SR_plastic_specular_anisotropy, SR_plastic_specular_rotation, SR_plastic_transmission, SR_plastic_transmission_color, SR_plastic_transmission_depth, SR_plastic_transmission_scatter, SR_plastic_transmission_scatter_anisotropy, SR_plastic_transmission_dispersion, SR_plastic_transmission_extra_roughness, SR_plastic_subsurface, SR_plastic_subsurface_color, SR_plastic_subsurface_radius, SR_plastic_subsurface_scale, SR_plastic_subsurface_anisotropy, SR_plastic_sheen, SR_plastic_sheen_color, SR_plastic_sheen_roughness, SR_plastic_coat, SR_plastic_coat_color, SR_plastic_coat_roughness, SR_plastic_coat_anisotropy, SR_plastic_coat_rotation, SR_plastic_coat_IOR, geomprop_Nworld_out1, SR_plastic_coat_affect_color, SR_plastic_coat_affect_roughness, SR_plastic_thin_film_thickness, SR_plastic_thin_film_IOR, SR_plastic_emission, SR_plastic_emission_color, SR_plastic_opacity, SR_plastic_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_plastic_out); + material Plastic_out = SR_plastic_out; + out1 = float4(Plastic_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_plastic_base + , u_pub.SR_plastic_base_color + , u_pub.SR_plastic_diffuse_roughness + , u_pub.SR_plastic_metalness + , u_pub.SR_plastic_specular + , u_pub.SR_plastic_specular_color + , u_pub.SR_plastic_specular_roughness + , u_pub.SR_plastic_specular_IOR + , u_pub.SR_plastic_specular_anisotropy + , u_pub.SR_plastic_specular_rotation + , u_pub.SR_plastic_transmission + , u_pub.SR_plastic_transmission_color + , u_pub.SR_plastic_transmission_depth + , u_pub.SR_plastic_transmission_scatter + , u_pub.SR_plastic_transmission_scatter_anisotropy + , u_pub.SR_plastic_transmission_dispersion + , u_pub.SR_plastic_transmission_extra_roughness + , u_pub.SR_plastic_subsurface + , u_pub.SR_plastic_subsurface_color + , u_pub.SR_plastic_subsurface_radius + , u_pub.SR_plastic_subsurface_scale + , u_pub.SR_plastic_subsurface_anisotropy + , u_pub.SR_plastic_sheen + , u_pub.SR_plastic_sheen_color + , u_pub.SR_plastic_sheen_roughness + , u_pub.SR_plastic_coat + , u_pub.SR_plastic_coat_color + , u_pub.SR_plastic_coat_roughness + , u_pub.SR_plastic_coat_anisotropy + , u_pub.SR_plastic_coat_rotation + , u_pub.SR_plastic_coat_IOR + , u_pub.SR_plastic_coat_affect_color + , u_pub.SR_plastic_coat_affect_roughness + , u_pub.SR_plastic_thin_film_thickness + , u_pub.SR_plastic_thin_film_IOR + , u_pub.SR_plastic_emission + , u_pub.SR_plastic_emission_color + , u_pub.SR_plastic_opacity + , u_pub.SR_plastic_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Plastic.msl.vert b/Materials/Examples/StandardSurface/Plastic.msl.vert new file mode 100644 index 0000000000..7aeaabe5a2 --- /dev/null +++ b/Materials/Examples/StandardSurface/Plastic.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_plastic'. Function already called in this scope. + // Omitted node 'Plastic'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Plastic.osl b/Materials/Examples/StandardSurface/Plastic.osl new file mode 100644 index 0000000000..72b5094adc --- /dev/null +++ b/Materials/Examples/StandardSurface/Plastic.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Plastic +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Plastic" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_plastic_base = 1.000000 + [[ + string widget = "number" + ]], + color SR_plastic_base_color = color(0.104704, 0.241883, 0.818000), + float SR_plastic_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_metalness = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_specular = 1.000000 + [[ + string widget = "number" + ]], + color SR_plastic_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_plastic_specular_roughness = 0.324675 + [[ + string widget = "number" + ]], + float SR_plastic_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_plastic_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_plastic_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_plastic_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_plastic_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_plastic_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_plastic_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_plastic_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_plastic_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_plastic_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_plastic_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_plastic_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_plastic_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_plastic_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_plastic_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_plastic_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_plastic_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_plastic_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_plastic_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_plastic_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_plastic_opacity = color(1.000000, 1.000000, 1.000000), + int SR_plastic_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_plastic_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_plastic_base, SR_plastic_base_color, SR_plastic_diffuse_roughness, SR_plastic_metalness, SR_plastic_specular, SR_plastic_specular_color, SR_plastic_specular_roughness, SR_plastic_specular_IOR, SR_plastic_specular_anisotropy, SR_plastic_specular_rotation, SR_plastic_transmission, SR_plastic_transmission_color, SR_plastic_transmission_depth, SR_plastic_transmission_scatter, SR_plastic_transmission_scatter_anisotropy, SR_plastic_transmission_dispersion, SR_plastic_transmission_extra_roughness, SR_plastic_subsurface, SR_plastic_subsurface_color, SR_plastic_subsurface_radius, SR_plastic_subsurface_scale, SR_plastic_subsurface_anisotropy, SR_plastic_sheen, SR_plastic_sheen_color, SR_plastic_sheen_roughness, SR_plastic_coat, SR_plastic_coat_color, SR_plastic_coat_roughness, SR_plastic_coat_anisotropy, SR_plastic_coat_rotation, SR_plastic_coat_IOR, geomprop_Nworld_out1, SR_plastic_coat_affect_color, SR_plastic_coat_affect_roughness, SR_plastic_thin_film_thickness, SR_plastic_thin_film_IOR, SR_plastic_emission, SR_plastic_emission_color, SR_plastic_opacity, SR_plastic_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_plastic_out); + MATERIAL Plastic_out = mx_surfacematerial(SR_plastic_out, backsurfaceshader, displacementshader1); + out = Plastic_out; +} + diff --git a/Materials/Examples/StandardSurface/ThinFilm.glsl.frag b/Materials/Examples/StandardSurface/ThinFilm.glsl.frag new file mode 100644 index 0000000000..c5350b58bc --- /dev/null +++ b/Materials/Examples/StandardSurface/ThinFilm.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_thin_film_base = 0.000000; +uniform vec3 SR_thin_film_base_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_thin_film_diffuse_roughness = 0.000000; +uniform float SR_thin_film_metalness = 0.000000; +uniform float SR_thin_film_specular = 1.000000; +uniform vec3 SR_thin_film_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_thin_film_specular_roughness = 0.020000; +uniform float SR_thin_film_specular_IOR = 2.500000; +uniform float SR_thin_film_specular_anisotropy = 0.000000; +uniform float SR_thin_film_specular_rotation = 0.000000; +uniform float SR_thin_film_transmission = 0.000000; +uniform vec3 SR_thin_film_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_thin_film_transmission_depth = 0.000000; +uniform vec3 SR_thin_film_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_thin_film_transmission_scatter_anisotropy = 0.000000; +uniform float SR_thin_film_transmission_dispersion = 0.000000; +uniform float SR_thin_film_transmission_extra_roughness = 0.000000; +uniform float SR_thin_film_subsurface = 0.000000; +uniform vec3 SR_thin_film_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_thin_film_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_thin_film_subsurface_scale = 1.000000; +uniform float SR_thin_film_subsurface_anisotropy = 0.000000; +uniform float SR_thin_film_sheen = 0.000000; +uniform vec3 SR_thin_film_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_thin_film_sheen_roughness = 0.300000; +uniform float SR_thin_film_coat = 0.000000; +uniform vec3 SR_thin_film_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_thin_film_coat_roughness = 0.100000; +uniform float SR_thin_film_coat_anisotropy = 0.000000; +uniform float SR_thin_film_coat_rotation = 0.000000; +uniform float SR_thin_film_coat_IOR = 1.500000; +uniform float SR_thin_film_coat_affect_color = 0.000000; +uniform float SR_thin_film_coat_affect_roughness = 0.000000; +uniform float SR_thin_film_thin_film_thickness = 550.000000; +uniform float SR_thin_film_thin_film_IOR = 1.500000; +uniform float SR_thin_film_emission = 0.000000; +uniform vec3 SR_thin_film_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_thin_film_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_thin_film_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_thin_film_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_thin_film_base, SR_thin_film_base_color, SR_thin_film_diffuse_roughness, SR_thin_film_metalness, SR_thin_film_specular, SR_thin_film_specular_color, SR_thin_film_specular_roughness, SR_thin_film_specular_IOR, SR_thin_film_specular_anisotropy, SR_thin_film_specular_rotation, SR_thin_film_transmission, SR_thin_film_transmission_color, SR_thin_film_transmission_depth, SR_thin_film_transmission_scatter, SR_thin_film_transmission_scatter_anisotropy, SR_thin_film_transmission_dispersion, SR_thin_film_transmission_extra_roughness, SR_thin_film_subsurface, SR_thin_film_subsurface_color, SR_thin_film_subsurface_radius, SR_thin_film_subsurface_scale, SR_thin_film_subsurface_anisotropy, SR_thin_film_sheen, SR_thin_film_sheen_color, SR_thin_film_sheen_roughness, SR_thin_film_coat, SR_thin_film_coat_color, SR_thin_film_coat_roughness, SR_thin_film_coat_anisotropy, SR_thin_film_coat_rotation, SR_thin_film_coat_IOR, geomprop_Nworld_out1, SR_thin_film_coat_affect_color, SR_thin_film_coat_affect_roughness, SR_thin_film_thin_film_thickness, SR_thin_film_thin_film_IOR, SR_thin_film_emission, SR_thin_film_emission_color, SR_thin_film_opacity, SR_thin_film_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_thin_film_out); + material ThinFilm_out = SR_thin_film_out; + out1 = vec4(ThinFilm_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/ThinFilm.glsl.vert b/Materials/Examples/StandardSurface/ThinFilm.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/ThinFilm.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/ThinFilm.mdl b/Materials/Examples/StandardSurface/ThinFilm.mdl new file mode 100644 index 0000000000..f868675375 --- /dev/null +++ b/Materials/Examples/StandardSurface/ThinFilm.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material ThinFilm +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_thin_film_base = 0.000000 + [[ + materialx::core::origin("SR_thin_film/base") + ]], + color SR_thin_film_base_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_thin_film/base_color") + ]], + float SR_thin_film_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_thin_film/diffuse_roughness") + ]], + float SR_thin_film_metalness = 0.000000 + [[ + materialx::core::origin("SR_thin_film/metalness") + ]], + float SR_thin_film_specular = 1.000000 + [[ + materialx::core::origin("SR_thin_film/specular") + ]], + color SR_thin_film_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_thin_film/specular_color") + ]], + float SR_thin_film_specular_roughness = 0.020000 + [[ + materialx::core::origin("SR_thin_film/specular_roughness") + ]], + uniform float SR_thin_film_specular_IOR = 2.500000 + [[ + materialx::core::origin("SR_thin_film/specular_IOR") + ]], + float SR_thin_film_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_thin_film/specular_anisotropy") + ]], + float SR_thin_film_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_thin_film/specular_rotation") + ]], + float SR_thin_film_transmission = 0.000000 + [[ + materialx::core::origin("SR_thin_film/transmission") + ]], + color SR_thin_film_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_thin_film/transmission_color") + ]], + float SR_thin_film_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_thin_film/transmission_depth") + ]], + color SR_thin_film_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_thin_film/transmission_scatter") + ]], + float SR_thin_film_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_thin_film/transmission_scatter_anisotropy") + ]], + float SR_thin_film_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_thin_film/transmission_dispersion") + ]], + float SR_thin_film_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_thin_film/transmission_extra_roughness") + ]], + float SR_thin_film_subsurface = 0.000000 + [[ + materialx::core::origin("SR_thin_film/subsurface") + ]], + color SR_thin_film_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_thin_film/subsurface_color") + ]], + color SR_thin_film_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_thin_film/subsurface_radius") + ]], + float SR_thin_film_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_thin_film/subsurface_scale") + ]], + float SR_thin_film_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_thin_film/subsurface_anisotropy") + ]], + float SR_thin_film_sheen = 0.000000 + [[ + materialx::core::origin("SR_thin_film/sheen") + ]], + color SR_thin_film_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_thin_film/sheen_color") + ]], + float SR_thin_film_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_thin_film/sheen_roughness") + ]], + float SR_thin_film_coat = 0.000000 + [[ + materialx::core::origin("SR_thin_film/coat") + ]], + color SR_thin_film_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_thin_film/coat_color") + ]], + float SR_thin_film_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_thin_film/coat_roughness") + ]], + float SR_thin_film_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_thin_film/coat_anisotropy") + ]], + float SR_thin_film_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_thin_film/coat_rotation") + ]], + uniform float SR_thin_film_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_thin_film/coat_IOR") + ]], + float SR_thin_film_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_thin_film/coat_affect_color") + ]], + float SR_thin_film_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_thin_film/coat_affect_roughness") + ]], + float SR_thin_film_thin_film_thickness = 550.000000 + [[ + materialx::core::origin("SR_thin_film/thin_film_thickness") + ]], + float SR_thin_film_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_thin_film/thin_film_IOR") + ]], + float SR_thin_film_emission = 0.000000 + [[ + materialx::core::origin("SR_thin_film/emission") + ]], + color SR_thin_film_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_thin_film/emission_color") + ]], + color SR_thin_film_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_thin_film/opacity") + ]], + bool SR_thin_film_thin_walled = false + [[ + materialx::core::origin("SR_thin_film/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_thin_film_out = NG_standard_surface_surfaceshader_100(SR_thin_film_base, SR_thin_film_base_color, SR_thin_film_diffuse_roughness, SR_thin_film_metalness, SR_thin_film_specular, SR_thin_film_specular_color, SR_thin_film_specular_roughness, SR_thin_film_specular_IOR, SR_thin_film_specular_anisotropy, SR_thin_film_specular_rotation, SR_thin_film_transmission, SR_thin_film_transmission_color, SR_thin_film_transmission_depth, SR_thin_film_transmission_scatter, SR_thin_film_transmission_scatter_anisotropy, SR_thin_film_transmission_dispersion, SR_thin_film_transmission_extra_roughness, SR_thin_film_subsurface, SR_thin_film_subsurface_color, SR_thin_film_subsurface_radius, SR_thin_film_subsurface_scale, SR_thin_film_subsurface_anisotropy, SR_thin_film_sheen, SR_thin_film_sheen_color, SR_thin_film_sheen_roughness, SR_thin_film_coat, SR_thin_film_coat_color, SR_thin_film_coat_roughness, SR_thin_film_coat_anisotropy, SR_thin_film_coat_rotation, SR_thin_film_coat_IOR, geomprop_Nworld_out1, SR_thin_film_coat_affect_color, SR_thin_film_coat_affect_roughness, SR_thin_film_thin_film_thickness, SR_thin_film_thin_film_IOR, SR_thin_film_emission, SR_thin_film_emission_color, SR_thin_film_opacity, SR_thin_film_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material ThinFilm_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_thin_film_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = ThinFilm_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/ThinFilm.msl.frag b/Materials/Examples/StandardSurface/ThinFilm.msl.frag new file mode 100644 index 0000000000..3cf5e00770 --- /dev/null +++ b/Materials/Examples/StandardSurface/ThinFilm.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_thin_film_base; + vec3 SR_thin_film_base_color; + float SR_thin_film_diffuse_roughness; + float SR_thin_film_metalness; + float SR_thin_film_specular; + vec3 SR_thin_film_specular_color; + float SR_thin_film_specular_roughness; + float SR_thin_film_specular_IOR; + float SR_thin_film_specular_anisotropy; + float SR_thin_film_specular_rotation; + float SR_thin_film_transmission; + vec3 SR_thin_film_transmission_color; + float SR_thin_film_transmission_depth; + vec3 SR_thin_film_transmission_scatter; + float SR_thin_film_transmission_scatter_anisotropy; + float SR_thin_film_transmission_dispersion; + float SR_thin_film_transmission_extra_roughness; + float SR_thin_film_subsurface; + vec3 SR_thin_film_subsurface_color; + vec3 SR_thin_film_subsurface_radius; + float SR_thin_film_subsurface_scale; + float SR_thin_film_subsurface_anisotropy; + float SR_thin_film_sheen; + vec3 SR_thin_film_sheen_color; + float SR_thin_film_sheen_roughness; + float SR_thin_film_coat; + vec3 SR_thin_film_coat_color; + float SR_thin_film_coat_roughness; + float SR_thin_film_coat_anisotropy; + float SR_thin_film_coat_rotation; + float SR_thin_film_coat_IOR; + float SR_thin_film_coat_affect_color; + float SR_thin_film_coat_affect_roughness; + float SR_thin_film_thin_film_thickness; + float SR_thin_film_thin_film_IOR; + float SR_thin_film_emission; + vec3 SR_thin_film_emission_color; + vec3 SR_thin_film_opacity; + bool SR_thin_film_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_thin_film_base + + , vec3 SR_thin_film_base_color + + , float SR_thin_film_diffuse_roughness + + , float SR_thin_film_metalness + + , float SR_thin_film_specular + + , vec3 SR_thin_film_specular_color + + , float SR_thin_film_specular_roughness + + , float SR_thin_film_specular_IOR + + , float SR_thin_film_specular_anisotropy + + , float SR_thin_film_specular_rotation + + , float SR_thin_film_transmission + + , vec3 SR_thin_film_transmission_color + + , float SR_thin_film_transmission_depth + + , vec3 SR_thin_film_transmission_scatter + + , float SR_thin_film_transmission_scatter_anisotropy + + , float SR_thin_film_transmission_dispersion + + , float SR_thin_film_transmission_extra_roughness + + , float SR_thin_film_subsurface + + , vec3 SR_thin_film_subsurface_color + + , vec3 SR_thin_film_subsurface_radius + + , float SR_thin_film_subsurface_scale + + , float SR_thin_film_subsurface_anisotropy + + , float SR_thin_film_sheen + + , vec3 SR_thin_film_sheen_color + + , float SR_thin_film_sheen_roughness + + , float SR_thin_film_coat + + , vec3 SR_thin_film_coat_color + + , float SR_thin_film_coat_roughness + + , float SR_thin_film_coat_anisotropy + + , float SR_thin_film_coat_rotation + + , float SR_thin_film_coat_IOR + + , float SR_thin_film_coat_affect_color + + , float SR_thin_film_coat_affect_roughness + + , float SR_thin_film_thin_film_thickness + + , float SR_thin_film_thin_film_IOR + + , float SR_thin_film_emission + + , vec3 SR_thin_film_emission_color + + , vec3 SR_thin_film_opacity + + , bool SR_thin_film_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_thin_film_base(SR_thin_film_base) + + , SR_thin_film_base_color(SR_thin_film_base_color) + + , SR_thin_film_diffuse_roughness(SR_thin_film_diffuse_roughness) + + , SR_thin_film_metalness(SR_thin_film_metalness) + + , SR_thin_film_specular(SR_thin_film_specular) + + , SR_thin_film_specular_color(SR_thin_film_specular_color) + + , SR_thin_film_specular_roughness(SR_thin_film_specular_roughness) + + , SR_thin_film_specular_IOR(SR_thin_film_specular_IOR) + + , SR_thin_film_specular_anisotropy(SR_thin_film_specular_anisotropy) + + , SR_thin_film_specular_rotation(SR_thin_film_specular_rotation) + + , SR_thin_film_transmission(SR_thin_film_transmission) + + , SR_thin_film_transmission_color(SR_thin_film_transmission_color) + + , SR_thin_film_transmission_depth(SR_thin_film_transmission_depth) + + , SR_thin_film_transmission_scatter(SR_thin_film_transmission_scatter) + + , SR_thin_film_transmission_scatter_anisotropy(SR_thin_film_transmission_scatter_anisotropy) + + , SR_thin_film_transmission_dispersion(SR_thin_film_transmission_dispersion) + + , SR_thin_film_transmission_extra_roughness(SR_thin_film_transmission_extra_roughness) + + , SR_thin_film_subsurface(SR_thin_film_subsurface) + + , SR_thin_film_subsurface_color(SR_thin_film_subsurface_color) + + , SR_thin_film_subsurface_radius(SR_thin_film_subsurface_radius) + + , SR_thin_film_subsurface_scale(SR_thin_film_subsurface_scale) + + , SR_thin_film_subsurface_anisotropy(SR_thin_film_subsurface_anisotropy) + + , SR_thin_film_sheen(SR_thin_film_sheen) + + , SR_thin_film_sheen_color(SR_thin_film_sheen_color) + + , SR_thin_film_sheen_roughness(SR_thin_film_sheen_roughness) + + , SR_thin_film_coat(SR_thin_film_coat) + + , SR_thin_film_coat_color(SR_thin_film_coat_color) + + , SR_thin_film_coat_roughness(SR_thin_film_coat_roughness) + + , SR_thin_film_coat_anisotropy(SR_thin_film_coat_anisotropy) + + , SR_thin_film_coat_rotation(SR_thin_film_coat_rotation) + + , SR_thin_film_coat_IOR(SR_thin_film_coat_IOR) + + , SR_thin_film_coat_affect_color(SR_thin_film_coat_affect_color) + + , SR_thin_film_coat_affect_roughness(SR_thin_film_coat_affect_roughness) + + , SR_thin_film_thin_film_thickness(SR_thin_film_thin_film_thickness) + + , SR_thin_film_thin_film_IOR(SR_thin_film_thin_film_IOR) + + , SR_thin_film_emission(SR_thin_film_emission) + + , SR_thin_film_emission_color(SR_thin_film_emission_color) + + , SR_thin_film_opacity(SR_thin_film_opacity) + + , SR_thin_film_thin_walled(SR_thin_film_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_thin_film_base; + + + vec3 SR_thin_film_base_color; + + + float SR_thin_film_diffuse_roughness; + + + float SR_thin_film_metalness; + + + float SR_thin_film_specular; + + + vec3 SR_thin_film_specular_color; + + + float SR_thin_film_specular_roughness; + + + float SR_thin_film_specular_IOR; + + + float SR_thin_film_specular_anisotropy; + + + float SR_thin_film_specular_rotation; + + + float SR_thin_film_transmission; + + + vec3 SR_thin_film_transmission_color; + + + float SR_thin_film_transmission_depth; + + + vec3 SR_thin_film_transmission_scatter; + + + float SR_thin_film_transmission_scatter_anisotropy; + + + float SR_thin_film_transmission_dispersion; + + + float SR_thin_film_transmission_extra_roughness; + + + float SR_thin_film_subsurface; + + + vec3 SR_thin_film_subsurface_color; + + + vec3 SR_thin_film_subsurface_radius; + + + float SR_thin_film_subsurface_scale; + + + float SR_thin_film_subsurface_anisotropy; + + + float SR_thin_film_sheen; + + + vec3 SR_thin_film_sheen_color; + + + float SR_thin_film_sheen_roughness; + + + float SR_thin_film_coat; + + + vec3 SR_thin_film_coat_color; + + + float SR_thin_film_coat_roughness; + + + float SR_thin_film_coat_anisotropy; + + + float SR_thin_film_coat_rotation; + + + float SR_thin_film_coat_IOR; + + + float SR_thin_film_coat_affect_color; + + + float SR_thin_film_coat_affect_roughness; + + + float SR_thin_film_thin_film_thickness; + + + float SR_thin_film_thin_film_IOR; + + + float SR_thin_film_emission; + + + vec3 SR_thin_film_emission_color; + + + vec3 SR_thin_film_opacity; + + + bool SR_thin_film_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_thin_film_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_thin_film_base, SR_thin_film_base_color, SR_thin_film_diffuse_roughness, SR_thin_film_metalness, SR_thin_film_specular, SR_thin_film_specular_color, SR_thin_film_specular_roughness, SR_thin_film_specular_IOR, SR_thin_film_specular_anisotropy, SR_thin_film_specular_rotation, SR_thin_film_transmission, SR_thin_film_transmission_color, SR_thin_film_transmission_depth, SR_thin_film_transmission_scatter, SR_thin_film_transmission_scatter_anisotropy, SR_thin_film_transmission_dispersion, SR_thin_film_transmission_extra_roughness, SR_thin_film_subsurface, SR_thin_film_subsurface_color, SR_thin_film_subsurface_radius, SR_thin_film_subsurface_scale, SR_thin_film_subsurface_anisotropy, SR_thin_film_sheen, SR_thin_film_sheen_color, SR_thin_film_sheen_roughness, SR_thin_film_coat, SR_thin_film_coat_color, SR_thin_film_coat_roughness, SR_thin_film_coat_anisotropy, SR_thin_film_coat_rotation, SR_thin_film_coat_IOR, geomprop_Nworld_out1, SR_thin_film_coat_affect_color, SR_thin_film_coat_affect_roughness, SR_thin_film_thin_film_thickness, SR_thin_film_thin_film_IOR, SR_thin_film_emission, SR_thin_film_emission_color, SR_thin_film_opacity, SR_thin_film_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_thin_film_out); + material ThinFilm_out = SR_thin_film_out; + out1 = float4(ThinFilm_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_thin_film_base + , u_pub.SR_thin_film_base_color + , u_pub.SR_thin_film_diffuse_roughness + , u_pub.SR_thin_film_metalness + , u_pub.SR_thin_film_specular + , u_pub.SR_thin_film_specular_color + , u_pub.SR_thin_film_specular_roughness + , u_pub.SR_thin_film_specular_IOR + , u_pub.SR_thin_film_specular_anisotropy + , u_pub.SR_thin_film_specular_rotation + , u_pub.SR_thin_film_transmission + , u_pub.SR_thin_film_transmission_color + , u_pub.SR_thin_film_transmission_depth + , u_pub.SR_thin_film_transmission_scatter + , u_pub.SR_thin_film_transmission_scatter_anisotropy + , u_pub.SR_thin_film_transmission_dispersion + , u_pub.SR_thin_film_transmission_extra_roughness + , u_pub.SR_thin_film_subsurface + , u_pub.SR_thin_film_subsurface_color + , u_pub.SR_thin_film_subsurface_radius + , u_pub.SR_thin_film_subsurface_scale + , u_pub.SR_thin_film_subsurface_anisotropy + , u_pub.SR_thin_film_sheen + , u_pub.SR_thin_film_sheen_color + , u_pub.SR_thin_film_sheen_roughness + , u_pub.SR_thin_film_coat + , u_pub.SR_thin_film_coat_color + , u_pub.SR_thin_film_coat_roughness + , u_pub.SR_thin_film_coat_anisotropy + , u_pub.SR_thin_film_coat_rotation + , u_pub.SR_thin_film_coat_IOR + , u_pub.SR_thin_film_coat_affect_color + , u_pub.SR_thin_film_coat_affect_roughness + , u_pub.SR_thin_film_thin_film_thickness + , u_pub.SR_thin_film_thin_film_IOR + , u_pub.SR_thin_film_emission + , u_pub.SR_thin_film_emission_color + , u_pub.SR_thin_film_opacity + , u_pub.SR_thin_film_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/ThinFilm.msl.vert b/Materials/Examples/StandardSurface/ThinFilm.msl.vert new file mode 100644 index 0000000000..650faaf5c7 --- /dev/null +++ b/Materials/Examples/StandardSurface/ThinFilm.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_thin_film'. Function already called in this scope. + // Omitted node 'ThinFilm'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/ThinFilm.osl b/Materials/Examples/StandardSurface/ThinFilm.osl new file mode 100644 index 0000000000..40e64900d6 --- /dev/null +++ b/Materials/Examples/StandardSurface/ThinFilm.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader ThinFilm +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "ThinFilm" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_thin_film_base = 0.000000 + [[ + string widget = "number" + ]], + color SR_thin_film_base_color = color(1.000000, 1.000000, 1.000000), + float SR_thin_film_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_metalness = 0.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_specular = 1.000000 + [[ + string widget = "number" + ]], + color SR_thin_film_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_thin_film_specular_roughness = 0.020000 + [[ + string widget = "number" + ]], + float SR_thin_film_specular_IOR = 2.500000 + [[ + string widget = "number" + ]], + float SR_thin_film_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_thin_film_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_thin_film_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_thin_film_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_thin_film_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_thin_film_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_thin_film_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_thin_film_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_thin_film_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_thin_film_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_thin_film_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_thin_film_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_thin_film_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_thin_film_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_thin_film_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_thin_film_thickness = 550.000000 + [[ + string widget = "number" + ]], + float SR_thin_film_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_thin_film_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_thin_film_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_thin_film_opacity = color(1.000000, 1.000000, 1.000000), + int SR_thin_film_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_thin_film_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_thin_film_base, SR_thin_film_base_color, SR_thin_film_diffuse_roughness, SR_thin_film_metalness, SR_thin_film_specular, SR_thin_film_specular_color, SR_thin_film_specular_roughness, SR_thin_film_specular_IOR, SR_thin_film_specular_anisotropy, SR_thin_film_specular_rotation, SR_thin_film_transmission, SR_thin_film_transmission_color, SR_thin_film_transmission_depth, SR_thin_film_transmission_scatter, SR_thin_film_transmission_scatter_anisotropy, SR_thin_film_transmission_dispersion, SR_thin_film_transmission_extra_roughness, SR_thin_film_subsurface, SR_thin_film_subsurface_color, SR_thin_film_subsurface_radius, SR_thin_film_subsurface_scale, SR_thin_film_subsurface_anisotropy, SR_thin_film_sheen, SR_thin_film_sheen_color, SR_thin_film_sheen_roughness, SR_thin_film_coat, SR_thin_film_coat_color, SR_thin_film_coat_roughness, SR_thin_film_coat_anisotropy, SR_thin_film_coat_rotation, SR_thin_film_coat_IOR, geomprop_Nworld_out1, SR_thin_film_coat_affect_color, SR_thin_film_coat_affect_roughness, SR_thin_film_thin_film_thickness, SR_thin_film_thin_film_IOR, SR_thin_film_emission, SR_thin_film_emission_color, SR_thin_film_opacity, SR_thin_film_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_thin_film_out); + MATERIAL ThinFilm_out = mx_surfacematerial(SR_thin_film_out, backsurfaceshader, displacementshader1); + out = ThinFilm_out; +} + diff --git a/Materials/Examples/StandardSurface/Tiled_Brass.glsl.frag b/Materials/Examples/StandardSurface/Tiled_Brass.glsl.frag new file mode 100644 index 0000000000..5edd54bef2 --- /dev/null +++ b/Materials/Examples/StandardSurface/Tiled_Brass.glsl.frag @@ -0,0 +1,1983 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D image_roughness_file; +uniform float image_roughness_default = 0.000000; +uniform vec2 image_roughness_uvtiling = vec2(1.000000, 1.000000); +uniform vec2 image_roughness_uvoffset = vec2(0.000000, 0.000000); +uniform vec2 image_roughness_realworldimagesize = vec2(1.000000, 1.000000); +uniform vec2 image_roughness_realworldtilesize = vec2(1.000000, 1.000000); +uniform int image_roughness_filtertype = 1; +uniform int image_roughness_framerange = 0; +uniform int image_roughness_frameoffset = 0; +uniform int image_roughness_frameendaction = 0; +uniform sampler2D image_color_file; +uniform vec3 image_color_default = vec3(0.000000, 0.000000, 0.000000); +uniform vec2 image_color_uvtiling = vec2(1.000000, 1.000000); +uniform vec2 image_color_uvoffset = vec2(0.000000, 0.000000); +uniform vec2 image_color_realworldimagesize = vec2(1.000000, 1.000000); +uniform vec2 image_color_realworldtilesize = vec2(1.000000, 1.000000); +uniform int image_color_filtertype = 1; +uniform int image_color_framerange = 0; +uniform int image_color_frameoffset = 0; +uniform int image_color_frameendaction = 0; +uniform float SR_brass1_base = 1.000000; +uniform vec3 SR_brass1_base_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_brass1_diffuse_roughness = 0.000000; +uniform float SR_brass1_metalness = 1.000000; +uniform float SR_brass1_specular = 0.000000; +uniform vec3 SR_brass1_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_brass1_specular_IOR = 1.500000; +uniform float SR_brass1_specular_anisotropy = 0.000000; +uniform float SR_brass1_specular_rotation = 0.000000; +uniform float SR_brass1_transmission = 0.000000; +uniform vec3 SR_brass1_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_brass1_transmission_depth = 0.000000; +uniform vec3 SR_brass1_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_brass1_transmission_scatter_anisotropy = 0.000000; +uniform float SR_brass1_transmission_dispersion = 0.000000; +uniform float SR_brass1_transmission_extra_roughness = 0.000000; +uniform float SR_brass1_subsurface = 0.000000; +uniform vec3 SR_brass1_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_brass1_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_brass1_subsurface_scale = 1.000000; +uniform float SR_brass1_subsurface_anisotropy = 0.000000; +uniform float SR_brass1_sheen = 0.000000; +uniform vec3 SR_brass1_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_brass1_sheen_roughness = 0.300000; +uniform float SR_brass1_coat = 1.000000; +uniform float SR_brass1_coat_anisotropy = 0.000000; +uniform float SR_brass1_coat_rotation = 0.000000; +uniform float SR_brass1_coat_IOR = 1.500000; +uniform float SR_brass1_coat_affect_color = 0.000000; +uniform float SR_brass1_coat_affect_roughness = 0.000000; +uniform float SR_brass1_thin_film_thickness = 0.000000; +uniform float SR_brass1_thin_film_IOR = 1.500000; +uniform float SR_brass1_emission = 0.000000; +uniform vec3 SR_brass1_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_brass1_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_brass1_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + +void NG_tiledimage_float(sampler2D file, float default1, vec2 texcoord1, vec2 uvtiling, vec2 uvoffset, vec2 realworldimagesize, vec2 realworldtilesize, int filtertype, int framerange, int frameoffset, int frameendaction, out float out1) +{ + vec2 N_mult_float_out = texcoord1 * uvtiling; + vec2 N_sub_float_out = N_mult_float_out - uvoffset; + vec2 N_divtilesize_float_out = N_sub_float_out / realworldimagesize; + vec2 N_multtilesize_float_out = N_divtilesize_float_out * realworldtilesize; + float N_img_float_out = 0.0; + mx_image_float(file, 0, default1, N_multtilesize_float_out, 2, 2, filtertype, framerange, frameoffset, frameendaction, vec2(1.000000, 1.000000), vec2(0.000000, 0.000000), N_img_float_out); + out1 = N_img_float_out; +} + + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_tiledimage_color3(sampler2D file, vec3 default1, vec2 texcoord1, vec2 uvtiling, vec2 uvoffset, vec2 realworldimagesize, vec2 realworldtilesize, int filtertype, int framerange, int frameoffset, int frameendaction, out vec3 out1) +{ + vec2 N_mult_color3_out = texcoord1 * uvtiling; + vec2 N_sub_color3_out = N_mult_color3_out - uvoffset; + vec2 N_divtilesize_color3_out = N_sub_color3_out / realworldimagesize; + vec2 N_multtilesize_color3_out = N_divtilesize_color3_out * realworldtilesize; + vec3 N_img_color3_out = vec3(0.0); + mx_image_color3(file, 0, default1, N_multtilesize_color3_out, 2, 2, filtertype, framerange, frameoffset, frameendaction, vec2(1.000000, 1.000000), vec2(0.000000, 0.000000), N_img_color3_out); + out1 = N_img_color3_out; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + float image_roughness_out = 0.0; + NG_tiledimage_float(image_roughness_file, image_roughness_default, geomprop_UV0_out1, image_roughness_uvtiling, image_roughness_uvoffset, image_roughness_realworldimagesize, image_roughness_realworldtilesize, image_roughness_filtertype, image_roughness_framerange, image_roughness_frameoffset, image_roughness_frameendaction, image_roughness_out); + vec3 image_color_out = vec3(0.0); + NG_tiledimage_color3(image_color_file, image_color_default, geomprop_UV0_out1, image_color_uvtiling, image_color_uvoffset, image_color_realworldimagesize, image_color_realworldtilesize, image_color_filtertype, image_color_framerange, image_color_frameoffset, image_color_frameendaction, image_color_out); + vec3 image_color_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(image_color_out, image_color_out_cm_out); + surfaceshader SR_brass1_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_brass1_base, SR_brass1_base_color, SR_brass1_diffuse_roughness, SR_brass1_metalness, SR_brass1_specular, SR_brass1_specular_color, image_roughness_out, SR_brass1_specular_IOR, SR_brass1_specular_anisotropy, SR_brass1_specular_rotation, SR_brass1_transmission, SR_brass1_transmission_color, SR_brass1_transmission_depth, SR_brass1_transmission_scatter, SR_brass1_transmission_scatter_anisotropy, SR_brass1_transmission_dispersion, SR_brass1_transmission_extra_roughness, SR_brass1_subsurface, SR_brass1_subsurface_color, SR_brass1_subsurface_radius, SR_brass1_subsurface_scale, SR_brass1_subsurface_anisotropy, SR_brass1_sheen, SR_brass1_sheen_color, SR_brass1_sheen_roughness, SR_brass1_coat, image_color_out_cm_out, image_roughness_out, SR_brass1_coat_anisotropy, SR_brass1_coat_rotation, SR_brass1_coat_IOR, geomprop_Nworld_out1, SR_brass1_coat_affect_color, SR_brass1_coat_affect_roughness, SR_brass1_thin_film_thickness, SR_brass1_thin_film_IOR, SR_brass1_emission, SR_brass1_emission_color, SR_brass1_opacity, SR_brass1_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_brass1_out); + material Tiled_Brass_out = SR_brass1_out; + out1 = vec4(Tiled_Brass_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Tiled_Brass.glsl.vert b/Materials/Examples/StandardSurface/Tiled_Brass.glsl.vert new file mode 100644 index 0000000000..60b47d493e --- /dev/null +++ b/Materials/Examples/StandardSurface/Tiled_Brass.glsl.vert @@ -0,0 +1,31 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Tiled_Brass.mdl b/Materials/Examples/StandardSurface/Tiled_Brass.mdl new file mode 100644 index 0000000000..525209556a --- /dev/null +++ b/Materials/Examples/StandardSurface/Tiled_Brass.mdl @@ -0,0 +1,480 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +float NG_tiledimage_float +( + uniform texture_2d file = texture_2d(), + float default1 = 0.000000, + float2 texcoord = float2(state::texture_coordinate(0).x, state::texture_coordinate(0).y), + float2 uvtiling = float2(1.000000, 1.000000), + float2 uvoffset = float2(0.000000, 0.000000), + float2 realworldimagesize = float2(1.000000, 1.000000), + float2 realworldtilesize = float2(1.000000, 1.000000), + uniform mx_filterlookup_type filtertype = mx_filterlookup_type_linear, + uniform string framerange = "", + uniform int frameoffset = 0, + uniform mx_addressmode_type frameendaction = mx_addressmode_type_constant +) +{ + float2 N_mult_float_out = texcoord * uvtiling; + float2 N_sub_float_out = N_mult_float_out - uvoffset; + float2 N_divtilesize_float_out = N_sub_float_out / realworldimagesize; + float2 N_multtilesize_float_out = N_divtilesize_float_out * realworldtilesize; + float N_img_float_out = materialx::stdlib_1_8::mx_image_float(file, "", default1, N_multtilesize_float_out, mx_addressmode_type_periodic, mx_addressmode_type_periodic, filtertype, framerange, frameoffset, frameendaction, mxp_flip_v:false); + return N_img_float_out; +} + +color NG_tiledimage_color3 +( + uniform texture_2d file = texture_2d(), + color default1 = color(0.000000, 0.000000, 0.000000), + float2 texcoord = float2(state::texture_coordinate(0).x, state::texture_coordinate(0).y), + float2 uvtiling = float2(1.000000, 1.000000), + float2 uvoffset = float2(0.000000, 0.000000), + float2 realworldimagesize = float2(1.000000, 1.000000), + float2 realworldtilesize = float2(1.000000, 1.000000), + uniform mx_filterlookup_type filtertype = mx_filterlookup_type_linear, + uniform string framerange = "", + uniform int frameoffset = 0, + uniform mx_addressmode_type frameendaction = mx_addressmode_type_constant +) +{ + float2 N_mult_color3_out = texcoord * uvtiling; + float2 N_sub_color3_out = N_mult_color3_out - uvoffset; + float2 N_divtilesize_color3_out = N_sub_color3_out / realworldimagesize; + float2 N_multtilesize_color3_out = N_divtilesize_color3_out * realworldtilesize; + color N_img_color3_out = materialx::stdlib_1_8::mx_image_color3(file, "", default1, N_multtilesize_color3_out, mx_addressmode_type_periodic, mx_addressmode_type_periodic, filtertype, framerange, frameoffset, frameendaction, mxp_flip_v:false); + return N_img_color3_out; +} + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Tiled_Brass +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform texture_2d image_roughness_file = texture_2d("../../../Images/brass_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_brass1/image_roughness/file") + ]], + float image_roughness_default = 0.000000 + [[ + materialx::core::origin("NG_brass1/image_roughness/default") + ]], + float2 image_roughness_uvtiling = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_brass1/image_roughness/uvtiling") + ]], + float2 image_roughness_uvoffset = float2(0.000000, 0.000000) + [[ + materialx::core::origin("NG_brass1/image_roughness/uvoffset") + ]], + float2 image_roughness_realworldimagesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_brass1/image_roughness/realworldimagesize") + ]], + float2 image_roughness_realworldtilesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_brass1/image_roughness/realworldtilesize") + ]], + uniform mx_filterlookup_type image_roughness_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_brass1/image_roughness/filtertype") + ]], + uniform string image_roughness_framerange = "" + [[ + materialx::core::origin("NG_brass1/image_roughness/framerange") + ]], + uniform int image_roughness_frameoffset = 0 + [[ + materialx::core::origin("NG_brass1/image_roughness/frameoffset") + ]], + uniform mx_addressmode_type image_roughness_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_brass1/image_roughness/frameendaction") + ]], + uniform texture_2d image_color_file = texture_2d("../../../Images/brass_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_brass1/image_color/file") + ]], + color image_color_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_brass1/image_color/default") + ]], + float2 image_color_uvtiling = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_brass1/image_color/uvtiling") + ]], + float2 image_color_uvoffset = float2(0.000000, 0.000000) + [[ + materialx::core::origin("NG_brass1/image_color/uvoffset") + ]], + float2 image_color_realworldimagesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_brass1/image_color/realworldimagesize") + ]], + float2 image_color_realworldtilesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_brass1/image_color/realworldtilesize") + ]], + uniform mx_filterlookup_type image_color_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_brass1/image_color/filtertype") + ]], + uniform string image_color_framerange = "" + [[ + materialx::core::origin("NG_brass1/image_color/framerange") + ]], + uniform int image_color_frameoffset = 0 + [[ + materialx::core::origin("NG_brass1/image_color/frameoffset") + ]], + uniform mx_addressmode_type image_color_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_brass1/image_color/frameendaction") + ]], + float SR_brass1_base = 1.000000 + [[ + materialx::core::origin("SR_brass1/base") + ]], + color SR_brass1_base_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_brass1/base_color") + ]], + float SR_brass1_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_brass1/diffuse_roughness") + ]], + float SR_brass1_metalness = 1.000000 + [[ + materialx::core::origin("SR_brass1/metalness") + ]], + float SR_brass1_specular = 0.000000 + [[ + materialx::core::origin("SR_brass1/specular") + ]], + color SR_brass1_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_brass1/specular_color") + ]], + uniform float SR_brass1_specular_IOR = 1.500000 + [[ + materialx::core::origin("SR_brass1/specular_IOR") + ]], + float SR_brass1_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_brass1/specular_anisotropy") + ]], + float SR_brass1_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_brass1/specular_rotation") + ]], + float SR_brass1_transmission = 0.000000 + [[ + materialx::core::origin("SR_brass1/transmission") + ]], + color SR_brass1_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_brass1/transmission_color") + ]], + float SR_brass1_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_brass1/transmission_depth") + ]], + color SR_brass1_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_brass1/transmission_scatter") + ]], + float SR_brass1_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_brass1/transmission_scatter_anisotropy") + ]], + float SR_brass1_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_brass1/transmission_dispersion") + ]], + float SR_brass1_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_brass1/transmission_extra_roughness") + ]], + float SR_brass1_subsurface = 0.000000 + [[ + materialx::core::origin("SR_brass1/subsurface") + ]], + color SR_brass1_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_brass1/subsurface_color") + ]], + color SR_brass1_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_brass1/subsurface_radius") + ]], + float SR_brass1_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_brass1/subsurface_scale") + ]], + float SR_brass1_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_brass1/subsurface_anisotropy") + ]], + float SR_brass1_sheen = 0.000000 + [[ + materialx::core::origin("SR_brass1/sheen") + ]], + color SR_brass1_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_brass1/sheen_color") + ]], + float SR_brass1_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_brass1/sheen_roughness") + ]], + float SR_brass1_coat = 1.000000 + [[ + materialx::core::origin("SR_brass1/coat") + ]], + float SR_brass1_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_brass1/coat_anisotropy") + ]], + float SR_brass1_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_brass1/coat_rotation") + ]], + uniform float SR_brass1_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_brass1/coat_IOR") + ]], + float SR_brass1_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_brass1/coat_affect_color") + ]], + float SR_brass1_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_brass1/coat_affect_roughness") + ]], + float SR_brass1_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_brass1/thin_film_thickness") + ]], + float SR_brass1_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_brass1/thin_film_IOR") + ]], + float SR_brass1_emission = 0.000000 + [[ + materialx::core::origin("SR_brass1/emission") + ]], + color SR_brass1_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_brass1/emission_color") + ]], + color SR_brass1_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_brass1/opacity") + ]], + bool SR_brass1_thin_walled = false + [[ + materialx::core::origin("SR_brass1/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + float image_roughness_out = NG_tiledimage_float(image_roughness_file, image_roughness_default, geomprop_UV0_out1, image_roughness_uvtiling, image_roughness_uvoffset, image_roughness_realworldimagesize, image_roughness_realworldtilesize, image_roughness_filtertype, image_roughness_framerange, image_roughness_frameoffset, image_roughness_frameendaction); + color image_color_out = NG_tiledimage_color3(image_color_file, image_color_default, geomprop_UV0_out1, image_color_uvtiling, image_color_uvoffset, image_color_realworldimagesize, image_color_realworldtilesize, image_color_filtertype, image_color_framerange, image_color_frameoffset, image_color_frameendaction); + color image_color_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(image_color_out); + material SR_brass1_out = NG_standard_surface_surfaceshader_100(SR_brass1_base, SR_brass1_base_color, SR_brass1_diffuse_roughness, SR_brass1_metalness, SR_brass1_specular, SR_brass1_specular_color, image_roughness_out, SR_brass1_specular_IOR, SR_brass1_specular_anisotropy, SR_brass1_specular_rotation, SR_brass1_transmission, SR_brass1_transmission_color, SR_brass1_transmission_depth, SR_brass1_transmission_scatter, SR_brass1_transmission_scatter_anisotropy, SR_brass1_transmission_dispersion, SR_brass1_transmission_extra_roughness, SR_brass1_subsurface, SR_brass1_subsurface_color, SR_brass1_subsurface_radius, SR_brass1_subsurface_scale, SR_brass1_subsurface_anisotropy, SR_brass1_sheen, SR_brass1_sheen_color, SR_brass1_sheen_roughness, SR_brass1_coat, image_color_out_cm_out, image_roughness_out, SR_brass1_coat_anisotropy, SR_brass1_coat_rotation, SR_brass1_coat_IOR, geomprop_Nworld_out1, SR_brass1_coat_affect_color, SR_brass1_coat_affect_roughness, SR_brass1_thin_film_thickness, SR_brass1_thin_film_IOR, SR_brass1_emission, SR_brass1_emission_color, SR_brass1_opacity, SR_brass1_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Tiled_Brass_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_brass1_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Tiled_Brass_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Tiled_Brass.msl.frag b/Materials/Examples/StandardSurface/Tiled_Brass.msl.frag new file mode 100644 index 0000000000..14e228c4b3 --- /dev/null +++ b/Materials/Examples/StandardSurface/Tiled_Brass.msl.frag @@ -0,0 +1,2755 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + float image_roughness_default; + vec2 image_roughness_uvtiling; + vec2 image_roughness_uvoffset; + vec2 image_roughness_realworldimagesize; + vec2 image_roughness_realworldtilesize; + int image_roughness_filtertype; + int image_roughness_framerange; + int image_roughness_frameoffset; + int image_roughness_frameendaction; + vec3 image_color_default; + vec2 image_color_uvtiling; + vec2 image_color_uvoffset; + vec2 image_color_realworldimagesize; + vec2 image_color_realworldtilesize; + int image_color_filtertype; + int image_color_framerange; + int image_color_frameoffset; + int image_color_frameendaction; + float SR_brass1_base; + vec3 SR_brass1_base_color; + float SR_brass1_diffuse_roughness; + float SR_brass1_metalness; + float SR_brass1_specular; + vec3 SR_brass1_specular_color; + float SR_brass1_specular_IOR; + float SR_brass1_specular_anisotropy; + float SR_brass1_specular_rotation; + float SR_brass1_transmission; + vec3 SR_brass1_transmission_color; + float SR_brass1_transmission_depth; + vec3 SR_brass1_transmission_scatter; + float SR_brass1_transmission_scatter_anisotropy; + float SR_brass1_transmission_dispersion; + float SR_brass1_transmission_extra_roughness; + float SR_brass1_subsurface; + vec3 SR_brass1_subsurface_color; + vec3 SR_brass1_subsurface_radius; + float SR_brass1_subsurface_scale; + float SR_brass1_subsurface_anisotropy; + float SR_brass1_sheen; + vec3 SR_brass1_sheen_color; + float SR_brass1_sheen_roughness; + float SR_brass1_coat; + float SR_brass1_coat_anisotropy; + float SR_brass1_coat_rotation; + float SR_brass1_coat_IOR; + float SR_brass1_coat_affect_color; + float SR_brass1_coat_affect_roughness; + float SR_brass1_thin_film_thickness; + float SR_brass1_thin_film_IOR; + float SR_brass1_emission; + vec3 SR_brass1_emission_color; + vec3 SR_brass1_opacity; + bool SR_brass1_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture image_roughness_file , float image_roughness_default + + , vec2 image_roughness_uvtiling + + , vec2 image_roughness_uvoffset + + , vec2 image_roughness_realworldimagesize + + , vec2 image_roughness_realworldtilesize + + , int image_roughness_filtertype + + , int image_roughness_framerange + + , int image_roughness_frameoffset + + , int image_roughness_frameendaction + +, MetalTexture image_color_file , vec3 image_color_default + + , vec2 image_color_uvtiling + + , vec2 image_color_uvoffset + + , vec2 image_color_realworldimagesize + + , vec2 image_color_realworldtilesize + + , int image_color_filtertype + + , int image_color_framerange + + , int image_color_frameoffset + + , int image_color_frameendaction + + , float SR_brass1_base + + , vec3 SR_brass1_base_color + + , float SR_brass1_diffuse_roughness + + , float SR_brass1_metalness + + , float SR_brass1_specular + + , vec3 SR_brass1_specular_color + + , float SR_brass1_specular_IOR + + , float SR_brass1_specular_anisotropy + + , float SR_brass1_specular_rotation + + , float SR_brass1_transmission + + , vec3 SR_brass1_transmission_color + + , float SR_brass1_transmission_depth + + , vec3 SR_brass1_transmission_scatter + + , float SR_brass1_transmission_scatter_anisotropy + + , float SR_brass1_transmission_dispersion + + , float SR_brass1_transmission_extra_roughness + + , float SR_brass1_subsurface + + , vec3 SR_brass1_subsurface_color + + , vec3 SR_brass1_subsurface_radius + + , float SR_brass1_subsurface_scale + + , float SR_brass1_subsurface_anisotropy + + , float SR_brass1_sheen + + , vec3 SR_brass1_sheen_color + + , float SR_brass1_sheen_roughness + + , float SR_brass1_coat + + , float SR_brass1_coat_anisotropy + + , float SR_brass1_coat_rotation + + , float SR_brass1_coat_IOR + + , float SR_brass1_coat_affect_color + + , float SR_brass1_coat_affect_roughness + + , float SR_brass1_thin_film_thickness + + , float SR_brass1_thin_film_IOR + + , float SR_brass1_emission + + , vec3 SR_brass1_emission_color + + , vec3 SR_brass1_opacity + + , bool SR_brass1_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, image_roughness_file(image_roughness_file) + , image_roughness_default(image_roughness_default) + + , image_roughness_uvtiling(image_roughness_uvtiling) + + , image_roughness_uvoffset(image_roughness_uvoffset) + + , image_roughness_realworldimagesize(image_roughness_realworldimagesize) + + , image_roughness_realworldtilesize(image_roughness_realworldtilesize) + + , image_roughness_filtertype(image_roughness_filtertype) + + , image_roughness_framerange(image_roughness_framerange) + + , image_roughness_frameoffset(image_roughness_frameoffset) + + , image_roughness_frameendaction(image_roughness_frameendaction) + +, image_color_file(image_color_file) + , image_color_default(image_color_default) + + , image_color_uvtiling(image_color_uvtiling) + + , image_color_uvoffset(image_color_uvoffset) + + , image_color_realworldimagesize(image_color_realworldimagesize) + + , image_color_realworldtilesize(image_color_realworldtilesize) + + , image_color_filtertype(image_color_filtertype) + + , image_color_framerange(image_color_framerange) + + , image_color_frameoffset(image_color_frameoffset) + + , image_color_frameendaction(image_color_frameendaction) + + , SR_brass1_base(SR_brass1_base) + + , SR_brass1_base_color(SR_brass1_base_color) + + , SR_brass1_diffuse_roughness(SR_brass1_diffuse_roughness) + + , SR_brass1_metalness(SR_brass1_metalness) + + , SR_brass1_specular(SR_brass1_specular) + + , SR_brass1_specular_color(SR_brass1_specular_color) + + , SR_brass1_specular_IOR(SR_brass1_specular_IOR) + + , SR_brass1_specular_anisotropy(SR_brass1_specular_anisotropy) + + , SR_brass1_specular_rotation(SR_brass1_specular_rotation) + + , SR_brass1_transmission(SR_brass1_transmission) + + , SR_brass1_transmission_color(SR_brass1_transmission_color) + + , SR_brass1_transmission_depth(SR_brass1_transmission_depth) + + , SR_brass1_transmission_scatter(SR_brass1_transmission_scatter) + + , SR_brass1_transmission_scatter_anisotropy(SR_brass1_transmission_scatter_anisotropy) + + , SR_brass1_transmission_dispersion(SR_brass1_transmission_dispersion) + + , SR_brass1_transmission_extra_roughness(SR_brass1_transmission_extra_roughness) + + , SR_brass1_subsurface(SR_brass1_subsurface) + + , SR_brass1_subsurface_color(SR_brass1_subsurface_color) + + , SR_brass1_subsurface_radius(SR_brass1_subsurface_radius) + + , SR_brass1_subsurface_scale(SR_brass1_subsurface_scale) + + , SR_brass1_subsurface_anisotropy(SR_brass1_subsurface_anisotropy) + + , SR_brass1_sheen(SR_brass1_sheen) + + , SR_brass1_sheen_color(SR_brass1_sheen_color) + + , SR_brass1_sheen_roughness(SR_brass1_sheen_roughness) + + , SR_brass1_coat(SR_brass1_coat) + + , SR_brass1_coat_anisotropy(SR_brass1_coat_anisotropy) + + , SR_brass1_coat_rotation(SR_brass1_coat_rotation) + + , SR_brass1_coat_IOR(SR_brass1_coat_IOR) + + , SR_brass1_coat_affect_color(SR_brass1_coat_affect_color) + + , SR_brass1_coat_affect_roughness(SR_brass1_coat_affect_roughness) + + , SR_brass1_thin_film_thickness(SR_brass1_thin_film_thickness) + + , SR_brass1_thin_film_IOR(SR_brass1_thin_film_IOR) + + , SR_brass1_emission(SR_brass1_emission) + + , SR_brass1_emission_color(SR_brass1_emission_color) + + , SR_brass1_opacity(SR_brass1_opacity) + + , SR_brass1_thin_walled(SR_brass1_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture image_roughness_file; + float image_roughness_default; + + + vec2 image_roughness_uvtiling; + + + vec2 image_roughness_uvoffset; + + + vec2 image_roughness_realworldimagesize; + + + vec2 image_roughness_realworldtilesize; + + + int image_roughness_filtertype; + + + int image_roughness_framerange; + + + int image_roughness_frameoffset; + + + int image_roughness_frameendaction; + + +MetalTexture image_color_file; + vec3 image_color_default; + + + vec2 image_color_uvtiling; + + + vec2 image_color_uvoffset; + + + vec2 image_color_realworldimagesize; + + + vec2 image_color_realworldtilesize; + + + int image_color_filtertype; + + + int image_color_framerange; + + + int image_color_frameoffset; + + + int image_color_frameendaction; + + + float SR_brass1_base; + + + vec3 SR_brass1_base_color; + + + float SR_brass1_diffuse_roughness; + + + float SR_brass1_metalness; + + + float SR_brass1_specular; + + + vec3 SR_brass1_specular_color; + + + float SR_brass1_specular_IOR; + + + float SR_brass1_specular_anisotropy; + + + float SR_brass1_specular_rotation; + + + float SR_brass1_transmission; + + + vec3 SR_brass1_transmission_color; + + + float SR_brass1_transmission_depth; + + + vec3 SR_brass1_transmission_scatter; + + + float SR_brass1_transmission_scatter_anisotropy; + + + float SR_brass1_transmission_dispersion; + + + float SR_brass1_transmission_extra_roughness; + + + float SR_brass1_subsurface; + + + vec3 SR_brass1_subsurface_color; + + + vec3 SR_brass1_subsurface_radius; + + + float SR_brass1_subsurface_scale; + + + float SR_brass1_subsurface_anisotropy; + + + float SR_brass1_sheen; + + + vec3 SR_brass1_sheen_color; + + + float SR_brass1_sheen_roughness; + + + float SR_brass1_coat; + + + float SR_brass1_coat_anisotropy; + + + float SR_brass1_coat_rotation; + + + float SR_brass1_coat_IOR; + + + float SR_brass1_coat_affect_color; + + + float SR_brass1_coat_affect_roughness; + + + float SR_brass1_thin_film_thickness; + + + float SR_brass1_thin_film_IOR; + + + float SR_brass1_emission; + + + vec3 SR_brass1_emission_color; + + + vec3 SR_brass1_opacity; + + + bool SR_brass1_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + void NG_tiledimage_float(MetalTexture file, float default1, vec2 texcoord1, vec2 uvtiling, vec2 uvoffset, vec2 realworldimagesize, vec2 realworldtilesize, int filtertype, int framerange, int frameoffset, int frameendaction, thread float& out1) + { + vec2 N_mult_float_out = texcoord1 * uvtiling; + vec2 N_sub_float_out = N_mult_float_out - uvoffset; + vec2 N_divtilesize_float_out = N_sub_float_out / realworldimagesize; + vec2 N_multtilesize_float_out = N_divtilesize_float_out * realworldtilesize; + float N_img_float_out = 0.0; + mx_image_float(file, 0, default1, N_multtilesize_float_out, 2, 2, filtertype, framerange, frameoffset, frameendaction, vec2(1.000000, 1.000000), vec2(0.000000, 0.000000), N_img_float_out); + out1 = N_img_float_out; + } + + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_tiledimage_color3(MetalTexture file, vec3 default1, vec2 texcoord1, vec2 uvtiling, vec2 uvoffset, vec2 realworldimagesize, vec2 realworldtilesize, int filtertype, int framerange, int frameoffset, int frameendaction, thread vec3& out1) + { + vec2 N_mult_color3_out = texcoord1 * uvtiling; + vec2 N_sub_color3_out = N_mult_color3_out - uvoffset; + vec2 N_divtilesize_color3_out = N_sub_color3_out / realworldimagesize; + vec2 N_multtilesize_color3_out = N_divtilesize_color3_out * realworldtilesize; + vec3 N_img_color3_out = vec3(0.0); + mx_image_color3(file, 0, default1, N_multtilesize_color3_out, 2, 2, filtertype, framerange, frameoffset, frameendaction, vec2(1.000000, 1.000000), vec2(0.000000, 0.000000), N_img_color3_out); + out1 = N_img_color3_out; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + float image_roughness_out = 0.0; + NG_tiledimage_float(image_roughness_file, image_roughness_default, geomprop_UV0_out1, image_roughness_uvtiling, image_roughness_uvoffset, image_roughness_realworldimagesize, image_roughness_realworldtilesize, image_roughness_filtertype, image_roughness_framerange, image_roughness_frameoffset, image_roughness_frameendaction, image_roughness_out); + vec3 image_color_out = vec3(0.0); + NG_tiledimage_color3(image_color_file, image_color_default, geomprop_UV0_out1, image_color_uvtiling, image_color_uvoffset, image_color_realworldimagesize, image_color_realworldtilesize, image_color_filtertype, image_color_framerange, image_color_frameoffset, image_color_frameendaction, image_color_out); + vec3 image_color_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(image_color_out, image_color_out_cm_out); + surfaceshader SR_brass1_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_brass1_base, SR_brass1_base_color, SR_brass1_diffuse_roughness, SR_brass1_metalness, SR_brass1_specular, SR_brass1_specular_color, image_roughness_out, SR_brass1_specular_IOR, SR_brass1_specular_anisotropy, SR_brass1_specular_rotation, SR_brass1_transmission, SR_brass1_transmission_color, SR_brass1_transmission_depth, SR_brass1_transmission_scatter, SR_brass1_transmission_scatter_anisotropy, SR_brass1_transmission_dispersion, SR_brass1_transmission_extra_roughness, SR_brass1_subsurface, SR_brass1_subsurface_color, SR_brass1_subsurface_radius, SR_brass1_subsurface_scale, SR_brass1_subsurface_anisotropy, SR_brass1_sheen, SR_brass1_sheen_color, SR_brass1_sheen_roughness, SR_brass1_coat, image_color_out_cm_out, image_roughness_out, SR_brass1_coat_anisotropy, SR_brass1_coat_rotation, SR_brass1_coat_IOR, geomprop_Nworld_out1, SR_brass1_coat_affect_color, SR_brass1_coat_affect_roughness, SR_brass1_thin_film_thickness, SR_brass1_thin_film_IOR, SR_brass1_emission, SR_brass1_emission_color, SR_brass1_opacity, SR_brass1_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_brass1_out); + material Tiled_Brass_out = SR_brass1_out; + out1 = float4(Tiled_Brass_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d image_roughness_file_tex [[texture(0)]], sampler image_roughness_file_sampler [[sampler(0)]] +, texture2d image_color_file_tex [[texture(1)]], sampler image_color_file_sampler [[sampler(1)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(2)]], sampler u_envRadiance_sampler [[sampler(2)]] +, texture2d u_envIrradiance_tex [[texture(3)]], sampler u_envIrradiance_sampler [[sampler(3)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +image_roughness_file_tex, image_roughness_file_sampler } + , u_pub.image_roughness_default + , u_pub.image_roughness_uvtiling + , u_pub.image_roughness_uvoffset + , u_pub.image_roughness_realworldimagesize + , u_pub.image_roughness_realworldtilesize + , u_pub.image_roughness_filtertype + , u_pub.image_roughness_framerange + , u_pub.image_roughness_frameoffset + , u_pub.image_roughness_frameendaction +, MetalTexture { +image_color_file_tex, image_color_file_sampler } + , u_pub.image_color_default + , u_pub.image_color_uvtiling + , u_pub.image_color_uvoffset + , u_pub.image_color_realworldimagesize + , u_pub.image_color_realworldtilesize + , u_pub.image_color_filtertype + , u_pub.image_color_framerange + , u_pub.image_color_frameoffset + , u_pub.image_color_frameendaction + , u_pub.SR_brass1_base + , u_pub.SR_brass1_base_color + , u_pub.SR_brass1_diffuse_roughness + , u_pub.SR_brass1_metalness + , u_pub.SR_brass1_specular + , u_pub.SR_brass1_specular_color + , u_pub.SR_brass1_specular_IOR + , u_pub.SR_brass1_specular_anisotropy + , u_pub.SR_brass1_specular_rotation + , u_pub.SR_brass1_transmission + , u_pub.SR_brass1_transmission_color + , u_pub.SR_brass1_transmission_depth + , u_pub.SR_brass1_transmission_scatter + , u_pub.SR_brass1_transmission_scatter_anisotropy + , u_pub.SR_brass1_transmission_dispersion + , u_pub.SR_brass1_transmission_extra_roughness + , u_pub.SR_brass1_subsurface + , u_pub.SR_brass1_subsurface_color + , u_pub.SR_brass1_subsurface_radius + , u_pub.SR_brass1_subsurface_scale + , u_pub.SR_brass1_subsurface_anisotropy + , u_pub.SR_brass1_sheen + , u_pub.SR_brass1_sheen_color + , u_pub.SR_brass1_sheen_roughness + , u_pub.SR_brass1_coat + , u_pub.SR_brass1_coat_anisotropy + , u_pub.SR_brass1_coat_rotation + , u_pub.SR_brass1_coat_IOR + , u_pub.SR_brass1_coat_affect_color + , u_pub.SR_brass1_coat_affect_roughness + , u_pub.SR_brass1_thin_film_thickness + , u_pub.SR_brass1_thin_film_IOR + , u_pub.SR_brass1_emission + , u_pub.SR_brass1_emission_color + , u_pub.SR_brass1_opacity + , u_pub.SR_brass1_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Tiled_Brass.msl.vert b/Materials/Examples/StandardSurface/Tiled_Brass.msl.vert new file mode 100644 index 0000000000..8559715987 --- /dev/null +++ b/Materials/Examples/StandardSurface/Tiled_Brass.msl.vert @@ -0,0 +1,121 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'image_roughness'. Function already called in this scope. + // Omitted node 'image_color'. Function already called in this scope. + // Omitted node 'image_color_out_cm'. Function already called in this scope. + // Omitted node 'SR_brass1'. Function already called in this scope. + // Omitted node 'Tiled_Brass'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Tiled_Brass.osl b/Materials/Examples/StandardSurface/Tiled_Brass.osl new file mode 100644 index 0000000000..a1b6c544de --- /dev/null +++ b/Materials/Examples/StandardSurface/Tiled_Brass.osl @@ -0,0 +1,609 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + +void NG_tiledimage_float(textureresource file, float default1, vector2 texcoord, vector2 uvtiling, vector2 uvoffset, vector2 realworldimagesize, vector2 realworldtilesize, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + vector2 N_mult_float_out = texcoord * uvtiling; + vector2 N_sub_float_out = N_mult_float_out - uvoffset; + vector2 N_divtilesize_float_out = N_sub_float_out / realworldimagesize; + vector2 N_multtilesize_float_out = N_divtilesize_float_out * realworldtilesize; + float N_img_float_out = 0.0; + mx_image_float(file, "", default1, N_multtilesize_float_out, "periodic", "periodic", filtertype, framerange, frameoffset, frameendaction, N_img_float_out); + out = N_img_float_out; +} + + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + +void NG_tiledimage_color3(textureresource file, color default1, vector2 texcoord, vector2 uvtiling, vector2 uvoffset, vector2 realworldimagesize, vector2 realworldtilesize, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + vector2 N_mult_color3_out = texcoord * uvtiling; + vector2 N_sub_color3_out = N_mult_color3_out - uvoffset; + vector2 N_divtilesize_color3_out = N_sub_color3_out / realworldimagesize; + vector2 N_multtilesize_color3_out = N_divtilesize_color3_out * realworldtilesize; + color N_img_color3_out = color(0.0); + mx_image_color3(file, "", default1, N_multtilesize_color3_out, "periodic", "periodic", filtertype, framerange, frameoffset, frameendaction, N_img_color3_out); + out = N_img_color3_out; +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Tiled_Brass +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Tiled_Brass" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string image_roughness_file = "../../../Images/brass_roughness.jpg" + [[ + string widget = "filename" + ]], + string image_roughness_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + float image_roughness_default = 0.000000 + [[ + string widget = "number" + ]], + vector2 image_roughness_uvtiling = {1.000000, 1.000000}, + vector2 image_roughness_uvoffset = {0.000000, 0.000000}, + vector2 image_roughness_realworldimagesize = {1.000000, 1.000000}, + vector2 image_roughness_realworldtilesize = {1.000000, 1.000000}, + string image_roughness_filtertype = "linear", + string image_roughness_framerange = "", + int image_roughness_frameoffset = 0 + [[ + string widget = "number" + ]], + string image_roughness_frameendaction = "constant", + string image_color_file = "../../../Images/brass_color.jpg" + [[ + string widget = "filename" + ]], + string image_color_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + color image_color_default = color(0.000000, 0.000000, 0.000000), + vector2 image_color_uvtiling = {1.000000, 1.000000}, + vector2 image_color_uvoffset = {0.000000, 0.000000}, + vector2 image_color_realworldimagesize = {1.000000, 1.000000}, + vector2 image_color_realworldtilesize = {1.000000, 1.000000}, + string image_color_filtertype = "linear", + string image_color_framerange = "", + int image_color_frameoffset = 0 + [[ + string widget = "number" + ]], + string image_color_frameendaction = "constant", + float SR_brass1_base = 1.000000 + [[ + string widget = "number" + ]], + color SR_brass1_base_color = color(1.000000, 1.000000, 1.000000), + float SR_brass1_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_brass1_metalness = 1.000000 + [[ + string widget = "number" + ]], + float SR_brass1_specular = 0.000000 + [[ + string widget = "number" + ]], + color SR_brass1_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_brass1_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_brass1_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_brass1_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_brass1_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_brass1_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_brass1_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_brass1_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_brass1_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_brass1_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_brass1_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_brass1_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_brass1_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_brass1_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_brass1_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_brass1_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_brass1_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_brass1_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_brass1_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_brass1_coat = 1.000000 + [[ + string widget = "number" + ]], + float SR_brass1_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_brass1_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_brass1_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_brass1_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_brass1_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_brass1_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_brass1_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_brass1_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_brass1_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_brass1_opacity = color(1.000000, 1.000000, 1.000000), + int SR_brass1_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource image_roughness_file_ = {image_roughness_file, image_roughness_file_colorspace}; + textureresource image_color_file_ = {image_color_file, image_color_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + float image_roughness_out = 0.0; + NG_tiledimage_float(image_roughness_file_, image_roughness_default, geomprop_UV0_out1, image_roughness_uvtiling, image_roughness_uvoffset, image_roughness_realworldimagesize, image_roughness_realworldtilesize, image_roughness_filtertype, image_roughness_framerange, image_roughness_frameoffset, image_roughness_frameendaction, image_roughness_out); + color image_color_out = color(0.0); + NG_tiledimage_color3(image_color_file_, image_color_default, geomprop_UV0_out1, image_color_uvtiling, image_color_uvoffset, image_color_realworldimagesize, image_color_realworldtilesize, image_color_filtertype, image_color_framerange, image_color_frameoffset, image_color_frameendaction, image_color_out); + color image_color_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(image_color_out, image_color_out_cm_out); + surfaceshader SR_brass1_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_brass1_base, SR_brass1_base_color, SR_brass1_diffuse_roughness, SR_brass1_metalness, SR_brass1_specular, SR_brass1_specular_color, image_roughness_out, SR_brass1_specular_IOR, SR_brass1_specular_anisotropy, SR_brass1_specular_rotation, SR_brass1_transmission, SR_brass1_transmission_color, SR_brass1_transmission_depth, SR_brass1_transmission_scatter, SR_brass1_transmission_scatter_anisotropy, SR_brass1_transmission_dispersion, SR_brass1_transmission_extra_roughness, SR_brass1_subsurface, SR_brass1_subsurface_color, SR_brass1_subsurface_radius, SR_brass1_subsurface_scale, SR_brass1_subsurface_anisotropy, SR_brass1_sheen, SR_brass1_sheen_color, SR_brass1_sheen_roughness, SR_brass1_coat, image_color_out_cm_out, image_roughness_out, SR_brass1_coat_anisotropy, SR_brass1_coat_rotation, SR_brass1_coat_IOR, geomprop_Nworld_out1, SR_brass1_coat_affect_color, SR_brass1_coat_affect_roughness, SR_brass1_thin_film_thickness, SR_brass1_thin_film_IOR, SR_brass1_emission, SR_brass1_emission_color, SR_brass1_opacity, SR_brass1_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_brass1_out); + MATERIAL Tiled_Brass_out = mx_surfacematerial(SR_brass1_out, backsurfaceshader, displacementshader1); + out = Tiled_Brass_out; +} + diff --git a/Materials/Examples/StandardSurface/Tiled_Wood.glsl.frag b/Materials/Examples/StandardSurface/Tiled_Wood.glsl.frag new file mode 100644 index 0000000000..e0eb8d4e33 --- /dev/null +++ b/Materials/Examples/StandardSurface/Tiled_Wood.glsl.frag @@ -0,0 +1,1984 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform int geomprop_UV0_index = 0; +uniform sampler2D image_color_file; +uniform vec3 image_color_default = vec3(0.000000, 0.000000, 0.000000); +uniform vec2 image_color_uvtiling = vec2(4.000000, 4.000000); +uniform vec2 image_color_uvoffset = vec2(0.000000, 0.000000); +uniform vec2 image_color_realworldimagesize = vec2(1.000000, 1.000000); +uniform vec2 image_color_realworldtilesize = vec2(1.000000, 1.000000); +uniform int image_color_filtertype = 1; +uniform int image_color_framerange = 0; +uniform int image_color_frameoffset = 0; +uniform int image_color_frameendaction = 0; +uniform sampler2D image_roughness_file; +uniform float image_roughness_default = 0.000000; +uniform vec2 image_roughness_uvtiling = vec2(4.000000, 4.000000); +uniform vec2 image_roughness_uvoffset = vec2(0.000000, 0.000000); +uniform vec2 image_roughness_realworldimagesize = vec2(1.000000, 1.000000); +uniform vec2 image_roughness_realworldtilesize = vec2(1.000000, 1.000000); +uniform int image_roughness_filtertype = 1; +uniform int image_roughness_framerange = 0; +uniform int image_roughness_frameoffset = 0; +uniform int image_roughness_frameendaction = 0; +uniform float SR_wood1_base = 1.000000; +uniform float SR_wood1_diffuse_roughness = 0.000000; +uniform float SR_wood1_metalness = 0.000000; +uniform float SR_wood1_specular = 0.400000; +uniform vec3 SR_wood1_specular_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_wood1_specular_IOR = 1.500000; +uniform float SR_wood1_specular_anisotropy = 0.500000; +uniform float SR_wood1_specular_rotation = 0.000000; +uniform float SR_wood1_transmission = 0.000000; +uniform vec3 SR_wood1_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_wood1_transmission_depth = 0.000000; +uniform vec3 SR_wood1_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_wood1_transmission_scatter_anisotropy = 0.000000; +uniform float SR_wood1_transmission_dispersion = 0.000000; +uniform float SR_wood1_transmission_extra_roughness = 0.000000; +uniform float SR_wood1_subsurface = 0.000000; +uniform vec3 SR_wood1_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_wood1_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_wood1_subsurface_scale = 1.000000; +uniform float SR_wood1_subsurface_anisotropy = 0.000000; +uniform float SR_wood1_sheen = 0.000000; +uniform vec3 SR_wood1_sheen_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_wood1_sheen_roughness = 0.300000; +uniform float SR_wood1_coat = 0.100000; +uniform vec3 SR_wood1_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_wood1_coat_roughness = 0.200000; +uniform float SR_wood1_coat_anisotropy = 0.500000; +uniform float SR_wood1_coat_rotation = 0.000000; +uniform float SR_wood1_coat_IOR = 1.500000; +uniform float SR_wood1_coat_affect_color = 0.000000; +uniform float SR_wood1_coat_affect_roughness = 0.000000; +uniform float SR_wood1_thin_film_thickness = 0.000000; +uniform float SR_wood1_thin_film_IOR = 1.500000; +uniform float SR_wood1_emission = 0.000000; +uniform vec3 SR_wood1_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_wood1_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_wood1_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) +{ + uv = uv * uv_scale + uv_offset; + return uv; +} + +void mx_image_color3(sampler2D tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out vec3 result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; +} + +void NG_tiledimage_color3(sampler2D file, vec3 default1, vec2 texcoord1, vec2 uvtiling, vec2 uvoffset, vec2 realworldimagesize, vec2 realworldtilesize, int filtertype, int framerange, int frameoffset, int frameendaction, out vec3 out1) +{ + vec2 N_mult_color3_out = texcoord1 * uvtiling; + vec2 N_sub_color3_out = N_mult_color3_out - uvoffset; + vec2 N_divtilesize_color3_out = N_sub_color3_out / realworldimagesize; + vec2 N_multtilesize_color3_out = N_divtilesize_color3_out * realworldtilesize; + vec3 N_img_color3_out = vec3(0.0); + mx_image_color3(file, 0, default1, N_multtilesize_color3_out, 2, 2, filtertype, framerange, frameoffset, frameendaction, vec2(1.000000, 1.000000), vec2(0.000000, 0.000000), N_img_color3_out); + out1 = N_img_color3_out; +} + + +void mx_image_float(sampler2D tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, out float result) +{ + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; +} + +void NG_tiledimage_float(sampler2D file, float default1, vec2 texcoord1, vec2 uvtiling, vec2 uvoffset, vec2 realworldimagesize, vec2 realworldtilesize, int filtertype, int framerange, int frameoffset, int frameendaction, out float out1) +{ + vec2 N_mult_float_out = texcoord1 * uvtiling; + vec2 N_sub_float_out = N_mult_float_out - uvoffset; + vec2 N_divtilesize_float_out = N_sub_float_out / realworldimagesize; + vec2 N_multtilesize_float_out = N_divtilesize_float_out * realworldtilesize; + float N_img_float_out = 0.0; + mx_image_float(file, 0, default1, N_multtilesize_float_out, 2, 2, filtertype, framerange, frameoffset, frameendaction, vec2(1.000000, 1.000000), vec2(0.000000, 0.000000), N_img_float_out); + out1 = N_img_float_out; +} + +void NG_separate3_color3(vec3 in1, out float outr, out float outg, out float outb) +{ + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, out vec3 out1) +{ + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = vec3(isAboveR_out,isAboveG_out,isAboveB_out); + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 image_color_out = vec3(0.0); + NG_tiledimage_color3(image_color_file, image_color_default, geomprop_UV0_out1, image_color_uvtiling, image_color_uvoffset, image_color_realworldimagesize, image_color_realworldtilesize, image_color_filtertype, image_color_framerange, image_color_frameoffset, image_color_frameendaction, image_color_out); + float image_roughness_out = 0.0; + NG_tiledimage_float(image_roughness_file, image_roughness_default, geomprop_UV0_out1, image_roughness_uvtiling, image_roughness_uvoffset, image_roughness_realworldimagesize, image_roughness_realworldtilesize, image_roughness_filtertype, image_roughness_framerange, image_roughness_frameoffset, image_roughness_frameendaction, image_roughness_out); + vec3 image_color_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(image_color_out, image_color_out_cm_out); + surfaceshader SR_wood1_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_wood1_base, image_color_out_cm_out, SR_wood1_diffuse_roughness, SR_wood1_metalness, SR_wood1_specular, SR_wood1_specular_color, image_roughness_out, SR_wood1_specular_IOR, SR_wood1_specular_anisotropy, SR_wood1_specular_rotation, SR_wood1_transmission, SR_wood1_transmission_color, SR_wood1_transmission_depth, SR_wood1_transmission_scatter, SR_wood1_transmission_scatter_anisotropy, SR_wood1_transmission_dispersion, SR_wood1_transmission_extra_roughness, SR_wood1_subsurface, SR_wood1_subsurface_color, SR_wood1_subsurface_radius, SR_wood1_subsurface_scale, SR_wood1_subsurface_anisotropy, SR_wood1_sheen, SR_wood1_sheen_color, SR_wood1_sheen_roughness, SR_wood1_coat, SR_wood1_coat_color, SR_wood1_coat_roughness, SR_wood1_coat_anisotropy, SR_wood1_coat_rotation, SR_wood1_coat_IOR, geomprop_Nworld_out1, SR_wood1_coat_affect_color, SR_wood1_coat_affect_roughness, SR_wood1_thin_film_thickness, SR_wood1_thin_film_IOR, SR_wood1_emission, SR_wood1_emission_color, SR_wood1_opacity, SR_wood1_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_wood1_out); + material Tiled_Wood_out = SR_wood1_out; + out1 = vec4(Tiled_Wood_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Tiled_Wood.glsl.vert b/Materials/Examples/StandardSurface/Tiled_Wood.glsl.vert new file mode 100644 index 0000000000..60b47d493e --- /dev/null +++ b/Materials/Examples/StandardSurface/Tiled_Wood.glsl.vert @@ -0,0 +1,31 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; +in vec2 i_texcoord_0; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Tiled_Wood.mdl b/Materials/Examples/StandardSurface/Tiled_Wood.mdl new file mode 100644 index 0000000000..6187e7168e --- /dev/null +++ b/Materials/Examples/StandardSurface/Tiled_Wood.mdl @@ -0,0 +1,484 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_tiledimage_color3 +( + uniform texture_2d file = texture_2d(), + color default1 = color(0.000000, 0.000000, 0.000000), + float2 texcoord = float2(state::texture_coordinate(0).x, state::texture_coordinate(0).y), + float2 uvtiling = float2(1.000000, 1.000000), + float2 uvoffset = float2(0.000000, 0.000000), + float2 realworldimagesize = float2(1.000000, 1.000000), + float2 realworldtilesize = float2(1.000000, 1.000000), + uniform mx_filterlookup_type filtertype = mx_filterlookup_type_linear, + uniform string framerange = "", + uniform int frameoffset = 0, + uniform mx_addressmode_type frameendaction = mx_addressmode_type_constant +) +{ + float2 N_mult_color3_out = texcoord * uvtiling; + float2 N_sub_color3_out = N_mult_color3_out - uvoffset; + float2 N_divtilesize_color3_out = N_sub_color3_out / realworldimagesize; + float2 N_multtilesize_color3_out = N_divtilesize_color3_out * realworldtilesize; + color N_img_color3_out = materialx::stdlib_1_8::mx_image_color3(file, "", default1, N_multtilesize_color3_out, mx_addressmode_type_periodic, mx_addressmode_type_periodic, filtertype, framerange, frameoffset, frameendaction, mxp_flip_v:false); + return N_img_color3_out; +} + +float NG_tiledimage_float +( + uniform texture_2d file = texture_2d(), + float default1 = 0.000000, + float2 texcoord = float2(state::texture_coordinate(0).x, state::texture_coordinate(0).y), + float2 uvtiling = float2(1.000000, 1.000000), + float2 uvoffset = float2(0.000000, 0.000000), + float2 realworldimagesize = float2(1.000000, 1.000000), + float2 realworldtilesize = float2(1.000000, 1.000000), + uniform mx_filterlookup_type filtertype = mx_filterlookup_type_linear, + uniform string framerange = "", + uniform int frameoffset = 0, + uniform mx_addressmode_type frameendaction = mx_addressmode_type_constant +) +{ + float2 N_mult_float_out = texcoord * uvtiling; + float2 N_sub_float_out = N_mult_float_out - uvoffset; + float2 N_divtilesize_float_out = N_sub_float_out / realworldimagesize; + float2 N_multtilesize_float_out = N_divtilesize_float_out * realworldtilesize; + float N_img_float_out = materialx::stdlib_1_8::mx_image_float(file, "", default1, N_multtilesize_float_out, mx_addressmode_type_periodic, mx_addressmode_type_periodic, filtertype, framerange, frameoffset, frameendaction, mxp_flip_v:false); + return N_img_float_out; +} + +struct NG_separate3_color3__result +{ + float mxp_outr; + float mxp_outg; + float mxp_outb; +}; + +NG_separate3_color3__result NG_separate3_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + float N_extract_0_out = materialx::stdlib_1_8::mx_extract_color3(in1, 0); + float N_extract_1_out = materialx::stdlib_1_8::mx_extract_color3(in1, 1); + float N_extract_2_out = materialx::stdlib_1_8::mx_extract_color3(in1, 2); + NG_separate3_color3__result result__; + result__.mxp_outr = N_extract_0_out; + result__.mxp_outg = N_extract_1_out; + result__.mxp_outb = N_extract_2_out; + return result__; +} + +color NG_srgb_texture_to_lin_rec709_color3 +( + color in1 = color(0.000000, 0.000000, 0.000000) +) +{ + color bias_out = in1 + 0.055000; + color linSeg_out = in1 / 12.920000; + NG_separate3_color3__result colorSeparate_result = NG_separate3_color3(in1); + color max_out = math::max(bias_out, 0.000000); + float isAboveR_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outr, 0.040450, 1.000000, 0.000000); + float isAboveG_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outg, 0.040450, 1.000000, 0.000000); + float isAboveB_out = materialx::stdlib_1_8::mx_ifgreater_float(colorSeparate_result.mxp_outb, 0.040450, 1.000000, 0.000000); + color scale_out = max_out / 1.055000; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + color powSeg_out = math::pow(scale_out, 2.400000); + color mix_out = math::lerp(linSeg_out, powSeg_out, isAbove_out); + return mix_out; +} + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Tiled_Wood +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_UV0_index = 0 + [[ + materialx::core::origin("UV0") + ]], + uniform texture_2d image_color_file = texture_2d("../../../Images/wood_color.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_wood1/image_color/file") + ]], + color image_color_default = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("NG_wood1/image_color/default") + ]], + float2 image_color_uvtiling = float2(4.000000, 4.000000) + [[ + materialx::core::origin("NG_wood1/image_color/uvtiling") + ]], + float2 image_color_uvoffset = float2(0.000000, 0.000000) + [[ + materialx::core::origin("NG_wood1/image_color/uvoffset") + ]], + float2 image_color_realworldimagesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_wood1/image_color/realworldimagesize") + ]], + float2 image_color_realworldtilesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_wood1/image_color/realworldtilesize") + ]], + uniform mx_filterlookup_type image_color_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_wood1/image_color/filtertype") + ]], + uniform string image_color_framerange = "" + [[ + materialx::core::origin("NG_wood1/image_color/framerange") + ]], + uniform int image_color_frameoffset = 0 + [[ + materialx::core::origin("NG_wood1/image_color/frameoffset") + ]], + uniform mx_addressmode_type image_color_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_wood1/image_color/frameendaction") + ]], + uniform texture_2d image_roughness_file = texture_2d("../../../Images/wood_roughness.jpg", tex::gamma_linear) + [[ + materialx::core::origin("NG_wood1/image_roughness/file") + ]], + float image_roughness_default = 0.000000 + [[ + materialx::core::origin("NG_wood1/image_roughness/default") + ]], + float2 image_roughness_uvtiling = float2(4.000000, 4.000000) + [[ + materialx::core::origin("NG_wood1/image_roughness/uvtiling") + ]], + float2 image_roughness_uvoffset = float2(0.000000, 0.000000) + [[ + materialx::core::origin("NG_wood1/image_roughness/uvoffset") + ]], + float2 image_roughness_realworldimagesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_wood1/image_roughness/realworldimagesize") + ]], + float2 image_roughness_realworldtilesize = float2(1.000000, 1.000000) + [[ + materialx::core::origin("NG_wood1/image_roughness/realworldtilesize") + ]], + uniform mx_filterlookup_type image_roughness_filtertype = mx_filterlookup_type_linear + [[ + materialx::core::origin("NG_wood1/image_roughness/filtertype") + ]], + uniform string image_roughness_framerange = "" + [[ + materialx::core::origin("NG_wood1/image_roughness/framerange") + ]], + uniform int image_roughness_frameoffset = 0 + [[ + materialx::core::origin("NG_wood1/image_roughness/frameoffset") + ]], + uniform mx_addressmode_type image_roughness_frameendaction = mx_addressmode_type_constant + [[ + materialx::core::origin("NG_wood1/image_roughness/frameendaction") + ]], + float SR_wood1_base = 1.000000 + [[ + materialx::core::origin("SR_wood1/base") + ]], + float SR_wood1_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_wood1/diffuse_roughness") + ]], + float SR_wood1_metalness = 0.000000 + [[ + materialx::core::origin("SR_wood1/metalness") + ]], + float SR_wood1_specular = 0.400000 + [[ + materialx::core::origin("SR_wood1/specular") + ]], + color SR_wood1_specular_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_wood1/specular_color") + ]], + uniform float SR_wood1_specular_IOR = 1.500000 + [[ + materialx::core::origin("SR_wood1/specular_IOR") + ]], + float SR_wood1_specular_anisotropy = 0.500000 + [[ + materialx::core::origin("SR_wood1/specular_anisotropy") + ]], + float SR_wood1_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_wood1/specular_rotation") + ]], + float SR_wood1_transmission = 0.000000 + [[ + materialx::core::origin("SR_wood1/transmission") + ]], + color SR_wood1_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_wood1/transmission_color") + ]], + float SR_wood1_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_wood1/transmission_depth") + ]], + color SR_wood1_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_wood1/transmission_scatter") + ]], + float SR_wood1_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_wood1/transmission_scatter_anisotropy") + ]], + float SR_wood1_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_wood1/transmission_dispersion") + ]], + float SR_wood1_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_wood1/transmission_extra_roughness") + ]], + float SR_wood1_subsurface = 0.000000 + [[ + materialx::core::origin("SR_wood1/subsurface") + ]], + color SR_wood1_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_wood1/subsurface_color") + ]], + color SR_wood1_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_wood1/subsurface_radius") + ]], + float SR_wood1_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_wood1/subsurface_scale") + ]], + float SR_wood1_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_wood1/subsurface_anisotropy") + ]], + float SR_wood1_sheen = 0.000000 + [[ + materialx::core::origin("SR_wood1/sheen") + ]], + color SR_wood1_sheen_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_wood1/sheen_color") + ]], + float SR_wood1_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_wood1/sheen_roughness") + ]], + float SR_wood1_coat = 0.100000 + [[ + materialx::core::origin("SR_wood1/coat") + ]], + color SR_wood1_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_wood1/coat_color") + ]], + float SR_wood1_coat_roughness = 0.200000 + [[ + materialx::core::origin("SR_wood1/coat_roughness") + ]], + float SR_wood1_coat_anisotropy = 0.500000 + [[ + materialx::core::origin("SR_wood1/coat_anisotropy") + ]], + float SR_wood1_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_wood1/coat_rotation") + ]], + uniform float SR_wood1_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_wood1/coat_IOR") + ]], + float SR_wood1_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_wood1/coat_affect_color") + ]], + float SR_wood1_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_wood1/coat_affect_roughness") + ]], + float SR_wood1_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_wood1/thin_film_thickness") + ]], + float SR_wood1_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_wood1/thin_film_IOR") + ]], + float SR_wood1_emission = 0.000000 + [[ + materialx::core::origin("SR_wood1/emission") + ]], + color SR_wood1_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_wood1/emission_color") + ]], + color SR_wood1_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_wood1/opacity") + ]], + bool SR_wood1_thin_walled = false + [[ + materialx::core::origin("SR_wood1/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + float2 geomprop_UV0_out1 = materialx::stdlib_1_8::mx_texcoord_vector2(mxp_index:geomprop_UV0_index); + color image_color_out = NG_tiledimage_color3(image_color_file, image_color_default, geomprop_UV0_out1, image_color_uvtiling, image_color_uvoffset, image_color_realworldimagesize, image_color_realworldtilesize, image_color_filtertype, image_color_framerange, image_color_frameoffset, image_color_frameendaction); + float image_roughness_out = NG_tiledimage_float(image_roughness_file, image_roughness_default, geomprop_UV0_out1, image_roughness_uvtiling, image_roughness_uvoffset, image_roughness_realworldimagesize, image_roughness_realworldtilesize, image_roughness_filtertype, image_roughness_framerange, image_roughness_frameoffset, image_roughness_frameendaction); + color image_color_out_cm_out = NG_srgb_texture_to_lin_rec709_color3(image_color_out); + material SR_wood1_out = NG_standard_surface_surfaceshader_100(SR_wood1_base, image_color_out_cm_out, SR_wood1_diffuse_roughness, SR_wood1_metalness, SR_wood1_specular, SR_wood1_specular_color, image_roughness_out, SR_wood1_specular_IOR, SR_wood1_specular_anisotropy, SR_wood1_specular_rotation, SR_wood1_transmission, SR_wood1_transmission_color, SR_wood1_transmission_depth, SR_wood1_transmission_scatter, SR_wood1_transmission_scatter_anisotropy, SR_wood1_transmission_dispersion, SR_wood1_transmission_extra_roughness, SR_wood1_subsurface, SR_wood1_subsurface_color, SR_wood1_subsurface_radius, SR_wood1_subsurface_scale, SR_wood1_subsurface_anisotropy, SR_wood1_sheen, SR_wood1_sheen_color, SR_wood1_sheen_roughness, SR_wood1_coat, SR_wood1_coat_color, SR_wood1_coat_roughness, SR_wood1_coat_anisotropy, SR_wood1_coat_rotation, SR_wood1_coat_IOR, geomprop_Nworld_out1, SR_wood1_coat_affect_color, SR_wood1_coat_affect_roughness, SR_wood1_thin_film_thickness, SR_wood1_thin_film_IOR, SR_wood1_emission, SR_wood1_emission_color, SR_wood1_opacity, SR_wood1_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Tiled_Wood_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_wood1_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Tiled_Wood_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Tiled_Wood.msl.frag b/Materials/Examples/StandardSurface/Tiled_Wood.msl.frag new file mode 100644 index 0000000000..150e1a87de --- /dev/null +++ b/Materials/Examples/StandardSurface/Tiled_Wood.msl.frag @@ -0,0 +1,2764 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + int geomprop_UV0_index; + vec3 image_color_default; + vec2 image_color_uvtiling; + vec2 image_color_uvoffset; + vec2 image_color_realworldimagesize; + vec2 image_color_realworldtilesize; + int image_color_filtertype; + int image_color_framerange; + int image_color_frameoffset; + int image_color_frameendaction; + float image_roughness_default; + vec2 image_roughness_uvtiling; + vec2 image_roughness_uvoffset; + vec2 image_roughness_realworldimagesize; + vec2 image_roughness_realworldtilesize; + int image_roughness_filtertype; + int image_roughness_framerange; + int image_roughness_frameoffset; + int image_roughness_frameendaction; + float SR_wood1_base; + float SR_wood1_diffuse_roughness; + float SR_wood1_metalness; + float SR_wood1_specular; + vec3 SR_wood1_specular_color; + float SR_wood1_specular_IOR; + float SR_wood1_specular_anisotropy; + float SR_wood1_specular_rotation; + float SR_wood1_transmission; + vec3 SR_wood1_transmission_color; + float SR_wood1_transmission_depth; + vec3 SR_wood1_transmission_scatter; + float SR_wood1_transmission_scatter_anisotropy; + float SR_wood1_transmission_dispersion; + float SR_wood1_transmission_extra_roughness; + float SR_wood1_subsurface; + vec3 SR_wood1_subsurface_color; + vec3 SR_wood1_subsurface_radius; + float SR_wood1_subsurface_scale; + float SR_wood1_subsurface_anisotropy; + float SR_wood1_sheen; + vec3 SR_wood1_sheen_color; + float SR_wood1_sheen_roughness; + float SR_wood1_coat; + vec3 SR_wood1_coat_color; + float SR_wood1_coat_roughness; + float SR_wood1_coat_anisotropy; + float SR_wood1_coat_rotation; + float SR_wood1_coat_IOR; + float SR_wood1_coat_affect_color; + float SR_wood1_coat_affect_roughness; + float SR_wood1_thin_film_thickness; + float SR_wood1_thin_film_IOR; + float SR_wood1_emission; + vec3 SR_wood1_emission_color; + vec3 SR_wood1_opacity; + bool SR_wood1_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec2 texcoord_0 ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , int geomprop_UV0_index + +, MetalTexture image_color_file , vec3 image_color_default + + , vec2 image_color_uvtiling + + , vec2 image_color_uvoffset + + , vec2 image_color_realworldimagesize + + , vec2 image_color_realworldtilesize + + , int image_color_filtertype + + , int image_color_framerange + + , int image_color_frameoffset + + , int image_color_frameendaction + +, MetalTexture image_roughness_file , float image_roughness_default + + , vec2 image_roughness_uvtiling + + , vec2 image_roughness_uvoffset + + , vec2 image_roughness_realworldimagesize + + , vec2 image_roughness_realworldtilesize + + , int image_roughness_filtertype + + , int image_roughness_framerange + + , int image_roughness_frameoffset + + , int image_roughness_frameendaction + + , float SR_wood1_base + + , float SR_wood1_diffuse_roughness + + , float SR_wood1_metalness + + , float SR_wood1_specular + + , vec3 SR_wood1_specular_color + + , float SR_wood1_specular_IOR + + , float SR_wood1_specular_anisotropy + + , float SR_wood1_specular_rotation + + , float SR_wood1_transmission + + , vec3 SR_wood1_transmission_color + + , float SR_wood1_transmission_depth + + , vec3 SR_wood1_transmission_scatter + + , float SR_wood1_transmission_scatter_anisotropy + + , float SR_wood1_transmission_dispersion + + , float SR_wood1_transmission_extra_roughness + + , float SR_wood1_subsurface + + , vec3 SR_wood1_subsurface_color + + , vec3 SR_wood1_subsurface_radius + + , float SR_wood1_subsurface_scale + + , float SR_wood1_subsurface_anisotropy + + , float SR_wood1_sheen + + , vec3 SR_wood1_sheen_color + + , float SR_wood1_sheen_roughness + + , float SR_wood1_coat + + , vec3 SR_wood1_coat_color + + , float SR_wood1_coat_roughness + + , float SR_wood1_coat_anisotropy + + , float SR_wood1_coat_rotation + + , float SR_wood1_coat_IOR + + , float SR_wood1_coat_affect_color + + , float SR_wood1_coat_affect_roughness + + , float SR_wood1_thin_film_thickness + + , float SR_wood1_thin_film_IOR + + , float SR_wood1_emission + + , vec3 SR_wood1_emission_color + + , vec3 SR_wood1_opacity + + , bool SR_wood1_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , geomprop_UV0_index(geomprop_UV0_index) + +, image_color_file(image_color_file) + , image_color_default(image_color_default) + + , image_color_uvtiling(image_color_uvtiling) + + , image_color_uvoffset(image_color_uvoffset) + + , image_color_realworldimagesize(image_color_realworldimagesize) + + , image_color_realworldtilesize(image_color_realworldtilesize) + + , image_color_filtertype(image_color_filtertype) + + , image_color_framerange(image_color_framerange) + + , image_color_frameoffset(image_color_frameoffset) + + , image_color_frameendaction(image_color_frameendaction) + +, image_roughness_file(image_roughness_file) + , image_roughness_default(image_roughness_default) + + , image_roughness_uvtiling(image_roughness_uvtiling) + + , image_roughness_uvoffset(image_roughness_uvoffset) + + , image_roughness_realworldimagesize(image_roughness_realworldimagesize) + + , image_roughness_realworldtilesize(image_roughness_realworldtilesize) + + , image_roughness_filtertype(image_roughness_filtertype) + + , image_roughness_framerange(image_roughness_framerange) + + , image_roughness_frameoffset(image_roughness_frameoffset) + + , image_roughness_frameendaction(image_roughness_frameendaction) + + , SR_wood1_base(SR_wood1_base) + + , SR_wood1_diffuse_roughness(SR_wood1_diffuse_roughness) + + , SR_wood1_metalness(SR_wood1_metalness) + + , SR_wood1_specular(SR_wood1_specular) + + , SR_wood1_specular_color(SR_wood1_specular_color) + + , SR_wood1_specular_IOR(SR_wood1_specular_IOR) + + , SR_wood1_specular_anisotropy(SR_wood1_specular_anisotropy) + + , SR_wood1_specular_rotation(SR_wood1_specular_rotation) + + , SR_wood1_transmission(SR_wood1_transmission) + + , SR_wood1_transmission_color(SR_wood1_transmission_color) + + , SR_wood1_transmission_depth(SR_wood1_transmission_depth) + + , SR_wood1_transmission_scatter(SR_wood1_transmission_scatter) + + , SR_wood1_transmission_scatter_anisotropy(SR_wood1_transmission_scatter_anisotropy) + + , SR_wood1_transmission_dispersion(SR_wood1_transmission_dispersion) + + , SR_wood1_transmission_extra_roughness(SR_wood1_transmission_extra_roughness) + + , SR_wood1_subsurface(SR_wood1_subsurface) + + , SR_wood1_subsurface_color(SR_wood1_subsurface_color) + + , SR_wood1_subsurface_radius(SR_wood1_subsurface_radius) + + , SR_wood1_subsurface_scale(SR_wood1_subsurface_scale) + + , SR_wood1_subsurface_anisotropy(SR_wood1_subsurface_anisotropy) + + , SR_wood1_sheen(SR_wood1_sheen) + + , SR_wood1_sheen_color(SR_wood1_sheen_color) + + , SR_wood1_sheen_roughness(SR_wood1_sheen_roughness) + + , SR_wood1_coat(SR_wood1_coat) + + , SR_wood1_coat_color(SR_wood1_coat_color) + + , SR_wood1_coat_roughness(SR_wood1_coat_roughness) + + , SR_wood1_coat_anisotropy(SR_wood1_coat_anisotropy) + + , SR_wood1_coat_rotation(SR_wood1_coat_rotation) + + , SR_wood1_coat_IOR(SR_wood1_coat_IOR) + + , SR_wood1_coat_affect_color(SR_wood1_coat_affect_color) + + , SR_wood1_coat_affect_roughness(SR_wood1_coat_affect_roughness) + + , SR_wood1_thin_film_thickness(SR_wood1_thin_film_thickness) + + , SR_wood1_thin_film_IOR(SR_wood1_thin_film_IOR) + + , SR_wood1_emission(SR_wood1_emission) + + , SR_wood1_emission_color(SR_wood1_emission_color) + + , SR_wood1_opacity(SR_wood1_opacity) + + , SR_wood1_thin_walled(SR_wood1_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + int geomprop_UV0_index; + + +MetalTexture image_color_file; + vec3 image_color_default; + + + vec2 image_color_uvtiling; + + + vec2 image_color_uvoffset; + + + vec2 image_color_realworldimagesize; + + + vec2 image_color_realworldtilesize; + + + int image_color_filtertype; + + + int image_color_framerange; + + + int image_color_frameoffset; + + + int image_color_frameendaction; + + +MetalTexture image_roughness_file; + float image_roughness_default; + + + vec2 image_roughness_uvtiling; + + + vec2 image_roughness_uvoffset; + + + vec2 image_roughness_realworldimagesize; + + + vec2 image_roughness_realworldtilesize; + + + int image_roughness_filtertype; + + + int image_roughness_framerange; + + + int image_roughness_frameoffset; + + + int image_roughness_frameendaction; + + + float SR_wood1_base; + + + float SR_wood1_diffuse_roughness; + + + float SR_wood1_metalness; + + + float SR_wood1_specular; + + + vec3 SR_wood1_specular_color; + + + float SR_wood1_specular_IOR; + + + float SR_wood1_specular_anisotropy; + + + float SR_wood1_specular_rotation; + + + float SR_wood1_transmission; + + + vec3 SR_wood1_transmission_color; + + + float SR_wood1_transmission_depth; + + + vec3 SR_wood1_transmission_scatter; + + + float SR_wood1_transmission_scatter_anisotropy; + + + float SR_wood1_transmission_dispersion; + + + float SR_wood1_transmission_extra_roughness; + + + float SR_wood1_subsurface; + + + vec3 SR_wood1_subsurface_color; + + + vec3 SR_wood1_subsurface_radius; + + + float SR_wood1_subsurface_scale; + + + float SR_wood1_subsurface_anisotropy; + + + float SR_wood1_sheen; + + + vec3 SR_wood1_sheen_color; + + + float SR_wood1_sheen_roughness; + + + float SR_wood1_coat; + + + vec3 SR_wood1_coat_color; + + + float SR_wood1_coat_roughness; + + + float SR_wood1_coat_anisotropy; + + + float SR_wood1_coat_rotation; + + + float SR_wood1_coat_IOR; + + + float SR_wood1_coat_affect_color; + + + float SR_wood1_coat_affect_roughness; + + + float SR_wood1_thin_film_thickness; + + + float SR_wood1_thin_film_IOR; + + + float SR_wood1_emission; + + + vec3 SR_wood1_emission_color; + + + vec3 SR_wood1_opacity; + + + bool SR_wood1_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + vec2 mx_transform_uv(vec2 uv, vec2 uv_scale, vec2 uv_offset) + { + uv = uv * uv_scale + uv_offset; + return uv; + } + + void mx_image_color3(MetalTexture tex_sampler, int layer, vec3 defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread vec3& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).rgb; + } + + void NG_tiledimage_color3(MetalTexture file, vec3 default1, vec2 texcoord1, vec2 uvtiling, vec2 uvoffset, vec2 realworldimagesize, vec2 realworldtilesize, int filtertype, int framerange, int frameoffset, int frameendaction, thread vec3& out1) + { + vec2 N_mult_color3_out = texcoord1 * uvtiling; + vec2 N_sub_color3_out = N_mult_color3_out - uvoffset; + vec2 N_divtilesize_color3_out = N_sub_color3_out / realworldimagesize; + vec2 N_multtilesize_color3_out = N_divtilesize_color3_out * realworldtilesize; + vec3 N_img_color3_out = vec3(0.0); + mx_image_color3(file, 0, default1, N_multtilesize_color3_out, 2, 2, filtertype, framerange, frameoffset, frameendaction, vec2(1.000000, 1.000000), vec2(0.000000, 0.000000), N_img_color3_out); + out1 = N_img_color3_out; + } + + + void mx_image_float(MetalTexture tex_sampler, int layer, float defaultval, vec2 texcoord, int uaddressmode, int vaddressmode, int filtertype, int framerange, int frameoffset, int frameendaction, vec2 uv_scale, vec2 uv_offset, thread float& result) + { + vec2 uv = mx_transform_uv(texcoord, uv_scale, uv_offset); + result = texture(tex_sampler, uv).r; + } + + void NG_tiledimage_float(MetalTexture file, float default1, vec2 texcoord1, vec2 uvtiling, vec2 uvoffset, vec2 realworldimagesize, vec2 realworldtilesize, int filtertype, int framerange, int frameoffset, int frameendaction, thread float& out1) + { + vec2 N_mult_float_out = texcoord1 * uvtiling; + vec2 N_sub_float_out = N_mult_float_out - uvoffset; + vec2 N_divtilesize_float_out = N_sub_float_out / realworldimagesize; + vec2 N_multtilesize_float_out = N_divtilesize_float_out * realworldtilesize; + float N_img_float_out = 0.0; + mx_image_float(file, 0, default1, N_multtilesize_float_out, 2, 2, filtertype, framerange, frameoffset, frameendaction, vec2(1.000000, 1.000000), vec2(0.000000, 0.000000), N_img_float_out); + out1 = N_img_float_out; + } + + void NG_separate3_color3(vec3 in1, thread float& outr, thread float& outg, thread float& outb) + { + const int N_extract_0_index_tmp = 0; + float N_extract_0_out = in1[N_extract_0_index_tmp]; + const int N_extract_1_index_tmp = 1; + float N_extract_1_out = in1[N_extract_1_index_tmp]; + const int N_extract_2_index_tmp = 2; + float N_extract_2_out = in1[N_extract_2_index_tmp]; + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; + } + + void NG_srgb_texture_to_lin_rec709_color3(vec3 in1, thread vec3& out1) + { + const float bias_in2_tmp = 0.055000; + vec3 bias_out = in1 + bias_in2_tmp; + const float linSeg_in2_tmp = 12.920000; + vec3 linSeg_out = in1 / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in1, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + const float max_in2_tmp = 0.000000; + vec3 max_out = max(bias_out, max_in2_tmp); + const float isAboveR_value2_tmp = 0.040450; + const float isAboveR_in1_tmp = 1.000000; + const float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = (colorSeparate_outr > isAboveR_value2_tmp) ? isAboveR_in1_tmp : isAboveR_in2_tmp; + const float isAboveG_value2_tmp = 0.040450; + const float isAboveG_in1_tmp = 1.000000; + const float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = (colorSeparate_outg > isAboveG_value2_tmp) ? isAboveG_in1_tmp : isAboveG_in2_tmp; + const float isAboveB_value2_tmp = 0.040450; + const float isAboveB_in1_tmp = 1.000000; + const float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = (colorSeparate_outb > isAboveB_value2_tmp) ? isAboveB_in1_tmp : isAboveB_in2_tmp; + const float scale_in2_tmp = 1.055000; + vec3 scale_out = max_out / scale_in2_tmp; + vec3 isAbove_out = { isAboveR_out,isAboveG_out,isAboveB_out }; + const float powSeg_in2_tmp = 2.400000; + vec3 powSeg_out = pow(scale_out, vec3(powSeg_in2_tmp)); + vec3 mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out1 = mix_out; + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + vec2 geomprop_UV0_out1 = vd.texcoord_0.xy; + vec3 image_color_out = vec3(0.0); + NG_tiledimage_color3(image_color_file, image_color_default, geomprop_UV0_out1, image_color_uvtiling, image_color_uvoffset, image_color_realworldimagesize, image_color_realworldtilesize, image_color_filtertype, image_color_framerange, image_color_frameoffset, image_color_frameendaction, image_color_out); + float image_roughness_out = 0.0; + NG_tiledimage_float(image_roughness_file, image_roughness_default, geomprop_UV0_out1, image_roughness_uvtiling, image_roughness_uvoffset, image_roughness_realworldimagesize, image_roughness_realworldtilesize, image_roughness_filtertype, image_roughness_framerange, image_roughness_frameoffset, image_roughness_frameendaction, image_roughness_out); + vec3 image_color_out_cm_out = vec3(0.0); + NG_srgb_texture_to_lin_rec709_color3(image_color_out, image_color_out_cm_out); + surfaceshader SR_wood1_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_wood1_base, image_color_out_cm_out, SR_wood1_diffuse_roughness, SR_wood1_metalness, SR_wood1_specular, SR_wood1_specular_color, image_roughness_out, SR_wood1_specular_IOR, SR_wood1_specular_anisotropy, SR_wood1_specular_rotation, SR_wood1_transmission, SR_wood1_transmission_color, SR_wood1_transmission_depth, SR_wood1_transmission_scatter, SR_wood1_transmission_scatter_anisotropy, SR_wood1_transmission_dispersion, SR_wood1_transmission_extra_roughness, SR_wood1_subsurface, SR_wood1_subsurface_color, SR_wood1_subsurface_radius, SR_wood1_subsurface_scale, SR_wood1_subsurface_anisotropy, SR_wood1_sheen, SR_wood1_sheen_color, SR_wood1_sheen_roughness, SR_wood1_coat, SR_wood1_coat_color, SR_wood1_coat_roughness, SR_wood1_coat_anisotropy, SR_wood1_coat_rotation, SR_wood1_coat_IOR, geomprop_Nworld_out1, SR_wood1_coat_affect_color, SR_wood1_coat_affect_roughness, SR_wood1_thin_film_thickness, SR_wood1_thin_film_IOR, SR_wood1_emission, SR_wood1_emission_color, SR_wood1_opacity, SR_wood1_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_wood1_out); + material Tiled_Wood_out = SR_wood1_out; + out1 = float4(Tiled_Wood_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], texture2d image_color_file_tex [[texture(0)]], sampler image_color_file_sampler [[sampler(0)]] +, texture2d image_roughness_file_tex [[texture(1)]], sampler image_roughness_file_sampler [[sampler(1)]] +, constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(2)]], sampler u_envRadiance_sampler [[sampler(2)]] +, texture2d u_envIrradiance_tex [[texture(3)]], sampler u_envIrradiance_sampler [[sampler(3)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.geomprop_UV0_index +, MetalTexture { +image_color_file_tex, image_color_file_sampler } + , u_pub.image_color_default + , u_pub.image_color_uvtiling + , u_pub.image_color_uvoffset + , u_pub.image_color_realworldimagesize + , u_pub.image_color_realworldtilesize + , u_pub.image_color_filtertype + , u_pub.image_color_framerange + , u_pub.image_color_frameoffset + , u_pub.image_color_frameendaction +, MetalTexture { +image_roughness_file_tex, image_roughness_file_sampler } + , u_pub.image_roughness_default + , u_pub.image_roughness_uvtiling + , u_pub.image_roughness_uvoffset + , u_pub.image_roughness_realworldimagesize + , u_pub.image_roughness_realworldtilesize + , u_pub.image_roughness_filtertype + , u_pub.image_roughness_framerange + , u_pub.image_roughness_frameoffset + , u_pub.image_roughness_frameendaction + , u_pub.SR_wood1_base + , u_pub.SR_wood1_diffuse_roughness + , u_pub.SR_wood1_metalness + , u_pub.SR_wood1_specular + , u_pub.SR_wood1_specular_color + , u_pub.SR_wood1_specular_IOR + , u_pub.SR_wood1_specular_anisotropy + , u_pub.SR_wood1_specular_rotation + , u_pub.SR_wood1_transmission + , u_pub.SR_wood1_transmission_color + , u_pub.SR_wood1_transmission_depth + , u_pub.SR_wood1_transmission_scatter + , u_pub.SR_wood1_transmission_scatter_anisotropy + , u_pub.SR_wood1_transmission_dispersion + , u_pub.SR_wood1_transmission_extra_roughness + , u_pub.SR_wood1_subsurface + , u_pub.SR_wood1_subsurface_color + , u_pub.SR_wood1_subsurface_radius + , u_pub.SR_wood1_subsurface_scale + , u_pub.SR_wood1_subsurface_anisotropy + , u_pub.SR_wood1_sheen + , u_pub.SR_wood1_sheen_color + , u_pub.SR_wood1_sheen_roughness + , u_pub.SR_wood1_coat + , u_pub.SR_wood1_coat_color + , u_pub.SR_wood1_coat_roughness + , u_pub.SR_wood1_coat_anisotropy + , u_pub.SR_wood1_coat_rotation + , u_pub.SR_wood1_coat_IOR + , u_pub.SR_wood1_coat_affect_color + , u_pub.SR_wood1_coat_affect_roughness + , u_pub.SR_wood1_thin_film_thickness + , u_pub.SR_wood1_thin_film_IOR + , u_pub.SR_wood1_emission + , u_pub.SR_wood1_emission_color + , u_pub.SR_wood1_opacity + , u_pub.SR_wood1_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Tiled_Wood.msl.vert b/Materials/Examples/StandardSurface/Tiled_Wood.msl.vert new file mode 100644 index 0000000000..07c5afe2f2 --- /dev/null +++ b/Materials/Examples/StandardSurface/Tiled_Wood.msl.vert @@ -0,0 +1,121 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; + vec2 i_texcoord_0 [[attribute(3)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec2 texcoord_0; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent +, vec2 i_texcoord_0 + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) +, i_texcoord_0(i_texcoord_0) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + vec2 i_texcoord_0; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.texcoord_0 = i_texcoord_0; + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'geomprop_UV0'. Function already called in this scope. + // Omitted node 'image_color'. Function already called in this scope. + // Omitted node 'image_roughness'. Function already called in this scope. + // Omitted node 'image_color_out_cm'. Function already called in this scope. + // Omitted node 'SR_wood1'. Function already called in this scope. + // Omitted node 'Tiled_Wood'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(4) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent, i_vs.i_texcoord_0 , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Tiled_Wood.osl b/Materials/Examples/StandardSurface/Tiled_Wood.osl new file mode 100644 index 0000000000..89befcb74f --- /dev/null +++ b/Materials/Examples/StandardSurface/Tiled_Wood.osl @@ -0,0 +1,613 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +vector2 mx_transform_uv(vector2 texcoord) +{ + return texcoord; +} + +void mx_image_color3(textureresource file, string layer, color default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = default_value; + vector2 st = mx_transform_uv(texcoord); + out = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode, "colorspace", file.colorspace); +} + +void NG_tiledimage_color3(textureresource file, color default1, vector2 texcoord, vector2 uvtiling, vector2 uvoffset, vector2 realworldimagesize, vector2 realworldtilesize, string filtertype, string framerange, int frameoffset, string frameendaction, output color out) +{ + vector2 N_mult_color3_out = texcoord * uvtiling; + vector2 N_sub_color3_out = N_mult_color3_out - uvoffset; + vector2 N_divtilesize_color3_out = N_sub_color3_out / realworldimagesize; + vector2 N_multtilesize_color3_out = N_divtilesize_color3_out * realworldtilesize; + color N_img_color3_out = color(0.0); + mx_image_color3(file, "", default1, N_multtilesize_color3_out, "periodic", "periodic", filtertype, framerange, frameoffset, frameendaction, N_img_color3_out); + out = N_img_color3_out; +} + + +void mx_image_float(textureresource file, string layer, float default_value, vector2 texcoord, string uaddressmode, string vaddressmode, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + if (file.filename == "" || + (uaddressmode == "constant" && (texcoord.x<0.0 || texcoord.x>1.0)) || + (vaddressmode == "constant" && (texcoord.y<0.0 || texcoord.y>1.0))) + { + out = default_value; + return; + } + + color missingColor = color(default_value); + vector2 st = mx_transform_uv(texcoord); + color rgb = texture(file.filename, st.x, st.y, "subimage", layer, "missingcolor", missingColor, "swrap", uaddressmode, "twrap", vaddressmode); + out = rgb[0]; +} + +void NG_tiledimage_float(textureresource file, float default1, vector2 texcoord, vector2 uvtiling, vector2 uvoffset, vector2 realworldimagesize, vector2 realworldtilesize, string filtertype, string framerange, int frameoffset, string frameendaction, output float out) +{ + vector2 N_mult_float_out = texcoord * uvtiling; + vector2 N_sub_float_out = N_mult_float_out - uvoffset; + vector2 N_divtilesize_float_out = N_sub_float_out / realworldimagesize; + vector2 N_multtilesize_float_out = N_divtilesize_float_out * realworldtilesize; + float N_img_float_out = 0.0; + mx_image_float(file, "", default1, N_multtilesize_float_out, "periodic", "periodic", filtertype, framerange, frameoffset, frameendaction, N_img_float_out); + out = N_img_float_out; +} + +void NG_separate3_color3(color in, output float outr, output float outg, output float outb) +{ + int N_extract_0_index_tmp = 0; + float N_extract_0_out = mx_extract(in, N_extract_0_index_tmp); + int N_extract_1_index_tmp = 1; + float N_extract_1_out = mx_extract(in, N_extract_1_index_tmp); + int N_extract_2_index_tmp = 2; + float N_extract_2_out = mx_extract(in, N_extract_2_index_tmp); + outr = N_extract_0_out; + outg = N_extract_1_out; + outb = N_extract_2_out; +} + +void NG_srgb_texture_to_lin_rec709_color3(color in, output color out) +{ + float bias_in2_tmp = 0.055000; + color bias_out = in + bias_in2_tmp; + float linSeg_in2_tmp = 12.920000; + color linSeg_out = in / linSeg_in2_tmp; + float colorSeparate_outr = 0.0; + float colorSeparate_outg = 0.0; + float colorSeparate_outb = 0.0; + NG_separate3_color3(in, colorSeparate_outr, colorSeparate_outg, colorSeparate_outb); + float max_in2_tmp = 0.000000; + color max_out = max(bias_out, max_in2_tmp); + float isAboveR_value2_tmp = 0.040450; + float isAboveR_in1_tmp = 1.000000; + float isAboveR_in2_tmp = 0.000000; + float isAboveR_out = mx_ternary(colorSeparate_outr > isAboveR_value2_tmp, isAboveR_in1_tmp, isAboveR_in2_tmp); + float isAboveG_value2_tmp = 0.040450; + float isAboveG_in1_tmp = 1.000000; + float isAboveG_in2_tmp = 0.000000; + float isAboveG_out = mx_ternary(colorSeparate_outg > isAboveG_value2_tmp, isAboveG_in1_tmp, isAboveG_in2_tmp); + float isAboveB_value2_tmp = 0.040450; + float isAboveB_in1_tmp = 1.000000; + float isAboveB_in2_tmp = 0.000000; + float isAboveB_out = mx_ternary(colorSeparate_outb > isAboveB_value2_tmp, isAboveB_in1_tmp, isAboveB_in2_tmp); + float scale_in2_tmp = 1.055000; + color scale_out = max_out / scale_in2_tmp; + color isAbove_out = color( isAboveR_out,isAboveG_out,isAboveB_out ); + float powSeg_in2_tmp = 2.400000; + color powSeg_out = pow(scale_out, powSeg_in2_tmp); + color mix_out = mix(linSeg_out, powSeg_out, isAbove_out); + out = mix_out; +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Tiled_Wood +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Tiled_Wood" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + int geomprop_UV0_index = 0 + [[ + string widget = "number" + ]], + string image_color_file = "../../../Images/wood_color.jpg" + [[ + string widget = "filename" + ]], + string image_color_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + color image_color_default = color(0.000000, 0.000000, 0.000000), + vector2 image_color_uvtiling = {4.000000, 4.000000}, + vector2 image_color_uvoffset = {0.000000, 0.000000}, + vector2 image_color_realworldimagesize = {1.000000, 1.000000}, + vector2 image_color_realworldtilesize = {1.000000, 1.000000}, + string image_color_filtertype = "linear", + string image_color_framerange = "", + int image_color_frameoffset = 0 + [[ + string widget = "number" + ]], + string image_color_frameendaction = "constant", + string image_roughness_file = "../../../Images/wood_roughness.jpg" + [[ + string widget = "filename" + ]], + string image_roughness_file_colorspace = "" + [[ + string widget = "colorspace" + ]], + float image_roughness_default = 0.000000 + [[ + string widget = "number" + ]], + vector2 image_roughness_uvtiling = {4.000000, 4.000000}, + vector2 image_roughness_uvoffset = {0.000000, 0.000000}, + vector2 image_roughness_realworldimagesize = {1.000000, 1.000000}, + vector2 image_roughness_realworldtilesize = {1.000000, 1.000000}, + string image_roughness_filtertype = "linear", + string image_roughness_framerange = "", + int image_roughness_frameoffset = 0 + [[ + string widget = "number" + ]], + string image_roughness_frameendaction = "constant", + float SR_wood1_base = 1.000000 + [[ + string widget = "number" + ]], + float SR_wood1_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_wood1_metalness = 0.000000 + [[ + string widget = "number" + ]], + float SR_wood1_specular = 0.400000 + [[ + string widget = "number" + ]], + color SR_wood1_specular_color = color(1.000000, 1.000000, 1.000000), + float SR_wood1_specular_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_wood1_specular_anisotropy = 0.500000 + [[ + string widget = "number" + ]], + float SR_wood1_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_wood1_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_wood1_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_wood1_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_wood1_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_wood1_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_wood1_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_wood1_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_wood1_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_wood1_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_wood1_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_wood1_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_wood1_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_wood1_sheen = 0.000000 + [[ + string widget = "number" + ]], + color SR_wood1_sheen_color = color(1.000000, 1.000000, 1.000000), + float SR_wood1_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_wood1_coat = 0.100000 + [[ + string widget = "number" + ]], + color SR_wood1_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_wood1_coat_roughness = 0.200000 + [[ + string widget = "number" + ]], + float SR_wood1_coat_anisotropy = 0.500000 + [[ + string widget = "number" + ]], + float SR_wood1_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_wood1_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_wood1_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_wood1_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_wood1_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_wood1_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_wood1_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_wood1_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_wood1_opacity = color(1.000000, 1.000000, 1.000000), + int SR_wood1_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + textureresource image_color_file_ = {image_color_file, image_color_file_colorspace}; + textureresource image_roughness_file_ = {image_roughness_file, image_roughness_file_colorspace}; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + vector2 geomprop_UV0_out1 = vector2(u,v); + color image_color_out = color(0.0); + NG_tiledimage_color3(image_color_file_, image_color_default, geomprop_UV0_out1, image_color_uvtiling, image_color_uvoffset, image_color_realworldimagesize, image_color_realworldtilesize, image_color_filtertype, image_color_framerange, image_color_frameoffset, image_color_frameendaction, image_color_out); + float image_roughness_out = 0.0; + NG_tiledimage_float(image_roughness_file_, image_roughness_default, geomprop_UV0_out1, image_roughness_uvtiling, image_roughness_uvoffset, image_roughness_realworldimagesize, image_roughness_realworldtilesize, image_roughness_filtertype, image_roughness_framerange, image_roughness_frameoffset, image_roughness_frameendaction, image_roughness_out); + color image_color_out_cm_out = color(0.0); + NG_srgb_texture_to_lin_rec709_color3(image_color_out, image_color_out_cm_out); + surfaceshader SR_wood1_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_wood1_base, image_color_out_cm_out, SR_wood1_diffuse_roughness, SR_wood1_metalness, SR_wood1_specular, SR_wood1_specular_color, image_roughness_out, SR_wood1_specular_IOR, SR_wood1_specular_anisotropy, SR_wood1_specular_rotation, SR_wood1_transmission, SR_wood1_transmission_color, SR_wood1_transmission_depth, SR_wood1_transmission_scatter, SR_wood1_transmission_scatter_anisotropy, SR_wood1_transmission_dispersion, SR_wood1_transmission_extra_roughness, SR_wood1_subsurface, SR_wood1_subsurface_color, SR_wood1_subsurface_radius, SR_wood1_subsurface_scale, SR_wood1_subsurface_anisotropy, SR_wood1_sheen, SR_wood1_sheen_color, SR_wood1_sheen_roughness, SR_wood1_coat, SR_wood1_coat_color, SR_wood1_coat_roughness, SR_wood1_coat_anisotropy, SR_wood1_coat_rotation, SR_wood1_coat_IOR, geomprop_Nworld_out1, SR_wood1_coat_affect_color, SR_wood1_coat_affect_roughness, SR_wood1_thin_film_thickness, SR_wood1_thin_film_IOR, SR_wood1_emission, SR_wood1_emission_color, SR_wood1_opacity, SR_wood1_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_wood1_out); + MATERIAL Tiled_Wood_out = mx_surfacematerial(SR_wood1_out, backsurfaceshader, displacementshader1); + out = Tiled_Wood_out; +} + diff --git a/Materials/Examples/StandardSurface/Velvet.glsl.frag b/Materials/Examples/StandardSurface/Velvet.glsl.frag new file mode 100644 index 0000000000..f42131e6c4 --- /dev/null +++ b/Materials/Examples/StandardSurface/Velvet.glsl.frag @@ -0,0 +1,1870 @@ +#version 400 + +struct BSDF { vec3 response; vec3 throughput; }; +#define EDF vec3 +struct surfaceshader { vec3 color; vec3 transparency; }; +struct volumeshader { vec3 color; vec3 transparency; }; +struct displacementshader { vec3 offset; float scale; }; +struct lightshader { vec3 intensity; vec3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +uniform surfaceshader backsurfaceshader; +uniform displacementshader displacementshader1; +uniform float SR_velvet_base = 0.800000; +uniform vec3 SR_velvet_base_color = vec3(0.029000, 0.000000, 0.047000); +uniform float SR_velvet_diffuse_roughness = 0.000000; +uniform float SR_velvet_metalness = 0.000000; +uniform float SR_velvet_specular = 0.000000; +uniform vec3 SR_velvet_specular_color = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_velvet_specular_roughness = 0.693000; +uniform float SR_velvet_specular_IOR = 0.000000; +uniform float SR_velvet_specular_anisotropy = 0.000000; +uniform float SR_velvet_specular_rotation = 0.000000; +uniform float SR_velvet_transmission = 0.000000; +uniform vec3 SR_velvet_transmission_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_velvet_transmission_depth = 0.000000; +uniform vec3 SR_velvet_transmission_scatter = vec3(0.000000, 0.000000, 0.000000); +uniform float SR_velvet_transmission_scatter_anisotropy = 0.000000; +uniform float SR_velvet_transmission_dispersion = 0.000000; +uniform float SR_velvet_transmission_extra_roughness = 0.000000; +uniform float SR_velvet_subsurface = 0.000000; +uniform vec3 SR_velvet_subsurface_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_velvet_subsurface_radius = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_velvet_subsurface_scale = 1.000000; +uniform float SR_velvet_subsurface_anisotropy = 0.000000; +uniform float SR_velvet_sheen = 1.000000; +uniform vec3 SR_velvet_sheen_color = vec3(0.404000, 0.058000, 1.000000); +uniform float SR_velvet_sheen_roughness = 0.300000; +uniform float SR_velvet_coat = 0.000000; +uniform vec3 SR_velvet_coat_color = vec3(1.000000, 1.000000, 1.000000); +uniform float SR_velvet_coat_roughness = 0.100000; +uniform float SR_velvet_coat_anisotropy = 0.000000; +uniform float SR_velvet_coat_rotation = 0.000000; +uniform float SR_velvet_coat_IOR = 1.500000; +uniform float SR_velvet_coat_affect_color = 0.000000; +uniform float SR_velvet_coat_affect_roughness = 0.000000; +uniform float SR_velvet_thin_film_thickness = 0.000000; +uniform float SR_velvet_thin_film_IOR = 1.500000; +uniform float SR_velvet_emission = 0.000000; +uniform vec3 SR_velvet_emission_color = vec3(1.000000, 1.000000, 1.000000); +uniform vec3 SR_velvet_opacity = vec3(1.000000, 1.000000, 1.000000); +uniform bool SR_velvet_thin_walled = false; + +// Uniform block: PrivateUniforms +uniform mat4 u_envMatrix = mat4(-1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); +uniform sampler2D u_envRadiance; +uniform float u_envLightIntensity = 1.000000; +uniform int u_envRadianceMips = 1; +uniform int u_envRadianceSamples = 16; +uniform sampler2D u_envIrradiance; +uniform bool u_refractionTwoSided = false; +uniform vec3 u_viewPosition = vec3(0.0); +uniform int u_numActiveLightSources = 0; + +in VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +// Pixel shader outputs +out vec4 out1; + +#define M_FLOAT_EPS 1e-8 + +#define mx_mod mod +#define mx_inverse inverse +#define mx_inversesqrt inversesqrt +#define mx_sin sin +#define mx_cos cos +#define mx_tan tan +#define mx_asin asin +#define mx_acos acos +#define mx_atan atan +#define mx_radians radians + +float mx_square(float x) +{ + return x*x; +} + +vec2 mx_square(vec2 x) +{ + return x*x; +} + +vec3 mx_square(vec3 x) +{ + return x*x; +} + +vec3 mx_srgb_encode(vec3 color) +{ + bvec3 isAbove = greaterThan(color, vec3(0.0031308)); + vec3 linSeg = color * 12.92; + vec3 powSeg = 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055; + return mix(linSeg, powSeg, isAbove); +} + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +#define M_PI 3.1415926535897932 +#define M_PI_INV (1.0 / M_PI) + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +float mx_pow6(float x) +{ + float x2 = mx_square(x); + return mx_square(x2) * x2; +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} +vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); +} + +// Enforce that the given normal is forward-facing from the specified view direction. +vec3 mx_forward_facing_normal(vec3 N, vec3 V) +{ + return (dot(N, V) < 0.0) ? -N : N; +} + +// https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf +float mx_golden_ratio_sequence(int i) +{ + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); +} + +// https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf +vec2 mx_spherical_fibonacci(int i, int numSamples) +{ + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); +} + +// Generate a uniform-weighted sample on the unit hemisphere. +vec3 mx_uniform_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Generate a cosine-weighted sample on the unit hemisphere. +vec3 mx_cosine_sample_hemisphere(vec2 Xi) +{ + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); +} + +// Construct an orthonormal basis from a unit vector. +// https://graphics.pixar.com/library/OrthonormalB/paper.pdf +mat3 mx_orthonormal_basis(vec3 N) +{ + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); +} + +const int FRESNEL_MODEL_DIELECTRIC = 0; +const int FRESNEL_MODEL_CONDUCTOR = 1; +const int FRESNEL_MODEL_SCHLICK = 2; + +// Parameters for Fresnel calculations +struct FresnelData +{ + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; +}; + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Appendix B.2 Equation 13 +float mx_ggx_NDF(vec3 H, vec2 alpha) +{ + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); +} + +// https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html +vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) +{ + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; +} + +// https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf +// Equation 34 +float mx_ggx_smith_G1(float cosTheta, float alpha) +{ + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); +} + +// Height-correlated Smith masking-shadowing +// http://jcgt.org/published/0003/02/03/paper.pdf +// Equations 72 and 99 +float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) +{ + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); +} + +// Rational quadratic fit to Monte Carlo data for GGX directional albedo. +vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } +#endif + return vec3(0.0); +} + +// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf +vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; +} + +vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); +#else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); +#endif +} + +float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) +{ + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; +} + +// https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf +// Equations 14 and 16 +vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) +{ + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; +} + +float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) +{ + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; +} + +// Compute the average of an anisotropic alpha pair. +float mx_average_alpha(vec2 alpha) +{ + return sqrt(alpha.x * alpha.y); +} + +// Convert a real-valued index of refraction to normal-incidence reflectivity. +float mx_ior_to_f0(float ior) +{ + return mx_square((ior - 1.0) / (ior + 1.0)); +} + +// Convert normal-incidence reflectivity to real-valued index of refraction. +float mx_f0_to_ior(float F0) +{ + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); +} +vec3 mx_f0_to_ior(vec3 F0) +{ + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); +} + +// https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf +vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) +{ + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +float mx_fresnel_dielectric(float cosTheta, float ior) +{ + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); +} + +// https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ +void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, out vec3 Rp, out vec3 Rs) +{ + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); +} + +vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) +{ + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, out vec3 phiP, out vec3 phiS) +{ + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); +} + +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_eval_sensitivity(float opd, vec3 shift) +{ + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; +} + +// A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence +// https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html +vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) +{ + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; +} + +FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) +{ + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; +} + +vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) +{ + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } +} + +// Compute the refraction of a ray through a solid sphere. +vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) +{ + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); +} + +vec2 mx_latlong_projection(vec3 dir) +{ + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); +} + +vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, sampler2D envSampler) +{ + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; +} + +// Return the mip level with the appropriate coverage for a filtered importance sample. +// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html +// Section 20.4 Equation 13 +float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) +{ + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); +} + +vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) +{ + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; +} + +vec3 mx_environment_irradiance(vec3 N) +{ + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; +} + + +vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) +{ + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; +} + +struct LightData +{ + int type; +}; + +uniform LightData u_lightData[MAX_LIGHT_SOURCES]; + +int numActiveLightSources() +{ + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; +} + +void sampleLightSource(LightData light, vec3 position, out lightshader result) +{ + result.intensity = vec3(0.0); + result.direction = vec3(0.0); +} + +void mx_roughness_anisotropy(float roughness, float anisotropy, out vec2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + + +// https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf +// Equation 2 +float mx_imageworks_sheen_NDF(float NdotH, float roughness) +{ + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); +} + +float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) +{ + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); +} + +// Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. +float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; +} + +float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); +} + +float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); +#elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); +#else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// The following functions are adapted from https://github.com/tizian/ltc-sheen. +// "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + +// Gaussian fit to directional albedo table. +float mx_zeltner_sheen_dir_albedo(float x, float y) +{ + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; +} + +// Rational fits to LTC matrix coefficients. +float mx_zeltner_sheen_ltc_aInv(float x, float y) +{ + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); +} + +float mx_zeltner_sheen_ltc_bInv(float x, float y) +{ + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); +} + +// V and N are assumed to be unit vectors. +mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) +{ + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); +} + +// Multiplication by directional albedo is handled by the calling function. +float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) +{ + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); +} + +vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, out float pdf) +{ + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; +} + +void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled out by the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } +} + +void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; +} + +void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, out vec3 result) +{ + result = vec3(dot(_in, lumacoeffs)); +} + +mat4 mx_rotationMatrix(vec3 axis, float angle) +{ + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, out vec3 result) +{ + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; +} + +void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, out vec3 ior, out vec3 extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_uniform_edf(vec3 N, vec3 L, vec3 color, out EDF result) +{ + result = color; +} + + +void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); +} + +void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } +} + +void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, inout BSDF bsdf) +{ + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; +} + + +void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); +} + +void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; +} + +// We fake diffuse transmission by using diffuse reflection from the opposite side. +// So this BTDF is really a BRDF. +void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; +} + +void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; +} + + +const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); +const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + +// Qualitative Oren-Nayar diffuse with simplified math: +// https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf +float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; +} + +// Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. +float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) +{ + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; +} + +float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } +#endif + return 0.0; +} + +float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) +{ + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; +} + +float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) +{ +#if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); +#else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); +#endif + return clamp(dirAlbedo, 0.0, 1.0); +} + +// Improved Oren-Nayar diffuse from Fujii: +// https://mimosa-pudica.net/improved-oren-nayar.html +float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); +} + +float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) +{ + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); +} + +// Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: +// https://academysoftwarefoundation.github.io/OpenPBR/ +vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) +{ + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; +} + +vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) +{ + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); +} + +// https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf +// Section 5.3 +float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) +{ + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; +} + +// Compute the directional albedo component of Burley diffuse for the given +// view angle and roughness. Curve fit provided by Stephen Hill. +float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) +{ + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); +} + +// Evaluate the Burley diffusion profile for the given distance and diffusion shape. +// Based on https://graphics.pixar.com/library/ApproxBSSRDF/ +vec3 mx_burley_diffusion_profile(float dist, vec3 shape) +{ + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; +} + +// Integrate the Burley diffusion profile over a sphere of the given radius. +// Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ +vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) +{ + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; +} + +vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) +{ + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); +} + +void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; +} + +void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; +} + + +void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; +} + +void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, inout BSDF bsdf) +{ + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; +} + +void NG_convert_float_color3(float in1, out vec3 out1) +{ + vec3 combine_out = vec3(in1,in1,in1); + out1 = combine_out; +} + + +void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, out EDF result) +{ + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, out surfaceshader out1) +{ + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader(vec3(0.0),vec3(0.0)); + { + vec3 N = normalize(vd.normalWorld); + vec3 V = normalize(u_viewPosition - vd.positionWorld); + vec3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + vec3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF specular_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF translucent_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF selected_subsurface_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF(vec3(0.0),vec3(1.0)); + BSDF subsurface_mix_out = BSDF(vec3(0.0),vec3(1.0)); + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF(vec3(0.0),vec3(1.0)); + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF(vec3(0.0),vec3(1.0)); + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF(vec3(0.0),vec3(1.0)); + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF(vec3(0.0),vec3(1.0)); + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF(vec3(0.0),vec3(1.0)); + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF(vec3(0.0),vec3(1.0)); + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(vec3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; +} + +void main() +{ + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_velvet_out = surfaceshader(vec3(0.0),vec3(0.0)); + NG_standard_surface_surfaceshader_100(SR_velvet_base, SR_velvet_base_color, SR_velvet_diffuse_roughness, SR_velvet_metalness, SR_velvet_specular, SR_velvet_specular_color, SR_velvet_specular_roughness, SR_velvet_specular_IOR, SR_velvet_specular_anisotropy, SR_velvet_specular_rotation, SR_velvet_transmission, SR_velvet_transmission_color, SR_velvet_transmission_depth, SR_velvet_transmission_scatter, SR_velvet_transmission_scatter_anisotropy, SR_velvet_transmission_dispersion, SR_velvet_transmission_extra_roughness, SR_velvet_subsurface, SR_velvet_subsurface_color, SR_velvet_subsurface_radius, SR_velvet_subsurface_scale, SR_velvet_subsurface_anisotropy, SR_velvet_sheen, SR_velvet_sheen_color, SR_velvet_sheen_roughness, SR_velvet_coat, SR_velvet_coat_color, SR_velvet_coat_roughness, SR_velvet_coat_anisotropy, SR_velvet_coat_rotation, SR_velvet_coat_IOR, geomprop_Nworld_out1, SR_velvet_coat_affect_color, SR_velvet_coat_affect_roughness, SR_velvet_thin_film_thickness, SR_velvet_thin_film_IOR, SR_velvet_emission, SR_velvet_emission_color, SR_velvet_opacity, SR_velvet_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_velvet_out); + material Velvet_out = SR_velvet_out; + out1 = vec4(Velvet_out.color, 1.0); +} + diff --git a/Materials/Examples/StandardSurface/Velvet.glsl.vert b/Materials/Examples/StandardSurface/Velvet.glsl.vert new file mode 100644 index 0000000000..6133cb8f5e --- /dev/null +++ b/Materials/Examples/StandardSurface/Velvet.glsl.vert @@ -0,0 +1,28 @@ +#version 400 + +// Uniform block: PrivateUniforms +uniform mat4 u_worldMatrix = mat4(1.0); +uniform mat4 u_viewProjectionMatrix = mat4(1.0); +uniform mat4 u_worldInverseTransposeMatrix = mat4(1.0); + +// Inputs block: VertexInputs +in vec3 i_position; +in vec3 i_normal; +in vec3 i_tangent; + +out VertexData +{ + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +} vd; + +void main() +{ + vec4 hPositionWorld = u_worldMatrix * vec4(i_position, 1.0); + gl_Position = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; +} + diff --git a/Materials/Examples/StandardSurface/Velvet.mdl b/Materials/Examples/StandardSurface/Velvet.mdl new file mode 100644 index 0000000000..df53e841e6 --- /dev/null +++ b/Materials/Examples/StandardSurface/Velvet.mdl @@ -0,0 +1,317 @@ +mdl 1.8; + +import ::df::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::anno::*; +import ::tex::*; +using ::materialx::core import *; +using ::materialx::sampling import *; +using ::materialx::stdlib_1_8 import *; +using ::materialx::pbrlib_1_8 import *; + +color NG_convert_float_color3 +( + float in1 = 0.000000 +) +{ + color combine_out = color( in1,in1,in1 ); + return combine_out; +} + +material NG_standard_surface_surfaceshader_100 +( + float base = 0.800000, + color base_color = color(1.000000, 1.000000, 1.000000), + float diffuse_roughness = 0.000000, + float metalness = 0.000000, + float specular = 1.000000, + color specular_color = color(1.000000, 1.000000, 1.000000), + float specular_roughness = 0.200000, + uniform float specular_IOR = 1.500000, + float specular_anisotropy = 0.000000, + float specular_rotation = 0.000000, + float transmission = 0.000000, + color transmission_color = color(1.000000, 1.000000, 1.000000), + float transmission_depth = 0.000000, + color transmission_scatter = color(0.000000, 0.000000, 0.000000), + float transmission_scatter_anisotropy = 0.000000, + float transmission_dispersion = 0.000000, + float transmission_extra_roughness = 0.000000, + float subsurface = 0.000000, + color subsurface_color = color(1.000000, 1.000000, 1.000000), + color subsurface_radius = color(1.000000, 1.000000, 1.000000), + float subsurface_scale = 1.000000, + float subsurface_anisotropy = 0.000000, + float sheen = 0.000000, + color sheen_color = color(1.000000, 1.000000, 1.000000), + float sheen_roughness = 0.300000, + float coat = 0.000000, + color coat_color = color(1.000000, 1.000000, 1.000000), + float coat_roughness = 0.100000, + float coat_anisotropy = 0.000000, + float coat_rotation = 0.000000, + uniform float coat_IOR = 1.500000, + float3 coat_normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float coat_affect_color = 0.000000, + float coat_affect_roughness = 0.000000, + float thin_film_thickness = 0.000000, + float thin_film_IOR = 1.500000, + float emission = 0.000000, + color emission_color = color(1.000000, 1.000000, 1.000000), + color opacity = color(1.000000, 1.000000, 1.000000), + bool thin_walled = false, + float3 normal = state::transform_normal(state::coordinate_internal, state::coordinate_world, state::normal()), + float3 tangent = state::transform_vector(state::coordinate_internal, state::coordinate_world, state::texture_tangent_u(0)) +) + = let +{ + float2 coat_roughness_vector_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_roughness, mxp_anisotropy:coat_anisotropy); + float coat_tangent_rotate_degree_out = coat_rotation * 360.000000; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_out = specular_rotation * 360.000000; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + color subsurface_color_nonnegative_out = math::max(subsurface_color, 0.000000); + float coat_clamped_out = math::clamp(coat, 0.000000, 1.000000); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + color base_color_nonnegative_out = math::max(base_color, 0.000000); + color coat_attenuation_out = math::lerp(color(1.000000, 1.000000, 1.000000), coat_color, coat); + float one_minus_coat_ior_out = 1.000000 - coat_IOR; + float one_plus_coat_ior_out = 1.000000 + coat_IOR; + color emission_weight_out = emission_color * emission; + color opacity_luminance_out = materialx::stdlib_1_8::mx_luminance_color3(opacity); + float3 coat_tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:coat_tangent_rotate_degree_out, mxp_axis:coat_normal); + materialx::pbrlib_1_8::mx_artistic_ior__result artistic_ior_result = materialx::pbrlib_1_8::mx_artistic_ior(mxp_reflectivity:metal_reflectivity_out, mxp_edge_color:metal_edgecolor_out); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + float3 tangent_rotate_out = materialx::stdlib_1_8::mx_rotate3d_vector3(mxp_in:tangent, mxp_amount:tangent_rotate_degree_out, mxp_axis:normal); + float transmission_roughness_clamped_out = math::clamp(transmission_roughness_add_out, 0.000000, 1.000000); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + float opacity_luminance_float_out = materialx::stdlib_1_8::mx_extract_color3(opacity_luminance_out, 0); + float3 coat_tangent_rotate_normalize_out = math::normalize(coat_tangent_rotate_out); + float coat_affected_roughness_out = math::lerp(specular_roughness, 1.000000, coat_affect_roughness_multiply2_out); + float3 tangent_rotate_normalize_out = math::normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_out = math::lerp(transmission_roughness_clamped_out, 1.000000, coat_affect_roughness_multiply2_out); + float coat_gamma_out = coat_gamma_multiply_out + 1.000000; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float3 coat_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(coat_anisotropy, 0.000000, coat_tangent_rotate_normalize_out, tangent); + float2 main_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_roughness_out, mxp_anisotropy:specular_anisotropy); + float3 main_tangent_out = materialx::stdlib_1_8::mx_ifgreater_vector3(specular_anisotropy, 0.000000, tangent_rotate_normalize_out, tangent); + float2 transmission_roughness_out = materialx::pbrlib_1_8::mx_roughness_anisotropy(mxp_roughness:coat_affected_transmission_roughness_out, mxp_anisotropy:specular_anisotropy); + color coat_affected_subsurface_color_out = math::pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = math::pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_out = 1.000000 - coat_ior_to_F0_out; + color emission_color0_out = NG_convert_float_color3(one_minus_coat_ior_to_F0_out); + material metal_bsdf_out = materialx::pbrlib_1_8::mx_conductor_bsdf(mxp_weight:1.000000, mxp_ior:artistic_ior_result.mxp_ior, mxp_extinction:artistic_ior_result.mxp_extinction, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx); + material transmission_bsdf_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:1.000000, mxp_tint:transmission_color, mxp_ior:specular_IOR, mxp_roughness:transmission_roughness_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_T, mxp_base:material()); + material translucent_bsdf_out = materialx::pbrlib_1_8::mx_translucent_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_normal:normal); + material subsurface_bsdf_out = materialx::pbrlib_1_8::mx_subsurface_bsdf(mxp_weight:1.000000, mxp_color:coat_affected_subsurface_color_out, mxp_radius:subsurface_radius_scaled_out, mxp_anisotropy:subsurface_anisotropy, mxp_normal:normal); + material selected_subsurface_bsdf_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:translucent_bsdf_out, mxp_bg:subsurface_bsdf_out, mxp_mix:subsurface_selector_out); + material diffuse_bsdf_out = materialx::pbrlib_1_8::mx_oren_nayar_diffuse_bsdf(mxp_weight:base, mxp_color:coat_affected_diffuse_color_out, mxp_roughness:diffuse_roughness, mxp_normal:normal); + material subsurface_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:selected_subsurface_bsdf_out, mxp_bg:diffuse_bsdf_out, mxp_mix:subsurface); + material sheen_layer_out = materialx::pbrlib_1_8::mx_sheen_bsdf(mxp_weight:sheen, mxp_color:sheen_color, mxp_roughness:sheen_roughness, mxp_normal:normal, mxp_base:subsurface_mix_out); + material transmission_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:transmission_bsdf_out, mxp_bg:sheen_layer_out, mxp_mix:transmission); + material specular_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:specular, mxp_tint:specular_color, mxp_ior:specular_IOR, mxp_roughness:main_roughness_out, mxp_thinfilm_thickness:thin_film_thickness, mxp_thinfilm_ior:thin_film_IOR, mxp_normal:normal, mxp_tangent:main_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:transmission_mix_out); + material metalness_mix_out = materialx::pbrlib_1_8::mx_mix_bsdf(mxp_fg:metal_bsdf_out, mxp_bg:specular_layer_out, mxp_mix:metalness); + material thin_film_layer_attenuated_out = materialx::pbrlib_1_8::mx_multiply_bsdf_color3(mxp_in1:metalness_mix_out, mxp_in2:coat_attenuation_out); + material coat_layer_out = materialx::pbrlib_1_8::mx_dielectric_bsdf(mxp_weight:coat, mxp_tint:color(1.000000, 1.000000, 1.000000), mxp_ior:coat_IOR, mxp_roughness:coat_roughness_vector_out, mxp_thinfilm_thickness:0.000000, mxp_thinfilm_ior:1.500000, mxp_normal:coat_normal, mxp_tangent:coat_tangent_out, mxp_distribution:mx_distribution_type_ggx, mxp_scatter_mode:mx_scatter_mode_R, mxp_base:thin_film_layer_attenuated_out); + material emission_edf_out = materialx::pbrlib_1_8::mx_uniform_edf(mxp_color:emission_weight_out); + material coat_tinted_emission_edf_out = materialx::pbrlib_1_8::mx_multiply_edf_color3(mxp_in1:emission_edf_out, mxp_in2:coat_color); + material coat_emission_edf_out = materialx::pbrlib_1_8::mx_generalized_schlick_edf(mxp_color0:emission_color0_out, mxp_color90:color(0.000000, 0.000000, 0.000000), mxp_exponent:5.000000, mxp_base:coat_tinted_emission_edf_out); + material blended_coat_emission_edf_out = materialx::pbrlib_1_8::mx_mix_edf(mxp_fg:coat_emission_edf_out, mxp_bg:emission_edf_out, mxp_mix:coat); + material shader_constructor_out = materialx::pbrlib_1_8::mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, false, specular_IOR); +} +in material(shader_constructor_out); + +export material Velvet +( + material backsurfaceshader = material() + [[ + materialx::core::origin("") + ]], + material displacementshader = material() + [[ + materialx::core::origin("") + ]], + uniform mx_coordinatespace_type geomprop_Nworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Nworld") + ]], + uniform mx_coordinatespace_type geomprop_Tworld_space = mx_coordinatespace_type_world + [[ + materialx::core::origin("Tworld") + ]], + uniform int geomprop_Tworld_index = 0 + [[ + materialx::core::origin("Tworld") + ]], + float SR_velvet_base = 0.800000 + [[ + materialx::core::origin("SR_velvet/base") + ]], + color SR_velvet_base_color = color(0.029000, 0.000000, 0.047000) + [[ + materialx::core::origin("SR_velvet/base_color") + ]], + float SR_velvet_diffuse_roughness = 0.000000 + [[ + materialx::core::origin("SR_velvet/diffuse_roughness") + ]], + float SR_velvet_metalness = 0.000000 + [[ + materialx::core::origin("SR_velvet/metalness") + ]], + float SR_velvet_specular = 0.000000 + [[ + materialx::core::origin("SR_velvet/specular") + ]], + color SR_velvet_specular_color = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_velvet/specular_color") + ]], + float SR_velvet_specular_roughness = 0.693000 + [[ + materialx::core::origin("SR_velvet/specular_roughness") + ]], + uniform float SR_velvet_specular_IOR = 0.000000 + [[ + materialx::core::origin("SR_velvet/specular_IOR") + ]], + float SR_velvet_specular_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_velvet/specular_anisotropy") + ]], + float SR_velvet_specular_rotation = 0.000000 + [[ + materialx::core::origin("SR_velvet/specular_rotation") + ]], + float SR_velvet_transmission = 0.000000 + [[ + materialx::core::origin("SR_velvet/transmission") + ]], + color SR_velvet_transmission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_velvet/transmission_color") + ]], + float SR_velvet_transmission_depth = 0.000000 + [[ + materialx::core::origin("SR_velvet/transmission_depth") + ]], + color SR_velvet_transmission_scatter = color(0.000000, 0.000000, 0.000000) + [[ + materialx::core::origin("SR_velvet/transmission_scatter") + ]], + float SR_velvet_transmission_scatter_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_velvet/transmission_scatter_anisotropy") + ]], + float SR_velvet_transmission_dispersion = 0.000000 + [[ + materialx::core::origin("SR_velvet/transmission_dispersion") + ]], + float SR_velvet_transmission_extra_roughness = 0.000000 + [[ + materialx::core::origin("SR_velvet/transmission_extra_roughness") + ]], + float SR_velvet_subsurface = 0.000000 + [[ + materialx::core::origin("SR_velvet/subsurface") + ]], + color SR_velvet_subsurface_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_velvet/subsurface_color") + ]], + color SR_velvet_subsurface_radius = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_velvet/subsurface_radius") + ]], + float SR_velvet_subsurface_scale = 1.000000 + [[ + materialx::core::origin("SR_velvet/subsurface_scale") + ]], + float SR_velvet_subsurface_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_velvet/subsurface_anisotropy") + ]], + float SR_velvet_sheen = 1.000000 + [[ + materialx::core::origin("SR_velvet/sheen") + ]], + color SR_velvet_sheen_color = color(0.404000, 0.058000, 1.000000) + [[ + materialx::core::origin("SR_velvet/sheen_color") + ]], + float SR_velvet_sheen_roughness = 0.300000 + [[ + materialx::core::origin("SR_velvet/sheen_roughness") + ]], + float SR_velvet_coat = 0.000000 + [[ + materialx::core::origin("SR_velvet/coat") + ]], + color SR_velvet_coat_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_velvet/coat_color") + ]], + float SR_velvet_coat_roughness = 0.100000 + [[ + materialx::core::origin("SR_velvet/coat_roughness") + ]], + float SR_velvet_coat_anisotropy = 0.000000 + [[ + materialx::core::origin("SR_velvet/coat_anisotropy") + ]], + float SR_velvet_coat_rotation = 0.000000 + [[ + materialx::core::origin("SR_velvet/coat_rotation") + ]], + uniform float SR_velvet_coat_IOR = 1.500000 + [[ + materialx::core::origin("SR_velvet/coat_IOR") + ]], + float SR_velvet_coat_affect_color = 0.000000 + [[ + materialx::core::origin("SR_velvet/coat_affect_color") + ]], + float SR_velvet_coat_affect_roughness = 0.000000 + [[ + materialx::core::origin("SR_velvet/coat_affect_roughness") + ]], + float SR_velvet_thin_film_thickness = 0.000000 + [[ + materialx::core::origin("SR_velvet/thin_film_thickness") + ]], + float SR_velvet_thin_film_IOR = 1.500000 + [[ + materialx::core::origin("SR_velvet/thin_film_IOR") + ]], + float SR_velvet_emission = 0.000000 + [[ + materialx::core::origin("SR_velvet/emission") + ]], + color SR_velvet_emission_color = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_velvet/emission_color") + ]], + color SR_velvet_opacity = color(1.000000, 1.000000, 1.000000) + [[ + materialx::core::origin("SR_velvet/opacity") + ]], + bool SR_velvet_thin_walled = false + [[ + materialx::core::origin("SR_velvet/thin_walled") + ]] +) += let +{ + float3 geomprop_Nworld_out1 = materialx::stdlib_1_8::mx_normal_vector3(mxp_space:geomprop_Nworld_space); + float3 geomprop_Tworld_out1 = materialx::stdlib_1_8::mx_tangent_vector3(mxp_space:geomprop_Tworld_space, mxp_index:geomprop_Tworld_index); + material SR_velvet_out = NG_standard_surface_surfaceshader_100(SR_velvet_base, SR_velvet_base_color, SR_velvet_diffuse_roughness, SR_velvet_metalness, SR_velvet_specular, SR_velvet_specular_color, SR_velvet_specular_roughness, SR_velvet_specular_IOR, SR_velvet_specular_anisotropy, SR_velvet_specular_rotation, SR_velvet_transmission, SR_velvet_transmission_color, SR_velvet_transmission_depth, SR_velvet_transmission_scatter, SR_velvet_transmission_scatter_anisotropy, SR_velvet_transmission_dispersion, SR_velvet_transmission_extra_roughness, SR_velvet_subsurface, SR_velvet_subsurface_color, SR_velvet_subsurface_radius, SR_velvet_subsurface_scale, SR_velvet_subsurface_anisotropy, SR_velvet_sheen, SR_velvet_sheen_color, SR_velvet_sheen_roughness, SR_velvet_coat, SR_velvet_coat_color, SR_velvet_coat_roughness, SR_velvet_coat_anisotropy, SR_velvet_coat_rotation, SR_velvet_coat_IOR, geomprop_Nworld_out1, SR_velvet_coat_affect_color, SR_velvet_coat_affect_roughness, SR_velvet_thin_film_thickness, SR_velvet_thin_film_IOR, SR_velvet_emission, SR_velvet_emission_color, SR_velvet_opacity, SR_velvet_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1); + material Velvet_out = materialx::stdlib_1_8::mx_surfacematerial(mxp_surfaceshader: SR_velvet_out, mxp_backsurfaceshader: backsurfaceshader, mxp_displacementshader: displacementshader); + material finalOutput__ = Velvet_out; +} +in material(finalOutput__); diff --git a/Materials/Examples/StandardSurface/Velvet.msl.frag b/Materials/Examples/StandardSurface/Velvet.msl.frag new file mode 100644 index 0000000000..efb16d4274 --- /dev/null +++ b/Materials/Examples/StandardSurface/Velvet.msl.frag @@ -0,0 +1,2506 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +struct MetalTexture +{ + texture2d tex; + sampler s; + int get_width() { return tex.get_width(); } + int get_height() { return tex.get_height(); } + int get_num_mip_levels() { return tex.get_num_mip_levels(); } +}; + +int get_width(MetalTexture mtlTex) { return mtlTex.get_width(); } + +float4 texture(MetalTexture mtlTex, float2 uv) +{ + return mtlTex.tex.sample(mtlTex.s, uv); +} + +float4 textureLod(MetalTexture mtlTex, float2 uv, float lod) +{ + return mtlTex.tex.sample(mtlTex.s, uv, level(lod)); +} + +int2 textureSize(MetalTexture mtlTex, int mipLevel) +{ + return int2(mtlTex.get_width(), mtlTex.get_height()); +} + +int texture_mips(MetalTexture mtlTex) +{ + return mtlTex.tex.get_num_mip_levels(); +} +struct BSDF { float3 response; float3 throughput; }; +#define EDF float3 +struct surfaceshader { float3 color; float3 transparency; }; +struct volumeshader { float3 color; float3 transparency; }; +struct displacementshader { float3 offset; float scale; }; +struct lightshader { float3 intensity; float3 direction; }; +#define material surfaceshader + +// Uniform block: PublicUniforms +struct PublicUniforms +{ + surfaceshader backsurfaceshader; + displacementshader displacementshader1; + float SR_velvet_base; + vec3 SR_velvet_base_color; + float SR_velvet_diffuse_roughness; + float SR_velvet_metalness; + float SR_velvet_specular; + vec3 SR_velvet_specular_color; + float SR_velvet_specular_roughness; + float SR_velvet_specular_IOR; + float SR_velvet_specular_anisotropy; + float SR_velvet_specular_rotation; + float SR_velvet_transmission; + vec3 SR_velvet_transmission_color; + float SR_velvet_transmission_depth; + vec3 SR_velvet_transmission_scatter; + float SR_velvet_transmission_scatter_anisotropy; + float SR_velvet_transmission_dispersion; + float SR_velvet_transmission_extra_roughness; + float SR_velvet_subsurface; + vec3 SR_velvet_subsurface_color; + vec3 SR_velvet_subsurface_radius; + float SR_velvet_subsurface_scale; + float SR_velvet_subsurface_anisotropy; + float SR_velvet_sheen; + vec3 SR_velvet_sheen_color; + float SR_velvet_sheen_roughness; + float SR_velvet_coat; + vec3 SR_velvet_coat_color; + float SR_velvet_coat_roughness; + float SR_velvet_coat_anisotropy; + float SR_velvet_coat_rotation; + float SR_velvet_coat_IOR; + float SR_velvet_coat_affect_color; + float SR_velvet_coat_affect_roughness; + float SR_velvet_thin_film_thickness; + float SR_velvet_thin_film_IOR; + float SR_velvet_emission; + vec3 SR_velvet_emission_color; + vec3 SR_velvet_opacity; + bool SR_velvet_thin_walled; +}; + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_envMatrix; + float u_envLightIntensity; + int u_envRadianceMips; + int u_envRadianceSamples; + bool u_refractionTwoSided; + vec3 u_viewPosition; + int u_numActiveLightSources; +}; + +// Inputs block: VertexData +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld ; + vec3 tangentWorld ; + vec3 positionWorld ; +}; +// Pixel shader outputs +struct PixelOutputs +{ + vec4 out1; +}; + +#define DIRECTIONAL_ALBEDO_METHOD 0 + +#define MAX_LIGHT_SOURCES 3 +struct LightData +{ + int type; + float pad0; + float pad1; + float pad2; +}; + +struct LightData_pixel +{ + LightData u_lightData[MAX_LIGHT_SOURCES]; +}; + +float3x3 operator+(float3x3 a, float b) +{ + return a + float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator+(float4x4 a, float b) +{ + return a + float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator-(float3x3 a, float b) +{ + return a - float3x3(b,b,b,b,b,b,b,b,b); +} + +float4x4 operator-(float4x4 a, float b) +{ + return a - float4x4(b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b); +} + +float3x3 operator/(float3x3 a, float3x3 b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float4x4 operator/(float4x4 a, float4x4 b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b[i][j]; + + return a; +} + +float3x3 operator/(float3x3 a, float b) +{ + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + a[i][j] /= b; + + return a; +} + +float4x4 operator/(float4x4 a, float b) +{ + for(int i = 0; i < 4; ++i) + for(int j = 0; j < 4; ++j) + a[i][j] /= b; + + return a; +} +struct GlobalContext +{ + GlobalContext( + VertexData vd +, constant LightData u_lightData[MAX_LIGHT_SOURCES] + , surfaceshader backsurfaceshader + + , displacementshader displacementshader1 + + , float SR_velvet_base + + , vec3 SR_velvet_base_color + + , float SR_velvet_diffuse_roughness + + , float SR_velvet_metalness + + , float SR_velvet_specular + + , vec3 SR_velvet_specular_color + + , float SR_velvet_specular_roughness + + , float SR_velvet_specular_IOR + + , float SR_velvet_specular_anisotropy + + , float SR_velvet_specular_rotation + + , float SR_velvet_transmission + + , vec3 SR_velvet_transmission_color + + , float SR_velvet_transmission_depth + + , vec3 SR_velvet_transmission_scatter + + , float SR_velvet_transmission_scatter_anisotropy + + , float SR_velvet_transmission_dispersion + + , float SR_velvet_transmission_extra_roughness + + , float SR_velvet_subsurface + + , vec3 SR_velvet_subsurface_color + + , vec3 SR_velvet_subsurface_radius + + , float SR_velvet_subsurface_scale + + , float SR_velvet_subsurface_anisotropy + + , float SR_velvet_sheen + + , vec3 SR_velvet_sheen_color + + , float SR_velvet_sheen_roughness + + , float SR_velvet_coat + + , vec3 SR_velvet_coat_color + + , float SR_velvet_coat_roughness + + , float SR_velvet_coat_anisotropy + + , float SR_velvet_coat_rotation + + , float SR_velvet_coat_IOR + + , float SR_velvet_coat_affect_color + + , float SR_velvet_coat_affect_roughness + + , float SR_velvet_thin_film_thickness + + , float SR_velvet_thin_film_IOR + + , float SR_velvet_emission + + , vec3 SR_velvet_emission_color + + , vec3 SR_velvet_opacity + + , bool SR_velvet_thin_walled + + , mat4 u_envMatrix + +, MetalTexture u_envRadiance , float u_envLightIntensity + + , int u_envRadianceMips + + , int u_envRadianceSamples + +, MetalTexture u_envIrradiance , bool u_refractionTwoSided + + , vec3 u_viewPosition + + , int u_numActiveLightSources + + ) : +gl_FragCoord( vd.pos) +, vd(vd) +, u_lightData + { + u_lightData[0] +, u_lightData[1] +, u_lightData[2] + } + , backsurfaceshader(backsurfaceshader) + + , displacementshader1(displacementshader1) + + , SR_velvet_base(SR_velvet_base) + + , SR_velvet_base_color(SR_velvet_base_color) + + , SR_velvet_diffuse_roughness(SR_velvet_diffuse_roughness) + + , SR_velvet_metalness(SR_velvet_metalness) + + , SR_velvet_specular(SR_velvet_specular) + + , SR_velvet_specular_color(SR_velvet_specular_color) + + , SR_velvet_specular_roughness(SR_velvet_specular_roughness) + + , SR_velvet_specular_IOR(SR_velvet_specular_IOR) + + , SR_velvet_specular_anisotropy(SR_velvet_specular_anisotropy) + + , SR_velvet_specular_rotation(SR_velvet_specular_rotation) + + , SR_velvet_transmission(SR_velvet_transmission) + + , SR_velvet_transmission_color(SR_velvet_transmission_color) + + , SR_velvet_transmission_depth(SR_velvet_transmission_depth) + + , SR_velvet_transmission_scatter(SR_velvet_transmission_scatter) + + , SR_velvet_transmission_scatter_anisotropy(SR_velvet_transmission_scatter_anisotropy) + + , SR_velvet_transmission_dispersion(SR_velvet_transmission_dispersion) + + , SR_velvet_transmission_extra_roughness(SR_velvet_transmission_extra_roughness) + + , SR_velvet_subsurface(SR_velvet_subsurface) + + , SR_velvet_subsurface_color(SR_velvet_subsurface_color) + + , SR_velvet_subsurface_radius(SR_velvet_subsurface_radius) + + , SR_velvet_subsurface_scale(SR_velvet_subsurface_scale) + + , SR_velvet_subsurface_anisotropy(SR_velvet_subsurface_anisotropy) + + , SR_velvet_sheen(SR_velvet_sheen) + + , SR_velvet_sheen_color(SR_velvet_sheen_color) + + , SR_velvet_sheen_roughness(SR_velvet_sheen_roughness) + + , SR_velvet_coat(SR_velvet_coat) + + , SR_velvet_coat_color(SR_velvet_coat_color) + + , SR_velvet_coat_roughness(SR_velvet_coat_roughness) + + , SR_velvet_coat_anisotropy(SR_velvet_coat_anisotropy) + + , SR_velvet_coat_rotation(SR_velvet_coat_rotation) + + , SR_velvet_coat_IOR(SR_velvet_coat_IOR) + + , SR_velvet_coat_affect_color(SR_velvet_coat_affect_color) + + , SR_velvet_coat_affect_roughness(SR_velvet_coat_affect_roughness) + + , SR_velvet_thin_film_thickness(SR_velvet_thin_film_thickness) + + , SR_velvet_thin_film_IOR(SR_velvet_thin_film_IOR) + + , SR_velvet_emission(SR_velvet_emission) + + , SR_velvet_emission_color(SR_velvet_emission_color) + + , SR_velvet_opacity(SR_velvet_opacity) + + , SR_velvet_thin_walled(SR_velvet_thin_walled) + + , u_envMatrix(u_envMatrix) + +, u_envRadiance(u_envRadiance) + , u_envLightIntensity(u_envLightIntensity) + + , u_envRadianceMips(u_envRadianceMips) + + , u_envRadianceSamples(u_envRadianceSamples) + +, u_envIrradiance(u_envIrradiance) + , u_refractionTwoSided(u_refractionTwoSided) + + , u_viewPosition(u_viewPosition) + + , u_numActiveLightSources(u_numActiveLightSources) + + {} + #define M_FLOAT_EPS 1e-8 + + #define mx_sin sin + #define mx_cos cos + #define mx_tan tan + #define mx_asin asin + #define mx_acos acos + + float mx_square(float x) + { + return x*x; + } + + vec2 mx_square(vec2 x) + { + return x*x; + } + + vec3 mx_square(vec3 x) + { + return x*x; + } + + float mx_inversesqrt(float x) + { + return ::rsqrt(x); + } + + template + T1 mx_mod(T1 x, T2 y) + { + return x - y * floor(x/y); + } + + float3x3 mx_inverse(float3x3 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2]; + + float det = determinant(m); + float idet = 1.0f / det; + + float3x3 ret; + + ret[0][0] = idet * (n22 * n33 - n32 * n23); + ret[1][0] = idet * (n32 * n13 - n12 * n33); + ret[2][0] = idet * (n12 * n23 - n22 * n13); + + ret[0][1] = idet * (n31 * n23 - n21 * n33); + ret[1][1] = idet * (n11 * n33 - n31 * n13); + ret[2][1] = idet * (n21 * n13 - n11 * n23); + + ret[0][2] = idet * (n21 * n32 - n31 * n22); + ret[1][2] = idet * (n31 * n12 - n11 * n32); + ret[2][2] = idet * (n11 * n22 - n21 * n12); + + return ret; + } + + float4x4 mx_inverse(float4x4 m) + { + float n11 = m[0][0], n12 = m[1][0], n13 = m[2][0], n14 = m[3][0]; + float n21 = m[0][1], n22 = m[1][1], n23 = m[2][1], n24 = m[3][1]; + float n31 = m[0][2], n32 = m[1][2], n33 = m[2][2], n34 = m[3][2]; + float n41 = m[0][3], n42 = m[1][3], n43 = m[2][3], n44 = m[3][3]; + + float t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + float t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + float t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + float t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + float det = determinant(m); + float idet = 1.0f / det; + + float4x4 ret; + + ret[0][0] = t11 * idet; + ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; + ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; + ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; + + ret[1][0] = t12 * idet; + ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; + ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; + ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; + + ret[2][0] = t13 * idet; + ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; + ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; + ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; + + ret[3][0] = t14 * idet; + ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; + ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; + ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; + + return ret; + } + + float mx_atan(float y_over_x) + { + return ::atan(y_over_x); + } + + float mx_atan(float y, float x) + { + return ::atan2(y, x); + } + + vec2 mx_atan(vec2 y, vec2 x) + { + return ::atan2(y, x); + } + + vec3 mx_atan(vec3 y, vec3 x) + { + return ::atan2(y, x); + } + + vec4 mx_atan(vec4 y, vec4 x) + { + return ::atan2(y, x); + } + + float mx_radians(float degree) + { + return (degree * M_PI_F / 180.0f); + } + + #define M_PI 3.1415926535897932 + #define M_PI_INV (1.0 / M_PI) + + float mx_pow5(float x) + { + return mx_square(mx_square(x)) * x; + } + + float mx_pow6(float x) + { + float x2 = mx_square(x); + return mx_square(x2) * x2; + } + + // Standard Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; + } + + // Generalized Schlick Fresnel + float mx_fresnel_schlick(float cosTheta, float F0, float F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); + } + + // Generalized Schlick Fresnel with a variable exponent + float mx_fresnel_schlick(float cosTheta, float F0, float F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + vec3 mx_fresnel_schlick(float cosTheta, vec3 F0, vec3 F90, float exponent) + { + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(F0, F90, pow(x, exponent)); + } + + // Enforce that the given normal is forward-facing from the specified view direction. + vec3 mx_forward_facing_normal(vec3 N, vec3 V) + { + return (dot(N, V) < 0.0) ? -N : N; + } + + // https://www.graphics.rwth-aachen.de/publication/2/jgt.pdf + float mx_golden_ratio_sequence(int i) + { + const float GOLDEN_RATIO = 1.6180339887498948; + return fract((float(i) + 1.0) * GOLDEN_RATIO); + } + + // https://people.irisa.fr/Ricardo.Marques/articles/2013/SF_CGF.pdf + vec2 mx_spherical_fibonacci(int i, int numSamples) + { + return vec2((float(i) + 0.5) / float(numSamples), mx_golden_ratio_sequence(i)); + } + + // Generate a uniform-weighted sample on the unit hemisphere. + vec3 mx_uniform_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = 1.0 - Xi.y; + float sinTheta = sqrt(1.0 - mx_square(cosTheta)); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Generate a cosine-weighted sample on the unit hemisphere. + vec3 mx_cosine_sample_hemisphere(vec2 Xi) + { + float phi = 2.0 * M_PI * Xi.x; + float cosTheta = sqrt(Xi.y); + float sinTheta = sqrt(1.0 - Xi.y); + return vec3(mx_cos(phi) * sinTheta, + mx_sin(phi) * sinTheta, + cosTheta); + } + + // Construct an orthonormal basis from a unit vector. + // https://graphics.pixar.com/library/OrthonormalB/paper.pdf + mat3 mx_orthonormal_basis(vec3 N) + { + float sign = (N.z < 0.0) ? -1.0 : 1.0; + float a = -1.0 / (sign + N.z); + float b = N.x * N.y * a; + vec3 X = vec3(1.0 + sign * N.x * N.x * a, sign * b, -sign * N.x); + vec3 Y = vec3(b, sign + N.y * N.y * a, -N.y); + return mat3(X, Y, N); + } + + const int FRESNEL_MODEL_DIELECTRIC = 0; + const int FRESNEL_MODEL_CONDUCTOR = 1; + const int FRESNEL_MODEL_SCHLICK = 2; + + // Parameters for Fresnel calculations + struct FresnelData + { + // Fresnel model + int model; + bool airy; + + // Physical Fresnel + vec3 ior; + vec3 extinction; + + // Generalized Schlick Fresnel + vec3 F0; + vec3 F82; + vec3 F90; + float exponent; + + // Thin film + float tf_thickness; + float tf_ior; + + // Refraction + bool refraction; + }; + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Appendix B.2 Equation 13 + float mx_ggx_NDF(vec3 H, vec2 alpha) + { + vec2 He = H.xy / alpha; + float denom = dot(He, He) + mx_square(H.z); + return 1.0 / (M_PI * alpha.x * alpha.y * mx_square(denom)); + } + + // https://ggx-research.github.io/publication/2023/06/09/publication-ggx.html + vec3 mx_ggx_importance_sample_VNDF(vec2 Xi, vec3 V, vec2 alpha) + { + // Transform the view direction to the hemisphere configuration. + V = normalize(vec3(V.xy * alpha, V.z)); + + // Sample a spherical cap in (-V.z, 1]. + float phi = 2.0 * M_PI * Xi.x; + float z = (1.0 - Xi.y) * (1.0 + V.z) - V.z; + float sinTheta = sqrt(clamp(1.0 - z * z, 0.0, 1.0)); + float x = sinTheta * mx_cos(phi); + float y = sinTheta * mx_sin(phi); + vec3 c = vec3(x, y, z); + + // Compute the microfacet normal. + vec3 H = c + V; + + // Transform the microfacet normal back to the ellipsoid configuration. + H = normalize(vec3(H.xy * alpha, max(H.z, 0.0))); + + return H; + } + + // https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf + // Equation 34 + float mx_ggx_smith_G1(float cosTheta, float alpha) + { + float cosTheta2 = mx_square(cosTheta); + float tanTheta2 = (1.0 - cosTheta2) / cosTheta2; + return 2.0 / (1.0 + sqrt(1.0 + mx_square(alpha) * tanTheta2)); + } + + // Height-correlated Smith masking-shadowing + // http://jcgt.org/published/0003/02/03/paper.pdf + // Equations 72 and 99 + float mx_ggx_smith_G2(float NdotL, float NdotV, float alpha) + { + float alpha2 = mx_square(alpha); + float lambdaL = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotL)); + float lambdaV = sqrt(alpha2 + (1.0 - alpha2) * mx_square(NdotV)); + return 2.0 / (lambdaL / NdotL + lambdaV / NdotV); + } + + // Rational quadratic fit to Monte Carlo data for GGX directional albedo. + vec3 mx_ggx_dir_albedo_analytic(float NdotV, float alpha, vec3 F0, vec3 F90) + { + float x = NdotV; + float y = alpha; + float x2 = mx_square(x); + float y2 = mx_square(y); + vec4 r = vec4(0.1003, 0.9345, 1.0, 1.0) + + vec4(-0.6303, -2.323, -1.765, 0.2281) * x + + vec4(9.748, 2.229, 8.263, 15.94) * y + + vec4(-2.038, -3.748, 11.53, -55.83) * x * y + + vec4(29.34, 1.424, 28.96, 13.08) * x2 + + vec4(-8.245, -0.7684, -7.507, 41.26) * y2 + + vec4(-26.44, 1.436, -36.11, 54.9) * x2 * y + + vec4(19.99, 0.2913, 15.86, 300.2) * x * y2 + + vec4(-5.448, 0.6286, 33.37, -285.1) * x2 * y2; + vec2 AB = clamp(r.xy / r.zw, 0.0, 1.0); + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo_table_lookup(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + vec2 AB = texture(u_albedoTable, vec2(NdotV, alpha)).rg; + return F0 * AB.x + F90 * AB.y; + } + #endif + return vec3(0.0); + } + + // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + vec3 mx_ggx_dir_albedo_monte_carlo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + vec2 AB = vec2(0.0); + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, vec2(alpha)); + vec3 L = -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Compute the Fresnel term. + float Fc = mx_fresnel_schlick(VdotH, 0.0, 1.0); + + // Compute the per-sample geometric term. + // https://hal.inria.fr/hal-00996995v2/document, Algorithm 2 + float G2 = mx_ggx_smith_G2(NdotL, NdotV, alpha); + + // Add the contribution of this sample. + AB += vec2(G2 * (1.0 - Fc), G2 * Fc); + } + + // Apply the global component of the geometric term and normalize. + AB /= mx_ggx_smith_G1(NdotV, alpha) * float(SAMPLE_COUNT); + + // Return the final directional albedo. + return F0 * AB.x + F90 * AB.y; + } + + vec3 mx_ggx_dir_albedo(float NdotV, float alpha, vec3 F0, vec3 F90) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + return mx_ggx_dir_albedo_analytic(NdotV, alpha, F0, F90); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + return mx_ggx_dir_albedo_table_lookup(NdotV, alpha, F0, F90); + #else + return mx_ggx_dir_albedo_monte_carlo(NdotV, alpha, F0, F90); + #endif + } + + float mx_ggx_dir_albedo(float NdotV, float alpha, float F0, float F90) + { + return mx_ggx_dir_albedo(NdotV, alpha, vec3(F0), vec3(F90)).x; + } + + // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf + // Equations 14 and 16 + vec3 mx_ggx_energy_compensation(float NdotV, float alpha, vec3 Fss) + { + float Ess = mx_ggx_dir_albedo(NdotV, alpha, 1.0, 1.0); + return 1.0 + Fss * (1.0 - Ess) / Ess; + } + + float mx_ggx_energy_compensation(float NdotV, float alpha, float Fss) + { + return mx_ggx_energy_compensation(NdotV, alpha, vec3(Fss)).x; + } + + // Compute the average of an anisotropic alpha pair. + float mx_average_alpha(vec2 alpha) + { + return sqrt(alpha.x * alpha.y); + } + + // Convert a real-valued index of refraction to normal-incidence reflectivity. + float mx_ior_to_f0(float ior) + { + return mx_square((ior - 1.0) / (ior + 1.0)); + } + + // Convert normal-incidence reflectivity to real-valued index of refraction. + float mx_f0_to_ior(float F0) + { + float sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (1.0 + sqrtF0) / (1.0 - sqrtF0); + } + vec3 mx_f0_to_ior(vec3 F0) + { + vec3 sqrtF0 = sqrt(clamp(F0, 0.01, 0.99)); + return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); + } + + // https://renderwonk.com/publications/wp-generalization-adobe/gen-adobe.pdf + vec3 mx_fresnel_hoffman_schlick(float cosTheta, FresnelData fd) + { + const float COS_THETA_MAX = 1.0 / 7.0; + const float COS_THETA_FACTOR = 1.0 / (COS_THETA_MAX * pow(1.0 - COS_THETA_MAX, 6.0)); + + float x = clamp(cosTheta, 0.0, 1.0); + vec3 a = mix(fd.F0, fd.F90, pow(1.0 - COS_THETA_MAX, fd.exponent)) * (vec3(1.0) - fd.F82) * COS_THETA_FACTOR; + return mix(fd.F0, fd.F90, pow(1.0 - x, fd.exponent)) - a * x * mx_pow6(1.0 - x); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + float mx_fresnel_dielectric(float cosTheta, float ior) + { + float c = cosTheta; + float g2 = ior*ior + c*c - 1.0; + if (g2 < 0.0) + { + // Total internal reflection + return 1.0; + } + + float g = sqrt(g2); + return 0.5 * mx_square((g - c) / (g + c)) * + (1.0 + mx_square(((g + c) * c - 1.0) / ((g - c) * c + 1.0))); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + vec2 mx_fresnel_dielectric_polarized(float cosTheta, float ior) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + + float t0 = max(ior * ior - sinTheta2, 0.0); + float t1 = t0 + cosTheta2; + float t2 = 2.0 * sqrt(t0) * cosTheta; + float Rs = (t1 - t2) / (t1 + t2); + + float t3 = cosTheta2 * t0 + sinTheta2 * sinTheta2; + float t4 = t2 * sinTheta2; + float Rp = Rs * (t3 - t4) / (t3 + t4); + + return vec2(Rp, Rs); + } + + // https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/ + void mx_fresnel_conductor_polarized(float cosTheta, vec3 n, vec3 k, thread vec3& Rp, thread vec3& Rs) + { + float cosTheta2 = mx_square(clamp(cosTheta, 0.0, 1.0)); + float sinTheta2 = 1.0 - cosTheta2; + vec3 n2 = n * n; + vec3 k2 = k * k; + + vec3 t0 = n2 - k2 - vec3(sinTheta2); + vec3 a2plusb2 = sqrt(t0 * t0 + 4.0 * n2 * k2); + vec3 t1 = a2plusb2 + vec3(cosTheta2); + vec3 a = sqrt(max(0.5 * (a2plusb2 + t0), 0.0)); + vec3 t2 = 2.0 * a * cosTheta; + Rs = (t1 - t2) / (t1 + t2); + + vec3 t3 = cosTheta2 * a2plusb2 + vec3(sinTheta2 * sinTheta2); + vec3 t4 = t2 * sinTheta2; + Rp = Rs * (t3 - t4) / (t3 + t4); + } + + vec3 mx_fresnel_conductor(float cosTheta, vec3 n, vec3 k) + { + vec3 Rp, Rs; + mx_fresnel_conductor_polarized(cosTheta, n, k, Rp, Rs); + return 0.5 * (Rp + Rs); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + void mx_fresnel_conductor_phase_polarized(float cosTheta, float eta1, vec3 eta2, vec3 kappa2, thread vec3& phiP, thread vec3& phiS) + { + vec3 k2 = kappa2 / eta2; + vec3 sinThetaSqr = vec3(1.0) - cosTheta * cosTheta; + vec3 A = eta2*eta2*(vec3(1.0)-k2*k2) - eta1*eta1*sinThetaSqr; + vec3 B = sqrt(A*A + mx_square(2.0*eta2*eta2*k2)); + vec3 U = sqrt((A+B)/2.0); + vec3 V = max(vec3(0.0), sqrt((B-A)/2.0)); + + phiS = mx_atan(2.0*eta1*V*cosTheta, U*U + V*V - mx_square(eta1*cosTheta)); + phiP = mx_atan(2.0*eta1*eta2*eta2*cosTheta * (2.0*k2*U - (vec3(1.0)-k2*k2) * V), + mx_square(eta2*eta2*(vec3(1.0)+k2*k2)*cosTheta) - eta1*eta1*(U*U+V*V)); + } + + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_eval_sensitivity(float opd, vec3 shift) + { + // Use Gaussian fits, given by 3 parameters: val, pos and var + float phase = 2.0*M_PI * opd; + vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); + vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); + vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); + vec3 xyz = val * sqrt(2.0*M_PI * var) * mx_cos(pos * phase + shift) * exp(- var * phase*phase); + xyz.x += 9.7470e-14 * sqrt(2.0*M_PI * 4.5282e+09) * mx_cos(2.2399e+06 * phase + shift[0]) * exp(- 4.5282e+09 * phase*phase); + return xyz / 1.0685e-7; + } + + // A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence + // https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html + vec3 mx_fresnel_airy(float cosTheta, FresnelData fd) + { + // XYZ to CIE 1931 RGB color space (using neutral E illuminant) + const mat3 XYZ_TO_RGB = mat3(2.3706743, -0.5138850, 0.0052982, -0.9000405, 1.4253036, -0.0146949, -0.4706338, 0.0885814, 1.0093968); + + // Assume vacuum on the outside + float eta1 = 1.0; + float eta2 = max(fd.tf_ior, eta1); + vec3 eta3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? mx_f0_to_ior(fd.F0) : fd.ior; + vec3 kappa3 = (fd.model == FRESNEL_MODEL_SCHLICK) ? vec3(0.0) : fd.extinction; + float cosThetaT = sqrt(1.0 - (1.0 - mx_square(cosTheta)) * mx_square(eta1 / eta2)); + + // First interface + vec2 R12 = mx_fresnel_dielectric_polarized(cosTheta, eta2 / eta1); + if (cosThetaT <= 0.0) + { + // Total internal reflection + R12 = vec2(1.0); + } + vec2 T121 = vec2(1.0) - R12; + + // Second interface + vec3 R23p, R23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + vec3 f = mx_fresnel_hoffman_schlick(cosThetaT, fd); + R23p = 0.5 * f; + R23s = 0.5 * f; + } + else + { + mx_fresnel_conductor_polarized(cosThetaT, eta3 / eta2, kappa3 / eta2, R23p, R23s); + } + + // Phase shift + float cosB = mx_cos(mx_atan(eta2 / eta1)); + vec2 phi21 = vec2(cosTheta < cosB ? 0.0 : M_PI, M_PI); + vec3 phi23p, phi23s; + if (fd.model == FRESNEL_MODEL_SCHLICK) + { + phi23p = vec3((eta3[0] < eta2) ? M_PI : 0.0, + (eta3[1] < eta2) ? M_PI : 0.0, + (eta3[2] < eta2) ? M_PI : 0.0); + phi23s = phi23p; + } + else + { + mx_fresnel_conductor_phase_polarized(cosThetaT, eta2, eta3, kappa3, phi23p, phi23s); + } + vec3 r123p = max(sqrt(R12.x*R23p), 0.0); + vec3 r123s = max(sqrt(R12.y*R23s), 0.0); + + // Iridescence term + vec3 I = vec3(0.0); + vec3 Cm, Sm; + + // Optical path difference + float distMeters = fd.tf_thickness * 1.0e-9; + float opd = 2.0 * eta2 * cosThetaT * distMeters; + + // Iridescence term using spectral antialiasing for Parallel polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rs = (mx_square(T121.x) * R23p) / (vec3(1.0) - R12.x*R23p); + I += R12.x + Rs; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rs - T121.x; + for (int m=1; m<=2; m++) + { + Cm *= r123p; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23p+vec3(phi21.x))); + I += Cm*Sm; + } + + // Iridescence term using spectral antialiasing for Perpendicular polarization + + // Reflectance term for m=0 (DC term amplitude) + vec3 Rp = (mx_square(T121.y) * R23s) / (vec3(1.0) - R12.y*R23s); + I += R12.y + Rp; + + // Reflectance term for m>0 (pairs of diracs) + Cm = Rp - T121.y; + for (int m=1; m<=2; m++) + { + Cm *= r123s; + Sm = 2.0 * mx_eval_sensitivity(float(m) * opd, float(m)*(phi23s+vec3(phi21.y))); + I += Cm*Sm; + } + + // Average parallel and perpendicular polarization + I *= 0.5; + + // Convert back to RGB reflectance + I = clamp(XYZ_TO_RGB * I, 0.0, 1.0); + + return I; + } + + FresnelData mx_init_fresnel_dielectric(float ior, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_DIELECTRIC; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(ior); + fd.extinction = vec3(0.0); + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_conductor(vec3 ior, vec3 extinction, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_CONDUCTOR; + fd.airy = tf_thickness > 0.0; + fd.ior = ior; + fd.extinction = extinction; + fd.F0 = vec3(0.0); + fd.F82 = vec3(0.0); + fd.F90 = vec3(0.0); + fd.exponent = 0.0; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + FresnelData mx_init_fresnel_schlick(vec3 F0, vec3 F82, vec3 F90, float exponent, float tf_thickness, float tf_ior) + { + FresnelData fd; + fd.model = FRESNEL_MODEL_SCHLICK; + fd.airy = tf_thickness > 0.0; + fd.ior = vec3(0.0); + fd.extinction = vec3(0.0); + fd.F0 = F0; + fd.F82 = F82; + fd.F90 = F90; + fd.exponent = exponent; + fd.tf_thickness = tf_thickness; + fd.tf_ior = tf_ior; + fd.refraction = false; + return fd; + } + + vec3 mx_compute_fresnel(float cosTheta, FresnelData fd) + { + if (fd.airy) + { + return mx_fresnel_airy(cosTheta, fd); + } + else if (fd.model == FRESNEL_MODEL_DIELECTRIC) + { + return vec3(mx_fresnel_dielectric(cosTheta, fd.ior.x)); + } + else if (fd.model == FRESNEL_MODEL_CONDUCTOR) + { + return mx_fresnel_conductor(cosTheta, fd.ior, fd.extinction); + } + else + { + return mx_fresnel_hoffman_schlick(cosTheta, fd); + } + } + + // Compute the refraction of a ray through a solid sphere. + vec3 mx_refraction_solid_sphere(vec3 R, vec3 N, float ior) + { + R = refract(R, N, 1.0 / ior); + vec3 N1 = normalize(R * dot(R, N) - N * 0.5); + return refract(R, N1, ior); + } + + vec2 mx_latlong_projection(vec3 dir) + { + float latitude = -mx_asin(dir.y) * M_PI_INV + 0.5; + float longitude = mx_atan(dir.x, -dir.z) * M_PI_INV * 0.5 + 0.5; + return vec2(longitude, latitude); + } + + vec3 mx_latlong_map_lookup(vec3 dir, mat4 transform, float lod, MetalTexture envSampler) + { + vec3 envDir = normalize((transform * vec4(dir,0.0)).xyz); + vec2 uv = mx_latlong_projection(envDir); + return textureLod(envSampler, uv, lod).rgb; + } + + // Return the mip level with the appropriate coverage for a filtered importance sample. + // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch20.html + // Section 20.4 Equation 13 + float mx_latlong_compute_lod(vec3 dir, float pdf, float maxMipLevel, int envSamples) + { + const float MIP_LEVEL_OFFSET = 1.5; + float effectiveMaxMipLevel = maxMipLevel - MIP_LEVEL_OFFSET; + float distortion = sqrt(1.0 - mx_square(dir.y)); + return max(effectiveMaxMipLevel - 0.5 * log2(float(envSamples) * pdf * distortion), 0.0); + } + + vec3 mx_environment_radiance(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd) + { + // Generate tangent frame. + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + mat3 tangentToWorld = mat3(X, Y, N); + + // Transform the view vector to tangent space. + V = vec3(dot(V, X), dot(V, Y), dot(V, N)); + + // Compute derived properties. + float NdotV = clamp(V.z, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(alpha); + float G1V = mx_ggx_smith_G1(NdotV, avgAlpha); + + // Integrate outgoing radiance using filtered importance sampling. + // http://cgg.mff.cuni.cz/~jaroslav/papers/2008-egsr-fis/2008-egsr-fis-final-embedded.pdf + vec3 radiance = vec3(0.0); + int envRadianceSamples = u_envRadianceSamples; + for (int i = 0; i < envRadianceSamples; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, envRadianceSamples); + + // Compute the half vector and incoming light direction. + vec3 H = mx_ggx_importance_sample_VNDF(Xi, V, alpha); + vec3 L = fd.refraction ? mx_refraction_solid_sphere(-V, H, fd.ior.x) : -reflect(V, H); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + // Sample the environment light from the given direction. + vec3 Lw = tangentToWorld * L; + float pdf = mx_ggx_NDF(H, alpha) * G1V / (4.0 * NdotV); + float lod = mx_latlong_compute_lod(Lw, pdf, float(u_envRadianceMips - 1), envRadianceSamples); + vec3 sampleColor = mx_latlong_map_lookup(Lw, u_envMatrix, lod, u_envRadiance); + + // Compute the Fresnel term. + vec3 F = mx_compute_fresnel(VdotH, fd); + + // Compute the geometric term. + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + // Compute the combined FG term, which simplifies to inverted Fresnel for refraction. + vec3 FG = fd.refraction ? vec3(1.0) - F : F * G; + + // Add the radiance contribution of this sample. + // From https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf + // incidentLight = sampleColor * NdotL + // microfacetSpecular = D * F * G / (4 * NdotL * NdotV) + // pdf = D * G1V / (4 * NdotV); + // radiance = incidentLight * microfacetSpecular / pdf + radiance += sampleColor * FG; + } + + // Apply the global component of the geometric term and normalize. + radiance /= G1V * float(envRadianceSamples); + + // Return the final radiance. + return radiance * u_envLightIntensity; + } + + vec3 mx_environment_irradiance(vec3 N) + { + vec3 Li = mx_latlong_map_lookup(N, u_envMatrix, 0.0, u_envIrradiance); + return Li * u_envLightIntensity; + } + + + vec3 mx_surface_transmission(vec3 N, vec3 V, vec3 X, vec2 alpha, int distribution, FresnelData fd, vec3 tint) + { + // Approximate the appearance of surface transmission as glossy + // environment map refraction, ignoring any scene geometry that might + // be visible through the surface. + fd.refraction = true; + if (u_refractionTwoSided) + { + tint = mx_square(tint); + } + return mx_environment_radiance(N, V, X, alpha, distribution, fd) * tint; + } + + vec4 gl_FragCoord; + VertexData vd; + + LightData u_lightData[MAX_LIGHT_SOURCES]; + + surfaceshader backsurfaceshader; + + + displacementshader displacementshader1; + + + float SR_velvet_base; + + + vec3 SR_velvet_base_color; + + + float SR_velvet_diffuse_roughness; + + + float SR_velvet_metalness; + + + float SR_velvet_specular; + + + vec3 SR_velvet_specular_color; + + + float SR_velvet_specular_roughness; + + + float SR_velvet_specular_IOR; + + + float SR_velvet_specular_anisotropy; + + + float SR_velvet_specular_rotation; + + + float SR_velvet_transmission; + + + vec3 SR_velvet_transmission_color; + + + float SR_velvet_transmission_depth; + + + vec3 SR_velvet_transmission_scatter; + + + float SR_velvet_transmission_scatter_anisotropy; + + + float SR_velvet_transmission_dispersion; + + + float SR_velvet_transmission_extra_roughness; + + + float SR_velvet_subsurface; + + + vec3 SR_velvet_subsurface_color; + + + vec3 SR_velvet_subsurface_radius; + + + float SR_velvet_subsurface_scale; + + + float SR_velvet_subsurface_anisotropy; + + + float SR_velvet_sheen; + + + vec3 SR_velvet_sheen_color; + + + float SR_velvet_sheen_roughness; + + + float SR_velvet_coat; + + + vec3 SR_velvet_coat_color; + + + float SR_velvet_coat_roughness; + + + float SR_velvet_coat_anisotropy; + + + float SR_velvet_coat_rotation; + + + float SR_velvet_coat_IOR; + + + float SR_velvet_coat_affect_color; + + + float SR_velvet_coat_affect_roughness; + + + float SR_velvet_thin_film_thickness; + + + float SR_velvet_thin_film_IOR; + + + float SR_velvet_emission; + + + vec3 SR_velvet_emission_color; + + + vec3 SR_velvet_opacity; + + + bool SR_velvet_thin_walled; + + + mat4 u_envMatrix; + + +MetalTexture u_envRadiance; + float u_envLightIntensity; + + + int u_envRadianceMips; + + + int u_envRadianceSamples; + + +MetalTexture u_envIrradiance; + bool u_refractionTwoSided; + + + vec3 u_viewPosition; + + + int u_numActiveLightSources; + + vec4 out1; + int numActiveLightSources() + { + return min(u_numActiveLightSources, MAX_LIGHT_SOURCES) ; + } + + void sampleLightSource(LightData light, float3 position, thread lightshader& result) + { + result.intensity = float3(0.0); + result.direction = float3(0.0); + } + + void mx_roughness_anisotropy(float roughness, float anisotropy, thread vec2& result) + { + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } + } + + + // https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf + // Equation 2 + float mx_imageworks_sheen_NDF(float NdotH, float roughness) + { + float invRoughness = 1.0 / max(roughness, 0.005); + float cos2 = NdotH * NdotH; + float sin2 = 1.0 - cos2; + return (2.0 + invRoughness) * pow(sin2, invRoughness * 0.5) / (2.0 * M_PI); + } + + float mx_imageworks_sheen_brdf(float NdotL, float NdotV, float NdotH, float roughness) + { + // Microfacet distribution. + float D = mx_imageworks_sheen_NDF(NdotH, roughness); + + // Fresnel and geometry terms are ignored. + float F = 1.0; + float G = 1.0; + + // We use a smoother denominator, as in: + // https://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf + return D * F * G / (4.0 * (NdotL + NdotV - NdotL*NdotV)); + } + + // Rational quadratic fit to Monte Carlo data for Imageworks sheen directional albedo. + float mx_imageworks_sheen_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(13.67300, 1.0) + + vec2(-68.78018, 61.57746) * NdotV + + vec2(799.08825, 442.78211) * roughness + + vec2(-905.00061, 2597.49308) * NdotV * roughness + + vec2(60.28956, 121.81241) * mx_square(NdotV) + + vec2(1086.96473, 3045.55075) * mx_square(roughness); + return r.x / r.y; + } + + float mx_imageworks_sheen_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_imageworks_sheen_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0f - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction and half vector. + vec3 L = mx_uniform_sample_hemisphere(Xi); + vec3 H = normalize(L + V); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float NdotH = clamp(H.z, M_FLOAT_EPS, 1.0); + + // Compute sheen reflectance. + float reflectance = mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = reflectance * NdotL / uniform_pdf; + radiance += reflectance * NdotL * 2.0 * M_PI; + } + + // Return the final directional albedo. + return radiance / float(SAMPLE_COUNT); + } + + float mx_imageworks_sheen_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 0 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_analytic(NdotV, roughness); + #elif DIRECTIONAL_ALBEDO_METHOD == 1 + float dirAlbedo = mx_imageworks_sheen_dir_albedo_table_lookup(NdotV, roughness); + #else + float dirAlbedo = mx_imageworks_sheen_dir_albedo_monte_carlo(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // The following functions are adapted from https://github.com/tizian/ltc-sheen. + // "Practical Multiple-Scattering Sheen Using Linearly Transformed Cosines", Zeltner et al. + + // Gaussian fit to directional albedo table. + float mx_zeltner_sheen_dir_albedo(float x, float y) + { + float s = y*(0.0206607 + 1.58491*y)/(0.0379424 + y*(1.32227 + y)); + float m = y*(-0.193854 + y*(-1.14885 + y*(1.7932 - 0.95943*y*y)))/(0.046391 + y); + float o = y*(0.000654023 + (-0.0207818 + 0.119681*y)*y)/(1.26264 + y*(-1.92021 + y)); + return exp(-0.5*mx_square((x - m)/s))/(s*sqrt(2.0*M_PI)) + o; + } + + // Rational fits to LTC matrix coefficients. + float mx_zeltner_sheen_ltc_aInv(float x, float y) + { + return (2.58126*x + 0.813703*y)*y/(1.0 + 0.310327*x*x + 2.60994*x*y); + } + + float mx_zeltner_sheen_ltc_bInv(float x, float y) + { + return sqrt(1.0 - x)*(y - 1.0)*y*y*y/(0.0000254053 + 1.71228*x - 1.71506*x*y + 1.34174*y*y); + } + + // V and N are assumed to be unit vectors. + mat3 mx_orthonormal_basis_ltc(vec3 V, vec3 N, float NdotV) + { + // Generate a tangent vector in the plane of V and N. + // This required to correctly orient the LTC lobe. + vec3 X = V - N*NdotV; + float lenSqr = dot(X, X); + if (lenSqr > 0.0) + { + X *= mx_inversesqrt(lenSqr); + vec3 Y = cross(N, X); + return mat3(X, Y, N); + } + + // If lenSqr == 0, then V == N, so any orthonormal basis will do. + return mx_orthonormal_basis(N); + } + + // Multiplication by directional albedo is handled by the calling function. + float mx_zeltner_sheen_brdf(vec3 L, vec3 V, vec3 N, float NdotV, float roughness) + { + mat3 toLTC = transpose(mx_orthonormal_basis_ltc(V, N, NdotV)); + vec3 w = toLTC * L; + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform w to original configuration (clamped cosine). + // |aInv 0 bInv| + // wo = M^-1 . w = | 0 aInv 0| . w + // | 0 0 1| + vec3 wo = vec3(aInv*w.x + bInv*w.z, aInv * w.y, w.z); + float lenSqr = dot(wo, wo); + + // D(w) = Do(M^-1.w / ||M^-1.w||) . |M^-1| / ||M^-1.w||^3 + // = Do(M^-1.w) . |M^-1| / ||M^-1.w||^4 + // = Do(wo) . |M^-1| / dot(wo, wo)^2 + // = Do(wo) . aInv^2 / dot(wo, wo)^2 + // = Do(wo) . (aInv / dot(wo, wo))^2 + return max(wo.z, 0.0) * M_PI_INV * mx_square(aInv / lenSqr); + } + + vec3 mx_zeltner_sheen_importance_sample(vec2 Xi, vec3 V, vec3 N, float roughness, thread float& pdf) + { + float NdotV = clamp(dot(N, V), 0.0, 1.0); + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 wo = mx_cosine_sample_hemisphere(Xi); + + float aInv = mx_zeltner_sheen_ltc_aInv(NdotV, roughness); + float bInv = mx_zeltner_sheen_ltc_bInv(NdotV, roughness); + + // Transform wo from original configuration (clamped cosine). + // |1/aInv 0 -bInv/aInv| + // w = M . wo = | 0 1/aInv 0| . wo + // | 0 0 1| + vec3 w = vec3(wo.x/aInv - wo.z*bInv/aInv, wo.y / aInv, wo.z); + + float lenSqr = dot(w, w); + w *= mx_inversesqrt(lenSqr); + + // D(w) = Do(wo) . ||M.wo||^3 / |M| + // = Do(wo / ||M.wo||) . ||M.wo||^4 / |M| + // = Do(w) . ||M.wo||^4 / |M| (possible because M doesn't change z component) + // = Do(w) . dot(w, w)^2 * aInv^2 + // = Do(w) . (aInv * dot(w, w))^2 + pdf = max(w.z, 0.0) * M_PI_INV * mx_square(aInv * lenSqr); + + mat3 fromLTC = mx_orthonormal_basis_ltc(V, N, NdotV); + w = fromLTC * w; + + return w; + } + + void mx_sheen_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + if (mode == 0) + { + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotH = clamp(dot(N, H), M_FLOAT_EPS, 1.0); + + vec3 fr = color * mx_imageworks_sheen_brdf(NdotL, NdotV, NdotH, roughness); + float dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + + // We need to include NdotL from the light integral here + // as in this case it's not cancelled thread by& the BRDF denominator. + bsdf.response = fr * NdotL * occlusion * weight; + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + + vec3 fr = color * mx_zeltner_sheen_brdf(L, V, N, NdotV, roughness); + float dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = dirAlbedo * fr * occlusion * weight; + } + } + + void mx_sheen_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 N, int mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + float dirAlbedo; + if (mode == 0) + { + dirAlbedo = mx_imageworks_sheen_dir_albedo(NdotV, roughness); + } + else + { + roughness = clamp(roughness, 0.01, 1.0); // Clamp to range of original impl. + dirAlbedo = mx_zeltner_sheen_dir_albedo(NdotV, roughness); + } + + vec3 Li = mx_environment_irradiance(N); + bsdf.throughput = vec3(1.0 - dirAlbedo * weight); + bsdf.response = Li * color * dirAlbedo * weight; + } + + void mx_luminance_color3(vec3 _in, vec3 lumacoeffs, thread vec3& result) + { + result = vec3(dot(_in, lumacoeffs)); + } + + mat4 mx_rotationMatrix(vec3 axis, float angle) + { + axis = normalize(axis); + float s = mx_sin(angle); + float c = mx_cos(angle); + float oc = 1.0 - c; + + return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, + oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, + oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + void mx_rotate_vector3(vec3 _in, float amount, vec3 axis, thread vec3& result) + { + float rotationRadians = mx_radians(amount); + mat4 m = mx_rotationMatrix(axis, rotationRadians); + result = (m * vec4(_in, 1.0)).xyz; + } + + void mx_artistic_ior(vec3 reflectivity, vec3 edge_color, thread vec3& ior, thread vec3& extinction) + { + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + vec3 r = clamp(reflectivity, 0.0, 0.99); + vec3 r_sqrt = sqrt(r); + vec3 n_min = (1.0 - r) / (1.0 + r); + vec3 n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + vec3 np1 = ior + 1.0; + vec3 nm1 = ior - 1.0; + vec3 k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); + } + + void mx_uniform_edf(vec3 N, vec3 L, vec3 color, thread EDF& result) + { + result = color; + } + + + void mx_dielectric_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * safeTint * occlusion * weight / (4.0 * NdotV); + } + + void mx_dielectric_bsdf_transmission(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + if (scatter_mode != 0) + { + bsdf.response = mx_surface_transmission(N, V, X, safeAlpha, distribution, fd, safeTint) * weight; + } + } + + void mx_dielectric_bsdf_indirect(vec3 V, float weight, vec3 tint, float ior, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, int scatter_mode, thread BSDF& bsdf) + { + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + vec3 safeTint = max(tint, 0.0); + FresnelData fd = mx_init_fresnel_dielectric(ior, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + + float F0 = mx_ior_to_f0(ior); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + vec3 dirAlbedo = mx_ggx_dir_albedo(NdotV, avgAlpha, F0, 1.0) * comp; + bsdf.throughput = 1.0 - dirAlbedo * weight; + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + bsdf.response = Li * safeTint * comp * weight; + } + + + void mx_conductor_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + X = normalize(X - dot(X, N) * N); + vec3 Y = cross(N, X); + vec3 H = normalize(L + V); + + float NdotL = clamp(dot(N, L), M_FLOAT_EPS, 1.0); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + float VdotH = clamp(dot(V, H), M_FLOAT_EPS, 1.0); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 Ht = vec3(dot(H, X), dot(H, Y), dot(H, N)); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(VdotH, fd); + float D = mx_ggx_NDF(Ht, safeAlpha); + float G = mx_ggx_smith_G2(NdotL, NdotV, avgAlpha); + + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + // Note: NdotL is cancelled out + bsdf.response = D * F * G * comp * occlusion * weight / (4.0 * NdotV); + } + + void mx_conductor_bsdf_indirect(vec3 V, float weight, vec3 ior_n, vec3 ior_k, vec2 roughness, float thinfilm_thickness, float thinfilm_ior, vec3 N, vec3 X, int distribution, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + N = mx_forward_facing_normal(N, V); + + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + + FresnelData fd = mx_init_fresnel_conductor(ior_n, ior_k, thinfilm_thickness, thinfilm_ior); + vec3 F = mx_compute_fresnel(NdotV, fd); + + vec2 safeAlpha = clamp(roughness, M_FLOAT_EPS, 1.0); + float avgAlpha = mx_average_alpha(safeAlpha); + vec3 comp = mx_ggx_energy_compensation(NdotV, avgAlpha, F); + + vec3 Li = mx_environment_radiance(N, V, X, safeAlpha, distribution, fd); + + bsdf.response = Li * comp * weight; + } + + // We fake diffuse transmission by using diffuse reflection from the opposite side. + // So this BTDF is really a BRDF. + void mx_translucent_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + // Invert normal since we're transmitting light from the other side + float NdotL = dot(L, -normal); + if (NdotL <= 0.0 || weight < M_FLOAT_EPS) + { + return; + } + + bsdf.response = color * weight * NdotL * M_PI_INV; + } + + void mx_translucent_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + // Invert normal since we're transmitting light from the other side + vec3 Li = mx_environment_irradiance(-normal); + bsdf.response = Li * color * weight; + } + + + const float FUJII_CONSTANT_1 = 0.5 - 2.0 / (3.0 * M_PI); + const float FUJII_CONSTANT_2 = 2.0 / 3.0 - 28.0 / (15.0 * M_PI); + + // Qualitative Oren-Nayar diffuse with simplified math: + // https://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf + float mx_oren_nayar_diffuse(float NdotV, float NdotL, float LdotV, float roughness) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : 0.0; + + float sigma2 = mx_square(roughness); + float A = 1.0 - 0.5 * (sigma2 / (sigma2 + 0.33)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + return A + B * stinv; + } + + // Rational quadratic fit to Monte Carlo data for Oren-Nayar directional albedo. + float mx_oren_nayar_diffuse_dir_albedo_analytic(float NdotV, float roughness) + { + vec2 r = vec2(1.0, 1.0) + + vec2(-0.4297, -0.6076) * roughness + + vec2(-0.7632, -0.4993) * NdotV * roughness + + vec2(1.4385, 2.0315) * mx_square(roughness); + return r.x / r.y; + } + + float mx_oren_nayar_diffuse_dir_albedo_table_lookup(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 1 + if (textureSize(u_albedoTable, 0).x > 1) + { + return texture(u_albedoTable, vec2(NdotV, roughness)).b; + } + #endif + return 0.0; + } + + float mx_oren_nayar_diffuse_dir_albedo_monte_carlo(float NdotV, float roughness) + { + NdotV = clamp(NdotV, M_FLOAT_EPS, 1.0); + vec3 V = vec3(sqrt(1.0 - mx_square(NdotV)), 0, NdotV); + + float radiance = 0.0; + const int SAMPLE_COUNT = 64; + for (int i = 0; i < SAMPLE_COUNT; i++) + { + vec2 Xi = mx_spherical_fibonacci(i, SAMPLE_COUNT); + + // Compute the incoming light direction. + vec3 L = mx_uniform_sample_hemisphere(Xi); + + // Compute dot products for this sample. + float NdotL = clamp(L.z, M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + // Compute diffuse reflectance. + float reflectance = mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness); + + // Add the radiance contribution of this sample. + // uniform_pdf = 1 / (2 * PI) + // radiance = (reflectance * NdotL) / (uniform_pdf * PI); + radiance += reflectance * NdotL; + } + + // Apply global components and normalize. + radiance *= 2.0 / float(SAMPLE_COUNT); + + // Return the final directional albedo. + return radiance; + } + + float mx_oren_nayar_diffuse_dir_albedo(float NdotV, float roughness) + { + #if DIRECTIONAL_ALBEDO_METHOD == 2 + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_monte_carlo(NdotV, roughness); + #else + float dirAlbedo = mx_oren_nayar_diffuse_dir_albedo_analytic(NdotV, roughness); + #endif + return clamp(dirAlbedo, 0.0, 1.0); + } + + // Improved Oren-Nayar diffuse from Fujii: + // https://mimosa-pudica.net/improved-oren-nayar.html + float mx_oren_nayar_fujii_diffuse_dir_albedo(float cosTheta, float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + float B = roughness * A; + float Si = sqrt(max(0.0, 1.0 - mx_square(cosTheta))); + float G = Si * (mx_acos(clamp(cosTheta, -1.0, 1.0)) - Si * cosTheta) + + 2.0 * ((Si / cosTheta) * (1.0 - Si * Si * Si) - Si) / 3.0; + return A + (B * G * M_PI_INV); + } + + float mx_oren_nayar_fujii_diffuse_avg_albedo(float roughness) + { + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + return A * (1.0 + FUJII_CONSTANT_2 * roughness); + } + + // Energy-compensated Oren-Nayar diffuse from OpenPBR Surface: + // https://academysoftwarefoundation.github.io/OpenPBR/ + vec3 mx_oren_nayar_compensated_diffuse(float NdotV, float NdotL, float LdotV, float roughness, vec3 color) + { + float s = LdotV - NdotL * NdotV; + float stinv = (s > 0.0) ? s / max(NdotL, NdotV) : s; + + // Compute the single-scatter lobe. + float A = 1.0 / (1.0 + FUJII_CONSTANT_1 * roughness); + vec3 lobeSingleScatter = color * A * (1.0 + roughness * stinv); + + // Compute the multi-scatter lobe. + float dirAlbedoV = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotV, roughness); + float dirAlbedoL = mx_oren_nayar_fujii_diffuse_dir_albedo(NdotL, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + vec3 lobeMultiScatter = colorMultiScatter * + max(M_FLOAT_EPS, 1.0 - dirAlbedoV) * + max(M_FLOAT_EPS, 1.0 - dirAlbedoL) / + max(M_FLOAT_EPS, 1.0 - avgAlbedo); + + // Return the sum. + return lobeSingleScatter + lobeMultiScatter; + } + + vec3 mx_oren_nayar_compensated_diffuse_dir_albedo(float cosTheta, float roughness, vec3 color) + { + float dirAlbedo = mx_oren_nayar_fujii_diffuse_dir_albedo(cosTheta, roughness); + float avgAlbedo = mx_oren_nayar_fujii_diffuse_avg_albedo(roughness); + vec3 colorMultiScatter = mx_square(color) * avgAlbedo / + (vec3(1.0) - color * max(0.0, 1.0 - avgAlbedo)); + return mix(colorMultiScatter, color, dirAlbedo); + } + + // https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf + // Section 5.3 + float mx_burley_diffuse(float NdotV, float NdotL, float LdotH, float roughness) + { + float F90 = 0.5 + (2.0 * roughness * mx_square(LdotH)); + float refL = mx_fresnel_schlick(NdotL, 1.0, F90); + float refV = mx_fresnel_schlick(NdotV, 1.0, F90); + return refL * refV; + } + + // Compute the directional albedo component of Burley diffuse for the given + // view angle and roughness. Curve fit provided by Stephen Hill. + float mx_burley_diffuse_dir_albedo(float NdotV, float roughness) + { + float x = NdotV; + float fit0 = 0.97619 - 0.488095 * mx_pow5(1.0 - x); + float fit1 = 1.55754 + (-2.02221 + (2.56283 - 1.06244 * x) * x) * x; + return mix(fit0, fit1, roughness); + } + + // Evaluate the Burley diffusion profile for the given distance and diffusion shape. + // Based on https://graphics.pixar.com/library/ApproxBSSRDF/ + vec3 mx_burley_diffusion_profile(float dist, vec3 shape) + { + vec3 num1 = exp(-shape * dist); + vec3 num2 = exp(-shape * dist / 3.0); + float denom = max(dist, M_FLOAT_EPS); + return (num1 + num2) / denom; + } + + // Integrate the Burley diffusion profile over a sphere of the given radius. + // Inspired by Eric Penner's presentation in http://advances.realtimerendering.com/s2011/ + vec3 mx_integrate_burley_diffusion(vec3 N, vec3 L, float radius, vec3 mfp) + { + float theta = mx_acos(dot(N, L)); + + // Estimate the Burley diffusion shape from mean free path. + vec3 shape = vec3(1.0) / max(mfp, 0.1); + + // Integrate the profile over the sphere. + vec3 sumD = vec3(0.0); + vec3 sumR = vec3(0.0); + const int SAMPLE_COUNT = 32; + const float SAMPLE_WIDTH = (2.0 * M_PI) / float(SAMPLE_COUNT); + for (int i = 0; i < SAMPLE_COUNT; i++) + { + float x = -M_PI + (float(i) + 0.5) * SAMPLE_WIDTH; + float dist = radius * abs(2.0 * mx_sin(x * 0.5)); + vec3 R = mx_burley_diffusion_profile(dist, shape); + sumD += R * max(mx_cos(theta + x), 0.0); + sumR += R; + } + + return sumD / sumR; + } + + vec3 mx_subsurface_scattering_approx(vec3 N, vec3 L, vec3 P, vec3 albedo, vec3 mfp) + { + float curvature = length(fwidth(N)) / length(fwidth(P)); + float radius = 1.0 / max(curvature, 0.01); + return albedo * mx_integrate_burley_diffusion(N, L, radius, mfp) / vec3(M_PI); + } + + void mx_subsurface_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + vec3 sss = mx_subsurface_scattering_approx(normal, L, P, color, radius); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float visibleOcclusion = 1.0 - NdotL * (1.0 - occlusion); + bsdf.response = sss * visibleOcclusion * weight; + } + + void mx_subsurface_bsdf_indirect(vec3 V, float weight, vec3 color, vec3 radius, float anisotropy, vec3 normal, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + // For now, we render indirect subsurface as simple indirect diffuse. + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * color * weight; + } + + + void mx_oren_nayar_diffuse_bsdf_reflection(vec3 L, vec3 V, vec3 P, float occlusion, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + float NdotL = clamp(dot(normal, L), M_FLOAT_EPS, 1.0); + float LdotV = clamp(dot(L, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse(NdotV, NdotL, LdotV, roughness, color) : + mx_oren_nayar_diffuse(NdotV, NdotL, LdotV, roughness) * color; + bsdf.response = diffuse * occlusion * weight * NdotL * M_PI_INV; + } + + void mx_oren_nayar_diffuse_bsdf_indirect(vec3 V, float weight, vec3 color, float roughness, vec3 normal, bool energy_compensation, thread BSDF& bsdf) + { + bsdf.throughput = vec3(0.0); + + if (weight < M_FLOAT_EPS) + { + return; + } + + normal = mx_forward_facing_normal(normal, V); + + float NdotV = clamp(dot(normal, V), M_FLOAT_EPS, 1.0); + + vec3 diffuse = energy_compensation ? + mx_oren_nayar_compensated_diffuse_dir_albedo(NdotV, roughness, color) : + mx_oren_nayar_diffuse_dir_albedo(NdotV, roughness) * color; + vec3 Li = mx_environment_irradiance(normal); + bsdf.response = Li * diffuse * weight; + } + + void NG_convert_float_color3(float in1, thread vec3& out1) + { + vec3 combine_out = { in1,in1,in1 }; + out1 = combine_out; + } + + + void mx_generalized_schlick_edf(vec3 N, vec3 V, vec3 color0, vec3 color90, float exponent, EDF base, thread EDF& result) + { + N = mx_forward_facing_normal(N, V); + float NdotV = clamp(dot(N, V), M_FLOAT_EPS, 1.0); + vec3 f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; + } + + void NG_standard_surface_surfaceshader_100(float base, vec3 base_color, float diffuse_roughness, float metalness, float specular, vec3 specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, vec3 transmission_color, float transmission_depth, vec3 transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface, vec3 subsurface_color, vec3 subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen, vec3 sheen_color, float sheen_roughness, float coat, vec3 coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vec3 coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission, vec3 emission_color, vec3 opacity, bool thin_walled, vec3 normal, vec3 tangent, thread surfaceshader& out1) + { + vec2 coat_roughness_vector_out = vec2(0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + const float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + vec3 metal_reflectivity_out = base_color * base; + vec3 metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + const float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + const float subsurface_color_nonnegative_in2_tmp = 0.000000; + vec3 subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + const float coat_clamped_low_tmp = 0.000000; + const float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + vec3 subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + const float base_color_nonnegative_in2_tmp = 0.000000; + vec3 base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + const vec3 coat_attenuation_bg_tmp = vec3(1.000000, 1.000000, 1.000000); + vec3 coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + const float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + const float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + vec3 emission_weight_out = emission_color * emission; + vec3 opacity_luminance_out = vec3(0.0); + mx_luminance_color3(opacity, vec3(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vec3 coat_tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + vec3 artistic_ior_ior = vec3(0.0); + vec3 artistic_ior_extinction = vec3(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vec3 tangent_rotate_out = vec3(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal, tangent_rotate_out); + const float transmission_roughness_clamped_low_tmp = 0.000000; + const float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + const int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = opacity_luminance_out[opacity_luminance_float_index_tmp]; + vec3 coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + const float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vec3 tangent_rotate_normalize_out = normalize(tangent_rotate_out); + const float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + const float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + const float coat_tangent_value2_tmp = 0.000000; + vec3 coat_tangent_out = (coat_anisotropy > coat_tangent_value2_tmp) ? coat_tangent_rotate_normalize_out : tangent; + vec2 main_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + const float main_tangent_value2_tmp = 0.000000; + vec3 main_tangent_out = (specular_anisotropy > main_tangent_value2_tmp) ? tangent_rotate_normalize_out : tangent; + vec2 transmission_roughness_out = vec2(0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + vec3 coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, vec3(coat_gamma_out)); + vec3 coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, vec3(coat_gamma_out)); + const float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + vec3 emission_color0_out = vec3(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + surfaceshader shader_constructor_out = surfaceshader{float3(0.0),float3(0.0)}; + { + float3 N = normalize(vd.normalWorld); + float3 V = normalize(u_viewPosition - vd.positionWorld); + float3 P = vd.positionWorld; + + float surfaceOpacity = opacity_luminance_float_out; + + // Shadow occlusion + float occlusion = 1.0; + + // Light loop + int numLights = numActiveLightSources(); + lightshader lightShader; + for (int activeLightIndex = 0; activeLightIndex < numLights; ++activeLightIndex) + { + sampleLightSource(u_lightData[activeLightIndex], vd.positionWorld, lightShader); + float3 L = lightShader.direction; + + // Calculate the BSDF response for this light source + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_reflection(L, V, P, occlusion, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_reflection(L, V, P, occlusion, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_reflection(L, V, P, occlusion, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_reflection(L, V, P, occlusion, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_reflection(L, V, P, occlusion, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + // Accumulate the light's contribution + shader_constructor_out.color += lightShader.intensity * coat_layer_out.response; + } + + // Ambient occlusion + occlusion = 1.0; + + // Add environment contribution + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_conductor_bsdf_indirect(V, 1.000000, artistic_ior_ior, artistic_ior_extinction, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, metal_bsdf_out); + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_indirect(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_sheen_bsdf_indirect(V, sheen, sheen_color, sheen_roughness, normal, 0, sheen_bsdf_out); + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_translucent_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, normal, translucent_bsdf_out); + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_subsurface_bsdf_indirect(V, 1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_oren_nayar_diffuse_bsdf_indirect(V, base, coat_affected_diffuse_color_out, diffuse_roughness, normal, false, diffuse_bsdf_out); + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + + shader_constructor_out.color += occlusion * coat_layer_out.response; + } + + // Add surface emission + { + EDF emission_edf_out = EDF(0.0); + mx_uniform_edf(N, V, emission_weight_out, emission_edf_out); + EDF coat_tinted_emission_edf_out = emission_edf_out * coat_color; + EDF coat_emission_edf_out = EDF(0.0); + mx_generalized_schlick_edf(N, V, emission_color0_out, vec3(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + // Omitted node 'emission_edf'. Function already called in this scope. + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + shader_constructor_out.color += blended_coat_emission_edf_out; + } + + // Calculate the BSDF transmission for viewing direction + { + BSDF coat_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, coat, vec3(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, 0, 0, coat_bsdf_out); + BSDF metal_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF specular_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal, main_tangent_out, 0, 0, specular_bsdf_out); + BSDF transmission_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + mx_dielectric_bsdf_transmission(V, 1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal, main_tangent_out, 0, 1, transmission_bsdf_out); + BSDF sheen_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF translucent_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF selected_subsurface_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + selected_subsurface_bsdf_out.response = mix(subsurface_bsdf_out.response, translucent_bsdf_out.response, subsurface_selector_out); + selected_subsurface_bsdf_out.throughput = mix(subsurface_bsdf_out.throughput, translucent_bsdf_out.throughput, subsurface_selector_out); + BSDF diffuse_bsdf_out = BSDF{float3(0.0),float3(1.0)}; + BSDF subsurface_mix_out = BSDF{float3(0.0),float3(1.0)}; + subsurface_mix_out.response = mix(diffuse_bsdf_out.response, selected_subsurface_bsdf_out.response, subsurface); + subsurface_mix_out.throughput = mix(diffuse_bsdf_out.throughput, selected_subsurface_bsdf_out.throughput, subsurface); + BSDF sheen_layer_out = BSDF{float3(0.0),float3(1.0)}; + sheen_layer_out.response = sheen_bsdf_out.response + subsurface_mix_out.response * sheen_bsdf_out.throughput; + sheen_layer_out.throughput = sheen_bsdf_out.throughput * subsurface_mix_out.throughput; + BSDF transmission_mix_out = BSDF{float3(0.0),float3(1.0)}; + transmission_mix_out.response = mix(sheen_layer_out.response, transmission_bsdf_out.response, transmission); + transmission_mix_out.throughput = mix(sheen_layer_out.throughput, transmission_bsdf_out.throughput, transmission); + BSDF specular_layer_out = BSDF{float3(0.0),float3(1.0)}; + specular_layer_out.response = specular_bsdf_out.response + transmission_mix_out.response * specular_bsdf_out.throughput; + specular_layer_out.throughput = specular_bsdf_out.throughput * transmission_mix_out.throughput; + BSDF metalness_mix_out = BSDF{float3(0.0),float3(1.0)}; + metalness_mix_out.response = mix(specular_layer_out.response, metal_bsdf_out.response, metalness); + metalness_mix_out.throughput = mix(specular_layer_out.throughput, metal_bsdf_out.throughput, metalness); + vec3 thin_film_layer_attenuated_out_in2_clamped = clamp(coat_attenuation_out, 0.0, 1.0); + BSDF thin_film_layer_attenuated_out = BSDF{float3(0.0),float3(1.0)}; + thin_film_layer_attenuated_out.response = metalness_mix_out.response * thin_film_layer_attenuated_out_in2_clamped; + thin_film_layer_attenuated_out.throughput = metalness_mix_out.throughput * thin_film_layer_attenuated_out_in2_clamped; + BSDF coat_layer_out = BSDF{float3(0.0),float3(1.0)}; + coat_layer_out.response = coat_bsdf_out.response + thin_film_layer_attenuated_out.response * coat_bsdf_out.throughput; + coat_layer_out.throughput = coat_bsdf_out.throughput * thin_film_layer_attenuated_out.throughput; + shader_constructor_out.color += coat_layer_out.response; + } + + // Compute and apply surface opacity + { + shader_constructor_out.color *= surfaceOpacity; + shader_constructor_out.transparency = mix(float3(1.0), shader_constructor_out.transparency, surfaceOpacity); + } + } + + out1 = shader_constructor_out; + } + + PixelOutputs FragmentMain() + { + vec3 geomprop_Nworld_out1 = normalize(vd.normalWorld); + vec3 geomprop_Tworld_out1 = normalize(vd.tangentWorld); + surfaceshader SR_velvet_out = surfaceshader{float3(0.0),float3(0.0)}; + NG_standard_surface_surfaceshader_100(SR_velvet_base, SR_velvet_base_color, SR_velvet_diffuse_roughness, SR_velvet_metalness, SR_velvet_specular, SR_velvet_specular_color, SR_velvet_specular_roughness, SR_velvet_specular_IOR, SR_velvet_specular_anisotropy, SR_velvet_specular_rotation, SR_velvet_transmission, SR_velvet_transmission_color, SR_velvet_transmission_depth, SR_velvet_transmission_scatter, SR_velvet_transmission_scatter_anisotropy, SR_velvet_transmission_dispersion, SR_velvet_transmission_extra_roughness, SR_velvet_subsurface, SR_velvet_subsurface_color, SR_velvet_subsurface_radius, SR_velvet_subsurface_scale, SR_velvet_subsurface_anisotropy, SR_velvet_sheen, SR_velvet_sheen_color, SR_velvet_sheen_roughness, SR_velvet_coat, SR_velvet_coat_color, SR_velvet_coat_roughness, SR_velvet_coat_anisotropy, SR_velvet_coat_rotation, SR_velvet_coat_IOR, geomprop_Nworld_out1, SR_velvet_coat_affect_color, SR_velvet_coat_affect_roughness, SR_velvet_thin_film_thickness, SR_velvet_thin_film_IOR, SR_velvet_emission, SR_velvet_emission_color, SR_velvet_opacity, SR_velvet_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_velvet_out); + material Velvet_out = SR_velvet_out; + out1 = float4(Velvet_out.color, 1.0); +return PixelOutputs{out1 }; + } + +}; +fragment PixelOutputs FragmentMain( +VertexData vd [[ stage_in ]], constant LightData_pixel& u_lightData[[ buffer(0) ]], constant PublicUniforms& u_pub[[ buffer(1) ]], texture2d u_envRadiance_tex [[texture(0)]], sampler u_envRadiance_sampler [[sampler(0)]] +, texture2d u_envIrradiance_tex [[texture(1)]], sampler u_envIrradiance_sampler [[sampler(1)]] +, constant PrivateUniforms& u_prv[[ buffer(2) ]]) +{ + GlobalContext ctx {vd, u_lightData.u_lightData + , u_pub.backsurfaceshader + , u_pub.displacementshader1 + , u_pub.SR_velvet_base + , u_pub.SR_velvet_base_color + , u_pub.SR_velvet_diffuse_roughness + , u_pub.SR_velvet_metalness + , u_pub.SR_velvet_specular + , u_pub.SR_velvet_specular_color + , u_pub.SR_velvet_specular_roughness + , u_pub.SR_velvet_specular_IOR + , u_pub.SR_velvet_specular_anisotropy + , u_pub.SR_velvet_specular_rotation + , u_pub.SR_velvet_transmission + , u_pub.SR_velvet_transmission_color + , u_pub.SR_velvet_transmission_depth + , u_pub.SR_velvet_transmission_scatter + , u_pub.SR_velvet_transmission_scatter_anisotropy + , u_pub.SR_velvet_transmission_dispersion + , u_pub.SR_velvet_transmission_extra_roughness + , u_pub.SR_velvet_subsurface + , u_pub.SR_velvet_subsurface_color + , u_pub.SR_velvet_subsurface_radius + , u_pub.SR_velvet_subsurface_scale + , u_pub.SR_velvet_subsurface_anisotropy + , u_pub.SR_velvet_sheen + , u_pub.SR_velvet_sheen_color + , u_pub.SR_velvet_sheen_roughness + , u_pub.SR_velvet_coat + , u_pub.SR_velvet_coat_color + , u_pub.SR_velvet_coat_roughness + , u_pub.SR_velvet_coat_anisotropy + , u_pub.SR_velvet_coat_rotation + , u_pub.SR_velvet_coat_IOR + , u_pub.SR_velvet_coat_affect_color + , u_pub.SR_velvet_coat_affect_roughness + , u_pub.SR_velvet_thin_film_thickness + , u_pub.SR_velvet_thin_film_IOR + , u_pub.SR_velvet_emission + , u_pub.SR_velvet_emission_color + , u_pub.SR_velvet_opacity + , u_pub.SR_velvet_thin_walled + , u_prv.u_envMatrix +, MetalTexture { +u_envRadiance_tex, u_envRadiance_sampler } + , u_prv.u_envLightIntensity + , u_prv.u_envRadianceMips + , u_prv.u_envRadianceSamples +, MetalTexture { +u_envIrradiance_tex, u_envIrradiance_sampler } + , u_prv.u_refractionTwoSided + , u_prv.u_viewPosition + , u_prv.u_numActiveLightSources + }; + return ctx.FragmentMain(); +} + diff --git a/Materials/Examples/StandardSurface/Velvet.msl.vert b/Materials/Examples/StandardSurface/Velvet.msl.vert new file mode 100644 index 0000000000..0403035ca6 --- /dev/null +++ b/Materials/Examples/StandardSurface/Velvet.msl.vert @@ -0,0 +1,110 @@ +//Metal Shading Language version 2.3 +#define __METAL__ +#include +#include +using namespace metal; +#define vec2 float2 +#define vec3 float3 +#define vec4 float4 +#define ivec2 int2 +#define ivec3 int3 +#define ivec4 int4 +#define uvec2 uint2 +#define uvec3 uint3 +#define uvec4 uint4 +#define bvec2 bool2 +#define bvec3 bool3 +#define bvec4 bool4 +#define mat3 float3x3 +#define mat4 float4x4 + + +// Uniform block: PrivateUniforms +struct PrivateUniforms +{ + mat4 u_worldMatrix; + mat4 u_viewProjectionMatrix; + mat4 u_worldInverseTransposeMatrix; +}; + +// Inputs block: VertexInputs +struct VertexInputs +{ + vec3 i_position [[attribute(0)]]; + vec3 i_normal [[attribute(1)]]; + vec3 i_tangent [[attribute(2)]]; +}; +struct VertexData +{ + float4 pos [[position]]; + vec3 normalWorld; + vec3 tangentWorld; + vec3 positionWorld; +}; + +struct GlobalContext +{ + GlobalContext( + vec3 i_position +, vec3 i_normal +, vec3 i_tangent + , mat4 u_worldMatrix + + , mat4 u_viewProjectionMatrix + + , mat4 u_worldInverseTransposeMatrix + + ) : + i_position(i_position) +, i_normal(i_normal) +, i_tangent(i_tangent) + , u_worldMatrix(u_worldMatrix) + + , u_viewProjectionMatrix(u_viewProjectionMatrix) + + , u_worldInverseTransposeMatrix(u_worldInverseTransposeMatrix) + + {} + vec3 i_position; + + vec3 i_normal; + + vec3 i_tangent; + + mat4 u_worldMatrix; + + + mat4 u_viewProjectionMatrix; + + + mat4 u_worldInverseTransposeMatrix; + + VertexData VertexMain() + { + VertexData vd; + float4 hPositionWorld = u_worldMatrix * float4(i_position, 1.0); + vd.pos = u_viewProjectionMatrix * hPositionWorld; + vd.normalWorld = normalize((u_worldInverseTransposeMatrix * vec4(i_normal, 0.0)).xyz); + vd.tangentWorld = normalize((u_worldMatrix * vec4(i_tangent, 0.0)).xyz); + vd.positionWorld = hPositionWorld.xyz; + + return vd; + // Omitted node 'geomprop_Nworld'. Function already called in this scope. + // Omitted node 'geomprop_Tworld'. Function already called in this scope. + // Omitted node 'SR_velvet'. Function already called in this scope. + // Omitted node 'Velvet'. Function already called in this scope. + } + +}; +vertex VertexData VertexMain( +VertexInputs i_vs [[ stage_in ]], constant PrivateUniforms& u_prv[[ buffer(3) ]]) +{ + GlobalContext ctx {i_vs.i_position, i_vs.i_normal, i_vs.i_tangent , u_prv.u_worldMatrix + , u_prv.u_viewProjectionMatrix + , u_prv.u_worldInverseTransposeMatrix + }; + VertexData out = ctx.VertexMain(); + out.pos.y = -out.pos.y; + return out; +} + diff --git a/Materials/Examples/StandardSurface/Velvet.osl b/Materials/Examples/StandardSurface/Velvet.osl new file mode 100644 index 0000000000..fe44266643 --- /dev/null +++ b/Materials/Examples/StandardSurface/Velvet.osl @@ -0,0 +1,457 @@ +#include "mx_funcs.h" + +#define true 1 +#define false 0 +struct textureresource { string filename; string colorspace; }; +#define BSDF closure color +#define EDF closure color +#define VDF closure color +struct surfaceshader { closure color bsdf; closure color edf; float opacity; }; +#define volumeshader closure color +#define displacementshader vector +#define lightshader closure color +#define MATERIAL closure color + +#define M_FLOAT_EPS 1e-8 + +void mx_roughness_anisotropy(float roughness, float anisotropy, output vector2 result) +{ + float roughness_sqr = clamp(roughness*roughness, M_FLOAT_EPS, 1.0); + if (anisotropy > 0.0) + { + float aspect = sqrt(1.0 - clamp(anisotropy, 0.0, 0.98)); + result.x = min(roughness_sqr / aspect, 1.0); + result.y = roughness_sqr * aspect; + } + else + { + result.x = roughness_sqr; + result.y = roughness_sqr; + } +} + +void mx_luminance_color3(color in, color lumacoeffs, output color result) +{ + result = dot(in, lumacoeffs); +} + +matrix rotationMatrix(vector axis, float angle) +{ + vector nAxis = normalize(axis); + float s = sin(angle); + float c = cos(angle); + float oc = 1.0 - c; + + return matrix(oc * nAxis[0] * nAxis[0] + c, oc * nAxis[0] * nAxis[1] - nAxis[2] * s, oc * nAxis[2] * nAxis[0] + nAxis[1] * s, 0.0, + oc * nAxis[0] * nAxis[1] + nAxis[2] * s, oc * nAxis[1] * nAxis[1] + c, oc * nAxis[1] * nAxis[2] - nAxis[0] * s, 0.0, + oc * nAxis[2] * nAxis[0] - nAxis[1] * s, oc * nAxis[1] * nAxis[2] + nAxis[0] * s, oc * nAxis[2] * nAxis[2] + c, 0.0, + 0.0, 0.0, 0.0, 1.0); +} + +void mx_rotate_vector3(vector _in, float amount, vector axis, output vector result) +{ + float rotationRadians = radians(amount); + matrix m = rotationMatrix(axis, rotationRadians); + vector4 trans = transform(m, vector4(_in[0], _in[1], _in[2], 1.0)); + result = vector(trans.x, trans.y, trans.z); +} + +void mx_artistic_ior(color reflectivity, color edge_color, output vector ior, output vector extinction) +{ + // "Artist Friendly Metallic Fresnel", Ole Gulbrandsen, 2014 + // http://jcgt.org/published/0003/04/03/paper.pdf + + color r = clamp(reflectivity, 0.0, 0.99); + color r_sqrt = sqrt(r); + color n_min = (1.0 - r) / (1.0 + r); + color n_max = (1.0 + r_sqrt) / (1.0 - r_sqrt); + ior = mix(n_max, n_min, edge_color); + + color np1 = ior + 1.0; + color nm1 = ior - 1.0; + color k2 = (np1*np1 * r - nm1*nm1) / (1.0 - r); + k2 = max(k2, 0.0); + extinction = sqrt(k2); +} + +void mx_dielectric_bsdf(float weight, color tint, float ior, vector2 roughness, float thinfilm_thickness, float thinfilm_ior, normal N, vector U, string distribution, string scatter_mode, output BSDF bsdf) +{ + if (scatter_mode == "R") + { + bsdf = weight * dielectric_bsdf(N, U, tint, color(0.0), roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else if (scatter_mode == "T") + { + bsdf = weight * dielectric_bsdf(N, U, color(0.0), tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } + else + { + bsdf = weight * dielectric_bsdf(N, U, tint, tint, roughness.x, roughness.y, ior, distribution, "thinfilm_thickness", thinfilm_thickness, "thinfilm_ior", thinfilm_ior); + } +} + +void mx_subsurface_bsdf(float weight, color _color, color radius, float anisotropy, normal N, output BSDF bsdf) +{ + // TODO: Subsurface closure is not supported by vanilla OSL. + bsdf = _color * weight * diffuse(N); +} + +void NG_convert_float_color3(float in, output color out) +{ + color combine_out = color( in,in,in ); + out = combine_out; +} + +float mx_square(float x) +{ + return x*x; +} + +vector2 mx_square(vector2 x) +{ + return x*x; +} + +vector mx_square(vector x) +{ + return x*x; +} + +vector4 mx_square(vector4 x) +{ + return x*x; +} + +float mx_pow5(float x) +{ + return mx_square(mx_square(x)) * x; +} + +color mx_fresnel_conductor(float cosTheta, vector n, vector k) +{ + float c2 = cosTheta*cosTheta; + vector n2_k2 = n*n + k*k; + vector nc2 = 2.0 * n * cosTheta; + + vector rs_a = n2_k2 + c2; + vector rp_a = n2_k2 * c2 + 1.0; + vector rs = (rs_a - nc2) / (rs_a + nc2); + vector rp = (rp_a - nc2) / (rp_a + nc2); + + return 0.5 * (rs + rp); +} + +// Standard Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} +color mx_fresnel_schlick(float cosTheta, color F0) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return F0 + (1.0 - F0) * x5; +} + +// Generalized Schlick Fresnel +float mx_fresnel_schlick(float cosTheta, float F0, float F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} +color mx_fresnel_schlick(float cosTheta, color F0, color F90) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + float x5 = mx_pow5(x); + return mix(F0, F90, x5); +} + +// Generalized Schlick Fresnel with a variable exponent +color mx_fresnel_schlick(float cosTheta, float f0, float f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} +color mx_fresnel_schlick(float cosTheta, color f0, color f90, float exponent) +{ + float x = clamp(1.0 - cosTheta, 0.0, 1.0); + return mix(f0, f90, pow(x, exponent)); +} + +void mx_generalized_schlick_edf(color color0, color color90, float exponent, EDF base, output EDF result) +{ + float NdotV = fabs(dot(N,-I)); + color f = mx_fresnel_schlick(NdotV, color0, color90, exponent); + result = base * f; +} + +void mx_surface(BSDF bsdf, EDF edf, float opacity, int thin_walled, output surfaceshader result) +{ + result.bsdf = bsdf; + result.edf = edf; + result.opacity = clamp(opacity, 0.0, 1.0); +} + +void NG_standard_surface_surfaceshader_100(float base, color base_color, float diffuse_roughness, float metalness, float specular, color specular_color, float specular_roughness, float specular_IOR, float specular_anisotropy, float specular_rotation, float transmission, color transmission_color, float transmission_depth, color transmission_scatter, float transmission_scatter_anisotropy, float transmission_dispersion, float transmission_extra_roughness, float subsurface1, color subsurface_color, color subsurface_radius, float subsurface_scale, float subsurface_anisotropy, float sheen1, color sheen_color, float sheen_roughness, float coat, color coat_color, float coat_roughness, float coat_anisotropy, float coat_rotation, float coat_IOR, vector coat_normal, float coat_affect_color, float coat_affect_roughness, float thin_film_thickness, float thin_film_IOR, float emission1, color emission_color, color opacity, int thin_walled, vector normal1, vector tangent, output surfaceshader out) +{ + closure color null_closure = 0; + vector2 coat_roughness_vector_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_roughness, coat_anisotropy, coat_roughness_vector_out); + float coat_tangent_rotate_degree_in2_tmp = 360.000000; + float coat_tangent_rotate_degree_out = coat_rotation * coat_tangent_rotate_degree_in2_tmp; + color metal_reflectivity_out = base_color * base; + color metal_edgecolor_out = specular_color * specular; + float coat_affect_roughness_multiply1_out = coat_affect_roughness * coat; + float tangent_rotate_degree_in2_tmp = 360.000000; + float tangent_rotate_degree_out = specular_rotation * tangent_rotate_degree_in2_tmp; + float transmission_roughness_add_out = specular_roughness + transmission_extra_roughness; + float subsurface_color_nonnegative_in2_tmp = 0.000000; + color subsurface_color_nonnegative_out = max(subsurface_color, subsurface_color_nonnegative_in2_tmp); + float coat_clamped_low_tmp = 0.000000; + float coat_clamped_high_tmp = 1.000000; + float coat_clamped_out = clamp(coat, coat_clamped_low_tmp, coat_clamped_high_tmp); + color subsurface_radius_scaled_out = subsurface_radius * subsurface_scale; + float subsurface_selector_out = float(thin_walled); + float base_color_nonnegative_in2_tmp = 0.000000; + color base_color_nonnegative_out = max(base_color, base_color_nonnegative_in2_tmp); + color coat_attenuation_bg_tmp = color(1.000000, 1.000000, 1.000000); + color coat_attenuation_out = mix(coat_attenuation_bg_tmp, coat_color, coat); + float one_minus_coat_ior_in1_tmp = 1.000000; + float one_minus_coat_ior_out = one_minus_coat_ior_in1_tmp - coat_IOR; + float one_plus_coat_ior_in1_tmp = 1.000000; + float one_plus_coat_ior_out = one_plus_coat_ior_in1_tmp + coat_IOR; + color emission_weight_out = emission_color * emission1; + color opacity_luminance_out = color(0.0); + mx_luminance_color3(opacity, color(0.272229, 0.674082, 0.053689), opacity_luminance_out); + vector coat_tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, coat_tangent_rotate_degree_out, coat_normal, coat_tangent_rotate_out); + color artistic_ior_ior = color(0.0); + color artistic_ior_extinction = color(0.0); + mx_artistic_ior(metal_reflectivity_out, metal_edgecolor_out, artistic_ior_ior, artistic_ior_extinction); + float coat_affect_roughness_multiply2_out = coat_affect_roughness_multiply1_out * coat_roughness; + vector tangent_rotate_out = vector(0.0); + mx_rotate_vector3(tangent, tangent_rotate_degree_out, normal1, tangent_rotate_out); + float transmission_roughness_clamped_low_tmp = 0.000000; + float transmission_roughness_clamped_high_tmp = 1.000000; + float transmission_roughness_clamped_out = clamp(transmission_roughness_add_out, transmission_roughness_clamped_low_tmp, transmission_roughness_clamped_high_tmp); + float coat_gamma_multiply_out = coat_clamped_out * coat_affect_color; + float coat_ior_to_F0_sqrt_out = one_minus_coat_ior_out / one_plus_coat_ior_out; + int opacity_luminance_float_index_tmp = 0; + float opacity_luminance_float_out = mx_extract(opacity_luminance_out, opacity_luminance_float_index_tmp); + vector coat_tangent_rotate_normalize_out = normalize(coat_tangent_rotate_out); + float coat_affected_roughness_fg_tmp = 1.000000; + float coat_affected_roughness_out = mix(specular_roughness, coat_affected_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + vector tangent_rotate_normalize_out = normalize(tangent_rotate_out); + float coat_affected_transmission_roughness_fg_tmp = 1.000000; + float coat_affected_transmission_roughness_out = mix(transmission_roughness_clamped_out, coat_affected_transmission_roughness_fg_tmp, coat_affect_roughness_multiply2_out); + float coat_gamma_in2_tmp = 1.000000; + float coat_gamma_out = coat_gamma_multiply_out + coat_gamma_in2_tmp; + float coat_ior_to_F0_out = coat_ior_to_F0_sqrt_out * coat_ior_to_F0_sqrt_out; + float coat_tangent_value2_tmp = 0.000000; + vector coat_tangent_out = mx_ternary(coat_anisotropy > coat_tangent_value2_tmp, coat_tangent_rotate_normalize_out, tangent); + vector2 main_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_roughness_out, specular_anisotropy, main_roughness_out); + float main_tangent_value2_tmp = 0.000000; + vector main_tangent_out = mx_ternary(specular_anisotropy > main_tangent_value2_tmp, tangent_rotate_normalize_out, tangent); + vector2 transmission_roughness_out = vector2(0.0, 0.0); + mx_roughness_anisotropy(coat_affected_transmission_roughness_out, specular_anisotropy, transmission_roughness_out); + color coat_affected_subsurface_color_out = pow(subsurface_color_nonnegative_out, coat_gamma_out); + color coat_affected_diffuse_color_out = pow(base_color_nonnegative_out, coat_gamma_out); + float one_minus_coat_ior_to_F0_in1_tmp = 1.000000; + float one_minus_coat_ior_to_F0_out = one_minus_coat_ior_to_F0_in1_tmp - coat_ior_to_F0_out; + color emission_color0_out = color(0.0); + NG_convert_float_color3(one_minus_coat_ior_to_F0_out, emission_color0_out); + BSDF coat_bsdf_out = null_closure; + mx_dielectric_bsdf(coat, color(1.000000, 1.000000, 1.000000), coat_IOR, coat_roughness_vector_out, 0.000000, 1.500000, coat_normal, coat_tangent_out, "ggx", "R", coat_bsdf_out); + float metal_bsdf_weight_tmp = 1.000000; + string metal_bsdf_distribution_tmp = "ggx"; + BSDF metal_bsdf_out = metal_bsdf_weight_tmp * conductor_bsdf(normal1, main_tangent_out, main_roughness_out.x, main_roughness_out.y, artistic_ior_ior, artistic_ior_extinction, metal_bsdf_distribution_tmp, "thinfilm_thickness", thin_film_thickness, "thinfilm_ior", thin_film_IOR); + BSDF specular_bsdf_out = null_closure; + mx_dielectric_bsdf(specular, specular_color, specular_IOR, main_roughness_out, thin_film_thickness, thin_film_IOR, normal1, main_tangent_out, "ggx", "R", specular_bsdf_out); + BSDF transmission_bsdf_out = null_closure; + mx_dielectric_bsdf(1.000000, transmission_color, specular_IOR, transmission_roughness_out, 0.000000, 1.500000, normal1, main_tangent_out, "ggx", "T", transmission_bsdf_out); + BSDF sheen_bsdf_out = sheen1 * sheen_bsdf(normal1, sheen_color, sheen_roughness); + float translucent_bsdf_weight_tmp = 1.000000; + BSDF translucent_bsdf_out = translucent_bsdf_weight_tmp * translucent_bsdf(normal1, coat_affected_subsurface_color_out); + BSDF subsurface_bsdf_out = null_closure; + mx_subsurface_bsdf(1.000000, coat_affected_subsurface_color_out, subsurface_radius_scaled_out, subsurface_anisotropy, normal1, subsurface_bsdf_out); + BSDF selected_subsurface_bsdf_out = mix(subsurface_bsdf_out, translucent_bsdf_out, subsurface_selector_out); + BSDF diffuse_bsdf_out = base * oren_nayar_diffuse_bsdf(normal1, coat_affected_diffuse_color_out, diffuse_roughness); + BSDF subsurface_mix_out = mix(diffuse_bsdf_out, selected_subsurface_bsdf_out, subsurface1); + BSDF sheen_layer_out = layer(sheen_bsdf_out, subsurface_mix_out); + BSDF transmission_mix_out = mix(sheen_layer_out, transmission_bsdf_out, transmission); + BSDF specular_layer_out = layer(specular_bsdf_out, transmission_mix_out); + BSDF metalness_mix_out = mix(specular_layer_out, metal_bsdf_out, metalness); + BSDF thin_film_layer_attenuated_out = (coat_attenuation_out * metalness_mix_out); + BSDF coat_layer_out = layer(coat_bsdf_out, thin_film_layer_attenuated_out); + EDF emission_edf_out = uniform_edf(emission_weight_out); + EDF coat_tinted_emission_edf_out = (coat_color * emission_edf_out); + EDF coat_emission_edf_out = null_closure; + mx_generalized_schlick_edf(emission_color0_out, color(0.000000, 0.000000, 0.000000), 5.000000, coat_tinted_emission_edf_out, coat_emission_edf_out); + EDF blended_coat_emission_edf_out = mix(emission_edf_out, coat_emission_edf_out, coat); + surfaceshader shader_constructor_out = surfaceshader(null_closure, null_closure, 1.0); + mx_surface(coat_layer_out, blended_coat_emission_edf_out, opacity_luminance_float_out, 0, shader_constructor_out); + out = shader_constructor_out; +} + +MATERIAL mx_surfacematerial(surfaceshader surface, surfaceshader backsurface, displacementshader disp) +{ + float opacity_weight = clamp(surface.opacity, 0.0, 1.0); + return (surface.bsdf + surface.edf) * opacity_weight + transparent() * (1.0 - opacity_weight); +} + +shader Velvet +[[ + string mtlx_category = "surfacematerial", + string mtlx_name = "Velvet" +]] +( + surfaceshader backsurfaceshader = { 0, 0, 1.0 }, + displacementshader displacementshader1 = vector(0.0), + string geomprop_Nworld_space = "world", + string geomprop_Tworld_space = "world", + int geomprop_Tworld_index = 0 + [[ + string widget = "number" + ]], + float SR_velvet_base = 0.800000 + [[ + string widget = "number" + ]], + color SR_velvet_base_color = color(0.029000, 0.000000, 0.047000), + float SR_velvet_diffuse_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_metalness = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_specular = 0.000000 + [[ + string widget = "number" + ]], + color SR_velvet_specular_color = color(0.000000, 0.000000, 0.000000), + float SR_velvet_specular_roughness = 0.693000 + [[ + string widget = "number" + ]], + float SR_velvet_specular_IOR = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_specular_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_specular_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_transmission = 0.000000 + [[ + string widget = "number" + ]], + color SR_velvet_transmission_color = color(1.000000, 1.000000, 1.000000), + float SR_velvet_transmission_depth = 0.000000 + [[ + string widget = "number" + ]], + color SR_velvet_transmission_scatter = color(0.000000, 0.000000, 0.000000), + float SR_velvet_transmission_scatter_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_transmission_dispersion = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_transmission_extra_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_subsurface = 0.000000 + [[ + string widget = "number" + ]], + color SR_velvet_subsurface_color = color(1.000000, 1.000000, 1.000000), + color SR_velvet_subsurface_radius = color(1.000000, 1.000000, 1.000000), + float SR_velvet_subsurface_scale = 1.000000 + [[ + string widget = "number" + ]], + float SR_velvet_subsurface_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_sheen = 1.000000 + [[ + string widget = "number" + ]], + color SR_velvet_sheen_color = color(0.404000, 0.058000, 1.000000), + float SR_velvet_sheen_roughness = 0.300000 + [[ + string widget = "number" + ]], + float SR_velvet_coat = 0.000000 + [[ + string widget = "number" + ]], + color SR_velvet_coat_color = color(1.000000, 1.000000, 1.000000), + float SR_velvet_coat_roughness = 0.100000 + [[ + string widget = "number" + ]], + float SR_velvet_coat_anisotropy = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_coat_rotation = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_coat_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_velvet_coat_affect_color = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_coat_affect_roughness = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_thin_film_thickness = 0.000000 + [[ + string widget = "number" + ]], + float SR_velvet_thin_film_IOR = 1.500000 + [[ + string widget = "number" + ]], + float SR_velvet_emission = 0.000000 + [[ + string widget = "number" + ]], + color SR_velvet_emission_color = color(1.000000, 1.000000, 1.000000), + color SR_velvet_opacity = color(1.000000, 1.000000, 1.000000), + int SR_velvet_thin_walled = 0 + [[ + string widget = "checkBox" + ]], + output MATERIAL out = 0 +) +{ + closure color null_closure = 0; + vector geomprop_Nworld_out1 = transform(geomprop_Nworld_space, N); + vector geomprop_Tworld_out1 = transform(geomprop_Tworld_space, normalize(dPdu)); + surfaceshader SR_velvet_out = surfaceshader(null_closure, null_closure, 1.0); + NG_standard_surface_surfaceshader_100(SR_velvet_base, SR_velvet_base_color, SR_velvet_diffuse_roughness, SR_velvet_metalness, SR_velvet_specular, SR_velvet_specular_color, SR_velvet_specular_roughness, SR_velvet_specular_IOR, SR_velvet_specular_anisotropy, SR_velvet_specular_rotation, SR_velvet_transmission, SR_velvet_transmission_color, SR_velvet_transmission_depth, SR_velvet_transmission_scatter, SR_velvet_transmission_scatter_anisotropy, SR_velvet_transmission_dispersion, SR_velvet_transmission_extra_roughness, SR_velvet_subsurface, SR_velvet_subsurface_color, SR_velvet_subsurface_radius, SR_velvet_subsurface_scale, SR_velvet_subsurface_anisotropy, SR_velvet_sheen, SR_velvet_sheen_color, SR_velvet_sheen_roughness, SR_velvet_coat, SR_velvet_coat_color, SR_velvet_coat_roughness, SR_velvet_coat_anisotropy, SR_velvet_coat_rotation, SR_velvet_coat_IOR, geomprop_Nworld_out1, SR_velvet_coat_affect_color, SR_velvet_coat_affect_roughness, SR_velvet_thin_film_thickness, SR_velvet_thin_film_IOR, SR_velvet_emission, SR_velvet_emission_color, SR_velvet_opacity, SR_velvet_thin_walled, geomprop_Nworld_out1, geomprop_Tworld_out1, SR_velvet_out); + MATERIAL Velvet_out = mx_surfacematerial(SR_velvet_out, backsurfaceshader, displacementshader1); + out = Velvet_out; +} + diff --git a/Materials/Examples/StandardSurface/chess_set/bishop_black_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/bishop_black_base_color.jpg new file mode 100644 index 0000000000..b74cbc50fa Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/bishop_black_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/bishop_black_normal.jpg b/Materials/Examples/StandardSurface/chess_set/bishop_black_normal.jpg new file mode 100644 index 0000000000..f205522e84 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/bishop_black_normal.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/bishop_black_roughness.jpg b/Materials/Examples/StandardSurface/chess_set/bishop_black_roughness.jpg new file mode 100644 index 0000000000..b6fafcf2fb Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/bishop_black_roughness.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/bishop_shared_metallic.jpg b/Materials/Examples/StandardSurface/chess_set/bishop_shared_metallic.jpg new file mode 100644 index 0000000000..d58c8a9d61 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/bishop_shared_metallic.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/bishop_white_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/bishop_white_base_color.jpg new file mode 100644 index 0000000000..bdd10f0561 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/bishop_white_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/bishop_white_normal.jpg b/Materials/Examples/StandardSurface/chess_set/bishop_white_normal.jpg new file mode 100644 index 0000000000..e7e825fe02 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/bishop_white_normal.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/bishop_white_roughness.jpg b/Materials/Examples/StandardSurface/chess_set/bishop_white_roughness.jpg new file mode 100644 index 0000000000..91ff237e5f Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/bishop_white_roughness.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/castle_black_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/castle_black_base_color.jpg new file mode 100644 index 0000000000..101fb07fb6 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/castle_black_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/castle_shared_metallic.jpg b/Materials/Examples/StandardSurface/chess_set/castle_shared_metallic.jpg new file mode 100644 index 0000000000..98ebcb2b35 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/castle_shared_metallic.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/castle_shared_normal.jpg b/Materials/Examples/StandardSurface/chess_set/castle_shared_normal.jpg new file mode 100644 index 0000000000..4e6e5a93ec Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/castle_shared_normal.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/castle_shared_roughness.jpg b/Materials/Examples/StandardSurface/chess_set/castle_shared_roughness.jpg new file mode 100644 index 0000000000..6d67f88316 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/castle_shared_roughness.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/castle_white_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/castle_white_base_color.jpg new file mode 100644 index 0000000000..92cccfdf95 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/castle_white_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/chessboard_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/chessboard_base_color.jpg new file mode 100644 index 0000000000..73ad41121b Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/chessboard_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/chessboard_metallic.jpg b/Materials/Examples/StandardSurface/chess_set/chessboard_metallic.jpg new file mode 100644 index 0000000000..8e54561eb8 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/chessboard_metallic.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/chessboard_normal.jpg b/Materials/Examples/StandardSurface/chess_set/chessboard_normal.jpg new file mode 100644 index 0000000000..d02f3dc15b Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/chessboard_normal.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/chessboard_roughness.jpg b/Materials/Examples/StandardSurface/chess_set/chessboard_roughness.jpg new file mode 100644 index 0000000000..9639d24520 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/chessboard_roughness.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/king_black_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/king_black_base_color.jpg new file mode 100644 index 0000000000..5b0cd47203 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/king_black_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/king_black_normal.jpg b/Materials/Examples/StandardSurface/chess_set/king_black_normal.jpg new file mode 100644 index 0000000000..61983b3b32 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/king_black_normal.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/king_black_roughness.jpg b/Materials/Examples/StandardSurface/chess_set/king_black_roughness.jpg new file mode 100644 index 0000000000..3a81b206e3 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/king_black_roughness.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/king_shared_metallic.jpg b/Materials/Examples/StandardSurface/chess_set/king_shared_metallic.jpg new file mode 100644 index 0000000000..9fc424a678 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/king_shared_metallic.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/king_shared_scattering.jpg b/Materials/Examples/StandardSurface/chess_set/king_shared_scattering.jpg new file mode 100644 index 0000000000..be5468f4de Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/king_shared_scattering.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/king_white_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/king_white_base_color.jpg new file mode 100644 index 0000000000..abe33ebee3 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/king_white_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/king_white_normal.jpg b/Materials/Examples/StandardSurface/chess_set/king_white_normal.jpg new file mode 100644 index 0000000000..65e868d44b Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/king_white_normal.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/king_white_roughness.jpg b/Materials/Examples/StandardSurface/chess_set/king_white_roughness.jpg new file mode 100644 index 0000000000..5bbace7f0a Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/king_white_roughness.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/knight_black_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/knight_black_base_color.jpg new file mode 100644 index 0000000000..68b9d92052 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/knight_black_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/knight_black_normal.jpg b/Materials/Examples/StandardSurface/chess_set/knight_black_normal.jpg new file mode 100644 index 0000000000..223a038b43 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/knight_black_normal.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/knight_black_roughness.jpg b/Materials/Examples/StandardSurface/chess_set/knight_black_roughness.jpg new file mode 100644 index 0000000000..111fccf683 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/knight_black_roughness.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/knight_white_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/knight_white_base_color.jpg new file mode 100644 index 0000000000..e7d34b2306 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/knight_white_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/knight_white_normal.jpg b/Materials/Examples/StandardSurface/chess_set/knight_white_normal.jpg new file mode 100644 index 0000000000..be398eeae2 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/knight_white_normal.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/knight_white_roughness.jpg b/Materials/Examples/StandardSurface/chess_set/knight_white_roughness.jpg new file mode 100644 index 0000000000..2201a35eeb Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/knight_white_roughness.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/pawn_black_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/pawn_black_base_color.jpg new file mode 100644 index 0000000000..f4280f07c3 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/pawn_black_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/pawn_shared_metallic.jpg b/Materials/Examples/StandardSurface/chess_set/pawn_shared_metallic.jpg new file mode 100644 index 0000000000..cd0d5a6713 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/pawn_shared_metallic.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/pawn_shared_normal.jpg b/Materials/Examples/StandardSurface/chess_set/pawn_shared_normal.jpg new file mode 100644 index 0000000000..264480890b Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/pawn_shared_normal.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/pawn_shared_roughness.jpg b/Materials/Examples/StandardSurface/chess_set/pawn_shared_roughness.jpg new file mode 100644 index 0000000000..fd9646199d Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/pawn_shared_roughness.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/pawn_white_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/pawn_white_base_color.jpg new file mode 100644 index 0000000000..d99080935b Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/pawn_white_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/queen_black_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/queen_black_base_color.jpg new file mode 100644 index 0000000000..3e4207c589 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/queen_black_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/queen_black_normal.jpg b/Materials/Examples/StandardSurface/chess_set/queen_black_normal.jpg new file mode 100644 index 0000000000..761589115f Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/queen_black_normal.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/queen_black_roughness.jpg b/Materials/Examples/StandardSurface/chess_set/queen_black_roughness.jpg new file mode 100644 index 0000000000..8c146f0508 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/queen_black_roughness.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/queen_shared_metallic.jpg b/Materials/Examples/StandardSurface/chess_set/queen_shared_metallic.jpg new file mode 100644 index 0000000000..5f82821ed0 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/queen_shared_metallic.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/queen_shared_scattering.jpg b/Materials/Examples/StandardSurface/chess_set/queen_shared_scattering.jpg new file mode 100644 index 0000000000..efecb700bb Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/queen_shared_scattering.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/queen_white_base_color.jpg b/Materials/Examples/StandardSurface/chess_set/queen_white_base_color.jpg new file mode 100644 index 0000000000..89d6825eca Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/queen_white_base_color.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/queen_white_normal.jpg b/Materials/Examples/StandardSurface/chess_set/queen_white_normal.jpg new file mode 100644 index 0000000000..54238c0b95 Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/queen_white_normal.jpg differ diff --git a/Materials/Examples/StandardSurface/chess_set/queen_white_roughness.jpg b/Materials/Examples/StandardSurface/chess_set/queen_white_roughness.jpg new file mode 100644 index 0000000000..f8a981edca Binary files /dev/null and b/Materials/Examples/StandardSurface/chess_set/queen_white_roughness.jpg differ diff --git a/Materials/Examples/StandardSurface/standard_surface_brass_tiled.mtlx b/Materials/Examples/StandardSurface/standard_surface_brass_tiled.mtlx new file mode 100644 index 0000000000..f97a98fcd2 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_brass_tiled.mtlx @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_brick_procedural.mtlx b/Materials/Examples/StandardSurface/standard_surface_brick_procedural.mtlx new file mode 100644 index 0000000000..1728ba4899 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_brick_procedural.mtlx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_carpaint.mtlx b/Materials/Examples/StandardSurface/standard_surface_carpaint.mtlx new file mode 100644 index 0000000000..738970875b --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_carpaint.mtlx @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_chess_set.mtlx b/Materials/Examples/StandardSurface/standard_surface_chess_set.mtlx new file mode 100644 index 0000000000..3cbaf02fac --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_chess_set.mtlx @@ -0,0 +1,555 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_chrome.mtlx b/Materials/Examples/StandardSurface/standard_surface_chrome.mtlx new file mode 100644 index 0000000000..81a5df6cad --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_chrome.mtlx @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_copper.mtlx b/Materials/Examples/StandardSurface/standard_surface_copper.mtlx new file mode 100644 index 0000000000..6eadaefa2e --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_copper.mtlx @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_default.mtlx b/Materials/Examples/StandardSurface/standard_surface_default.mtlx new file mode 100644 index 0000000000..b4f09666c1 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_default.mtlx @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_glass.mtlx b/Materials/Examples/StandardSurface/standard_surface_glass.mtlx new file mode 100644 index 0000000000..5a5461e791 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_glass.mtlx @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_glass_tinted.mtlx b/Materials/Examples/StandardSurface/standard_surface_glass_tinted.mtlx new file mode 100644 index 0000000000..ef515a1bf1 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_glass_tinted.mtlx @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_gold.mtlx b/Materials/Examples/StandardSurface/standard_surface_gold.mtlx new file mode 100644 index 0000000000..d8f0e6bc6f --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_gold.mtlx @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_greysphere.mtlx b/Materials/Examples/StandardSurface/standard_surface_greysphere.mtlx new file mode 100644 index 0000000000..92a1c34190 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_greysphere.mtlx @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_greysphere_calibration.mtlx b/Materials/Examples/StandardSurface/standard_surface_greysphere_calibration.mtlx new file mode 100644 index 0000000000..584f440cd4 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_greysphere_calibration.mtlx @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_jade.mtlx b/Materials/Examples/StandardSurface/standard_surface_jade.mtlx new file mode 100644 index 0000000000..0becdec226 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_jade.mtlx @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_look_brass_tiled.mtlx b/Materials/Examples/StandardSurface/standard_surface_look_brass_tiled.mtlx new file mode 100644 index 0000000000..510f1c27fd --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_look_brass_tiled.mtlx @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_look_wood_tiled.mtlx b/Materials/Examples/StandardSurface/standard_surface_look_wood_tiled.mtlx new file mode 100644 index 0000000000..9a9073d09b --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_look_wood_tiled.mtlx @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_marble_solid.mtlx b/Materials/Examples/StandardSurface/standard_surface_marble_solid.mtlx new file mode 100644 index 0000000000..59c113197f --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_marble_solid.mtlx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_metal_brushed.mtlx b/Materials/Examples/StandardSurface/standard_surface_metal_brushed.mtlx new file mode 100644 index 0000000000..aabc1d0592 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_metal_brushed.mtlx @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_plastic.mtlx b/Materials/Examples/StandardSurface/standard_surface_plastic.mtlx new file mode 100644 index 0000000000..2c16ff4e25 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_plastic.mtlx @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_thin_film.mtlx b/Materials/Examples/StandardSurface/standard_surface_thin_film.mtlx new file mode 100644 index 0000000000..7bda7f34b4 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_thin_film.mtlx @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_velvet.mtlx b/Materials/Examples/StandardSurface/standard_surface_velvet.mtlx new file mode 100644 index 0000000000..473578c949 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_velvet.mtlx @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/StandardSurface/standard_surface_wood_tiled.mtlx b/Materials/Examples/StandardSurface/standard_surface_wood_tiled.mtlx new file mode 100644 index 0000000000..ed6690f071 --- /dev/null +++ b/Materials/Examples/StandardSurface/standard_surface_wood_tiled.mtlx @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/UsdPreviewSurface/usd_preview_surface_brass_tiled.mtlx b/Materials/Examples/UsdPreviewSurface/usd_preview_surface_brass_tiled.mtlx new file mode 100644 index 0000000000..85f6f3e139 --- /dev/null +++ b/Materials/Examples/UsdPreviewSurface/usd_preview_surface_brass_tiled.mtlx @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/UsdPreviewSurface/usd_preview_surface_carpaint.mtlx b/Materials/Examples/UsdPreviewSurface/usd_preview_surface_carpaint.mtlx new file mode 100644 index 0000000000..3fb1b00589 --- /dev/null +++ b/Materials/Examples/UsdPreviewSurface/usd_preview_surface_carpaint.mtlx @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/Materials/Examples/UsdPreviewSurface/usd_preview_surface_default.mtlx b/Materials/Examples/UsdPreviewSurface/usd_preview_surface_default.mtlx new file mode 100644 index 0000000000..62317197b1 --- /dev/null +++ b/Materials/Examples/UsdPreviewSurface/usd_preview_surface_default.mtlx @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/Materials/Examples/UsdPreviewSurface/usd_preview_surface_glass.mtlx b/Materials/Examples/UsdPreviewSurface/usd_preview_surface_glass.mtlx new file mode 100644 index 0000000000..5cc6ab552e --- /dev/null +++ b/Materials/Examples/UsdPreviewSurface/usd_preview_surface_glass.mtlx @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/Materials/Examples/UsdPreviewSurface/usd_preview_surface_gold.mtlx b/Materials/Examples/UsdPreviewSurface/usd_preview_surface_gold.mtlx new file mode 100644 index 0000000000..c1e0e066c5 --- /dev/null +++ b/Materials/Examples/UsdPreviewSurface/usd_preview_surface_gold.mtlx @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/Materials/Examples/UsdPreviewSurface/usd_preview_surface_plastic.mtlx b/Materials/Examples/UsdPreviewSurface/usd_preview_surface_plastic.mtlx new file mode 100644 index 0000000000..58fd5bf11c --- /dev/null +++ b/Materials/Examples/UsdPreviewSurface/usd_preview_surface_plastic.mtlx @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/index.html b/index.html new file mode 100644 index 0000000000..99a91a83ad --- /dev/null +++ b/index.html @@ -0,0 +1,233 @@ + + + + + + MaterialX Web Viewer + + + + +
+
+ + +
+
+ + +
+ +
+ + + diff --git a/main.js b/main.js new file mode 100644 index 0000000000..dc84faf78b --- /dev/null +++ b/main.js @@ -0,0 +1,186 @@ +/* + * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development"). + * This devtool is neither made for production nor for readable output files. + * It uses "eval()" calls to create a separate source file in the browser devtools. + * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) + * or disable the default devtool with "devtool: false". + * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). + */ +/******/ (() => { // webpackBootstrap +/******/ "use strict"; +/******/ var __webpack_modules__ = ({ + +/***/ "./source/dropHandling.js": +/*!********************************!*\ + !*** ./source/dropHandling.js ***! + \********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ dragOverHandler: () => (/* binding */ dragOverHandler),\n/* harmony export */ dropHandler: () => (/* binding */ dropHandler),\n/* harmony export */ setLoadingCallback: () => (/* binding */ setLoadingCallback),\n/* harmony export */ setSceneLoadingCallback: () => (/* binding */ setSceneLoadingCallback)\n/* harmony export */ });\n/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! three */ \"./node_modules/three/build/three.module.js\");\n/* harmony import */ var three_examples_jsm_libs_fflate_module_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three/examples/jsm/libs/fflate.module.js */ \"./node_modules/three/examples/jsm/libs/fflate.module.js\");\n\n\n\nconst debugFileHandling = false;\nlet loadingCallback = null;\nlet sceneLoadingCallback = null;\n\nfunction setLoadingCallback(cb)\n{\n loadingCallback = cb;\n}\n\nfunction setSceneLoadingCallback(cb)\n{\n sceneLoadingCallback = cb;\n}\n\nfunction dropHandler(ev)\n{\n if (debugFileHandling) console.log('File(s) dropped', ev.dataTransfer.items, ev.dataTransfer.files);\n\n // Prevent default behavior (Prevent file from being opened)\n ev.preventDefault();\n\n if (ev.dataTransfer.items)\n {\n const allEntries = [];\n\n let haveGetAsEntry = false;\n if (ev.dataTransfer.items.length > 0)\n haveGetAsEntry =\n (\"getAsEntry\" in ev.dataTransfer.items[0]) ||\n (\"webkitGetAsEntry\" in ev.dataTransfer.items[0]);\n\n // Useful for debugging file handling on platforms that don't support newer file system APIs\n // haveGetAsEntry = false;\n\n if (haveGetAsEntry)\n {\n for (var i = 0; i < ev.dataTransfer.items.length; i++)\n {\n let item = ev.dataTransfer.items[i];\n let entry = (\"getAsEntry\" in item) ? item.getAsEntry() : item.webkitGetAsEntry();\n allEntries.push(entry);\n }\n handleFilesystemEntries(allEntries);\n return;\n }\n\n for (var i = 0; i < ev.dataTransfer.items.length; i++)\n {\n let item = ev.dataTransfer.items[i];\n\n // API when there's no \"getAsEntry\" support\n console.log(item.kind, item);\n if (item.kind === 'file')\n {\n var file = item.getAsFile();\n testAndLoadFile(file);\n }\n // could also be a directory\n else if (item.kind === 'directory')\n {\n var dirReader = item.createReader();\n dirReader.readEntries(function (entries)\n {\n for (var i = 0; i < entries.length; i++)\n {\n console.log(entries[i].name);\n var entry = entries[i];\n if (entry.isFile)\n {\n entry.file(function (file)\n {\n testAndLoadFile(file);\n });\n }\n }\n });\n }\n }\n } else\n {\n for (var i = 0; i < ev.dataTransfer.files.length; i++)\n {\n let file = ev.dataTransfer.files[i];\n testAndLoadFile(file);\n }\n }\n}\n\nfunction dragOverHandler(ev)\n{\n ev.preventDefault();\n}\n\nasync function getBufferFromFile(fileEntry)\n{\n\n if (fileEntry instanceof ArrayBuffer) return fileEntry;\n if (fileEntry instanceof String) return fileEntry;\n\n const name = fileEntry.fullPath || fileEntry.name;\n const ext = name.split('.').pop();\n const readAsText = ext === 'mtlx';\n\n if (debugFileHandling) console.log(\"reading \", fileEntry, \"as text?\", readAsText);\n\n if (debugFileHandling) console.log(\"getBufferFromFile\", fileEntry);\n const buffer = await new Promise((resolve, reject) =>\n {\n function readFile(file)\n {\n var reader = new FileReader();\n reader.onloadend = function (e)\n {\n if (debugFileHandling) console.log(\"loaded\", \"should be text?\", readAsText, this.result);\n resolve(this.result);\n };\n\n if (readAsText)\n reader.readAsText(file);\n else\n reader.readAsArrayBuffer(file);\n }\n\n if (\"file\" in fileEntry)\n {\n fileEntry.file(function (file)\n {\n readFile(file);\n }, (e) =>\n {\n console.error(\"Error reading file \", e);\n });\n }\n else\n {\n readFile(fileEntry);\n }\n });\n return buffer;\n}\n\nasync function handleFilesystemEntries(entries)\n{\n const allFiles = [];\n const fileIgnoreList = [\n '.gitignore',\n 'README.md',\n '.DS_Store',\n ]\n const dirIgnoreList = [\n '.git',\n 'node_modules',\n ]\n\n let isGLB = false;\n let haveMtlx = false;\n for (let entry of entries)\n {\n if (debugFileHandling) console.log(\"file entry\", entry)\n if (entry.isFile)\n {\n if (debugFileHandling)\n console.log(\"single file\", entry);\n if (fileIgnoreList.includes(entry.name))\n {\n continue;\n }\n allFiles.push(entry);\n\n if (entry.name.endsWith('glb'))\n {\n isGLB = true;\n break;\n }\n }\n else if (entry.isDirectory)\n {\n if (dirIgnoreList.includes(entry.name))\n {\n continue;\n }\n const files = await readDirectory(entry);\n if (debugFileHandling) console.log(\"all files\", files);\n for (const file of files)\n {\n if (fileIgnoreList.includes(file.name))\n {\n continue;\n }\n allFiles.push(file);\n }\n }\n }\n\n const imageLoader = new three__WEBPACK_IMPORTED_MODULE_0__.ImageLoader();\n\n // unpack zip files first\n for (const fileEntry of allFiles)\n {\n // special case: zip archives\n if (fileEntry.fullPath.toLowerCase().endsWith('.zip'))\n {\n await new Promise(async (resolve, reject) =>\n {\n const arrayBuffer = await getBufferFromFile(fileEntry);\n\n // use fflate to unpack them and add the files to the cache\n three_examples_jsm_libs_fflate_module_js__WEBPACK_IMPORTED_MODULE_1__.unzip(new Uint8Array(arrayBuffer), (error, unzipped) =>\n {\n // push these files into allFiles\n for (const [filePath, buffer] of Object.entries(unzipped))\n {\n\n // mock FileEntry for easier usage downstream\n const blob = new Blob([buffer]);\n const newFileEntry = {\n fullPath: \"/\" + filePath,\n name: filePath.split('/').pop(),\n file: (callback) =>\n {\n callback(blob);\n },\n isFile: true,\n };\n allFiles.push(newFileEntry);\n }\n\n resolve();\n });\n });\n }\n }\n\n // sort so mtlx files come first\n allFiles.sort((a, b) =>\n {\n if (a.name.endsWith('.mtlx') && !b.name.endsWith('.mtlx'))\n {\n return -1;\n }\n if (!a.name.endsWith('.mtlx') && b.name.endsWith('.mtlx'))\n {\n return 1;\n }\n return 0;\n });\n\n if (isGLB)\n {\n console.log(\"Load GLB file\", allFiles[0]);\n\n const rootFile = allFiles[0];\n three__WEBPACK_IMPORTED_MODULE_0__.Cache.add(rootFile.fullPath, await getBufferFromFile(rootFile));\n\n if (debugFileHandling) console.log(\"CACHE\", three__WEBPACK_IMPORTED_MODULE_0__.Cache.files);\n\n sceneLoadingCallback(rootFile);\n return;\n }\n\n if (!allFiles[0].name.endsWith('mtlx'))\n {\n console.log(\"No MaterialX files dropped. Skipping content.\");\n return;\n }\n\n if (debugFileHandling)\n {\n console.log(\"- All files\", allFiles);\n }\n\n // put all files in three' Cache\n for (const fileEntry of allFiles)\n {\n\n const allowedFileTypes = [\n 'png', 'jpg', 'jpeg'\n ];\n\n const ext = fileEntry.fullPath.split('.').pop();\n if (!allowedFileTypes.includes(ext))\n {\n // console.log(\"skipping file\", fileEntry.fullPath);\n continue;\n }\n\n const buffer = await getBufferFromFile(fileEntry);\n const img = await imageLoader.loadAsync(URL.createObjectURL(new Blob([buffer])));\n if (debugFileHandling) console.log(\"caching file\", fileEntry.fullPath, img);\n three__WEBPACK_IMPORTED_MODULE_0__.Cache.add(fileEntry.fullPath, img);\n }\n\n // TODO we could also allow dropping of multiple MaterialX files (or folders with them inside) \n // and seed the dropdown from that.\n // At that point, actually reading files and textures into memory should be deferred until they are actually used.\n if (allFiles.length > 0)\n {\n const rootFile = allFiles[0];\n three__WEBPACK_IMPORTED_MODULE_0__.Cache.add(rootFile.fullPath, await getBufferFromFile(rootFile));\n\n if (debugFileHandling) console.log(\"CACHE\", three__WEBPACK_IMPORTED_MODULE_0__.Cache.files);\n\n loadingCallback(rootFile);\n }\n else\n {\n console.log('No files to add cache.')\n }\n}\n\nasync function readDirectory(directory)\n{\n let entries = [];\n let getEntries = async (directory) =>\n {\n let dirReader = directory.createReader();\n await new Promise((resolve, reject) =>\n {\n dirReader.readEntries(\n async (results) =>\n {\n if (results.length)\n {\n // entries = entries.concat(results);\n for (let entry of results)\n {\n if (entry.isDirectory)\n {\n await getEntries(entry);\n }\n else\n {\n entries.push(entry);\n }\n }\n }\n resolve();\n },\n (error) =>\n {\n /* handle error — error is a FileError object */\n },\n )\n }\n )\n };\n\n await getEntries(directory);\n return entries;\n}\n\nasync function testAndLoadFile(file)\n{\n let ext = file.name.split('.').pop();\n if (debugFileHandling) console.log(file.name + \", \" + file.size + \", \" + ext);\n\n const arrayBuffer = await getBufferFromFile(file);\n console.log(arrayBuffer)\n\n // mock a fileEntry and pass through the same loading logic\n const newFileEntry = {\n fullPath: \"/\" + file.name,\n name: file.name.split('/').pop(),\n isFile: true,\n file: (callback) =>\n {\n callback(file);\n }\n };\n\n handleFilesystemEntries([newFileEntry]);\n}\n\n//# sourceURL=webpack://MaterialXView/./source/dropHandling.js?"); + +/***/ }), + +/***/ "./source/helper.js": +/*!**************************!*\ + !*** ./source/helper.js ***! + \**************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ findLights: () => (/* binding */ findLights),\n/* harmony export */ getLightRotation: () => (/* binding */ getLightRotation),\n/* harmony export */ getUniformValues: () => (/* binding */ getUniformValues),\n/* harmony export */ prepareEnvTexture: () => (/* binding */ prepareEnvTexture),\n/* harmony export */ registerLights: () => (/* binding */ registerLights)\n/* harmony export */ });\n/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! three */ \"./node_modules/three/build/three.module.js\");\n//\n// Copyright Contributors to the MaterialX Project\n// SPDX-License-Identifier: Apache-2.0\n//\n\n\n\nconst IMAGE_PROPERTY_SEPARATOR = \"_\";\nconst UADDRESS_MODE_SUFFIX = IMAGE_PROPERTY_SEPARATOR + \"uaddressmode\";\nconst VADDRESS_MODE_SUFFIX = IMAGE_PROPERTY_SEPARATOR + \"vaddressmode\";\nconst FILTER_TYPE_SUFFIX = IMAGE_PROPERTY_SEPARATOR + \"filtertype\";\nconst IMAGE_PATH_SEPARATOR = \"/\";\n\n/**\n * Initialized the environment texture as MaterialX expects it\n * @param {THREE.Texture} texture\n * @param {Object} capabilities\n * @returns {THREE.Texture}\n */\nfunction prepareEnvTexture(texture, capabilities)\n{\n let newTexture = new three__WEBPACK_IMPORTED_MODULE_0__.DataTexture(texture.image.data, texture.image.width, texture.image.height, texture.format, texture.type);\n newTexture.wrapS = three__WEBPACK_IMPORTED_MODULE_0__.RepeatWrapping;\n newTexture.anisotropy = capabilities.getMaxAnisotropy();\n newTexture.minFilter = three__WEBPACK_IMPORTED_MODULE_0__.LinearMipmapLinearFilter;\n newTexture.magFilter = three__WEBPACK_IMPORTED_MODULE_0__.LinearFilter;\n newTexture.generateMipmaps = true;\n newTexture.needsUpdate = true;\n\n return newTexture;\n}\n\n/**\n * Get Three uniform from MaterialX vector\n * @param {any} value\n * @param {any} dimension\n * @returns {THREE.Uniform}\n */\nfunction fromVector(value, dimension)\n{\n let outValue;\n if (value)\n {\n outValue = value.data();\n }\n else\n {\n outValue = [];\n for (let i = 0; i < dimension; ++i)\n outValue.push(0.0);\n }\n\n return outValue;\n}\n\n/**\n * Get Three uniform from MaterialX matrix\n * @param {mx.matrix} matrix\n * @param {mx.matrix.size} dimension\n */\nfunction fromMatrix(matrix, dimension)\n{\n let vec = [];\n if (matrix)\n {\n for (let i = 0; i < matrix.numRows(); ++i)\n {\n for (let k = 0; k < matrix.numColumns(); ++k)\n {\n vec.push(matrix.getItem(i, k));\n }\n }\n } else\n {\n for (let i = 0; i < dimension; ++i)\n vec.push(0.0);\n }\n\n return vec;\n}\n\n/**\n * Get Three uniform from MaterialX value\n * @param {mx.Uniform.type} type\n * @param {mx.Uniform.value} value\n * @param {mx.Uniform.name} name\n * @param {mx.Uniforms} uniforms\n * @param {THREE.textureLoader} textureLoader\n */\nfunction toThreeUniform(type, value, name, uniforms, textureLoader, searchPath, flipY)\n{\n let outValue = null;\n switch (type)\n {\n case 'float':\n case 'integer':\n case 'boolean':\n outValue = value;\n break;\n case 'vector2':\n outValue = fromVector(value, 2);\n break;\n case 'vector3':\n case 'color3':\n outValue = fromVector(value, 3);\n break;\n case 'vector4':\n case 'color4':\n outValue = fromVector(value, 4);\n break;\n case 'matrix33':\n outValue = fromMatrix(value, 9);\n break;\n case 'matrix44':\n outValue = fromMatrix(value, 16);\n break;\n case 'filename':\n if (value)\n {\n // Cache / reuse texture to avoid reload overhead.\n // Note: that data blobs and embedded data textures are not cached as they are transient data.\n let checkCache = true;\n let texturePath = searchPath + IMAGE_PATH_SEPARATOR + value;\n if (value.startsWith('blob:')) \n {\n texturePath = value;\n console.log('Load blob URL:', texturePath);\n checkCache = false;\n }\n else if (value.startsWith('http'))\n {\n texturePath = value;\n console.log('Load HTTP URL:', texturePath);\n }\n else if (value.startsWith('data:'))\n {\n texturePath = value;\n checkCache = false;\n console.log('Load data URL:', texturePath);\n }\n const cachedTexture = checkCache && three__WEBPACK_IMPORTED_MODULE_0__.Cache.get(texturePath);\n if (cachedTexture)\n {\n // Get texture from cache\n outValue = cachedTexture;\n console.log('Use cached texture: ', texturePath, outValue);\n }\n else\n {\n outValue = textureLoader.load(\n texturePath, \n function (texture) {\n console.log('Load new texture: ' + texturePath, texture);\n outValue = texture;\n\n // Add texture to ThreeJS cache\n if (checkCache)\n three__WEBPACK_IMPORTED_MODULE_0__.Cache.add(texturePath, texture);\n },\n undefined,\n function (error) {\n console.error('Error loading texture: ', error);\n }); \n\n // Set address & filtering mode\n if (outValue)\n setTextureParameters(outValue, name, uniforms, flipY);\n }\n }\n break;\n case 'samplerCube':\n case 'string':\n break;\n default:\n console.log('Value type not supported: ' + type);\n outValue = null;\n }\n\n return outValue;\n}\n\n/**\n * Get Three wrapping mode\n * @param {mx.TextureFilter.wrap} mode\n * @returns {THREE.Wrapping}\n */\nfunction getWrapping(mode)\n{\n let wrap;\n switch (mode)\n {\n case 1:\n wrap = three__WEBPACK_IMPORTED_MODULE_0__.ClampToEdgeWrapping;\n break;\n case 2:\n wrap = three__WEBPACK_IMPORTED_MODULE_0__.RepeatWrapping;\n break;\n case 3:\n wrap = three__WEBPACK_IMPORTED_MODULE_0__.MirroredRepeatWrapping;\n break;\n default:\n wrap = three__WEBPACK_IMPORTED_MODULE_0__.RepeatWrapping;\n break;\n }\n return wrap;\n}\n\n/**\n * Get Three minification filter\n * @param {mx.TextureFilter.minFilter} type\n * @param {mx.TextureFilter.generateMipmaps} generateMipmaps\n */\nfunction getMinFilter(type, generateMipmaps)\n{\n const filterType = generateMipmaps ? three__WEBPACK_IMPORTED_MODULE_0__.LinearMipMapLinearFilter : three__WEBPACK_IMPORTED_MODULE_0__.LinearFilter;\n if (type === 0)\n {\n filterType = generateMipmaps ? three__WEBPACK_IMPORTED_MODULE_0__.NearestMipMapNearestFilter : three__WEBPACK_IMPORTED_MODULE_0__.NearestFilter;\n }\n return filterType;\n}\n\n/**\n * Set Three texture parameters\n * @param {THREE.Texture} texture\n * @param {mx.Uniform.name} name\n * @param {mx.Uniforms} uniforms\n * @param {mx.TextureFilter.generateMipmaps} generateMipmaps\n */\nfunction setTextureParameters(texture, name, uniforms, flipY = true, generateMipmaps = true)\n{\n const idx = name.lastIndexOf(IMAGE_PROPERTY_SEPARATOR);\n const base = name.substring(0, idx) || name;\n\n texture.generateMipmaps = generateMipmaps;\n texture.wrapS = three__WEBPACK_IMPORTED_MODULE_0__.RepeatWrapping;\n texture.wrapT = three__WEBPACK_IMPORTED_MODULE_0__.RepeatWrapping;\n texture.magFilter = three__WEBPACK_IMPORTED_MODULE_0__.LinearFilter;\n texture.flipY = flipY;\n\n if (uniforms.find(base + UADDRESS_MODE_SUFFIX))\n {\n const uaddressmode = uniforms.find(base + UADDRESS_MODE_SUFFIX).getValue().getData();\n texture.wrapS = getWrapping(uaddressmode);\n }\n\n if (uniforms.find(base + VADDRESS_MODE_SUFFIX))\n {\n const vaddressmode = uniforms.find(base + VADDRESS_MODE_SUFFIX).getValue().getData();\n texture.wrapT = getWrapping(vaddressmode);\n }\n\n const filterType = uniforms.find(base + FILTER_TYPE_SUFFIX) ? uniforms.get(base + FILTER_TYPE_SUFFIX).value : -1;\n texture.minFilter = getMinFilter(filterType, generateMipmaps);\n}\n\n/**\n * Return the global light rotation matrix\n */\nfunction getLightRotation()\n{\n return new three__WEBPACK_IMPORTED_MODULE_0__.Matrix4().makeRotationY(Math.PI / 2);\n}\n\n/**\n * Returns all lights nodes in a MaterialX document\n * @param {mx.Document} doc \n * @returns {Array.}\n */\nfunction findLights(doc)\n{\n let lights = [];\n for (let node of doc.getNodes())\n {\n if (node.getType() === \"lightshader\")\n lights.push(node);\n }\n return lights;\n}\n\n/**\n * Register lights in shader generation context\n * @param {Object} mx MaterialX Module\n * @param {Array.} lights Light nodes\n * @param {mx.GenContext} genContext Shader generation context\n * @returns {Array.}\n */\nfunction registerLights(mx, lights, genContext)\n{\n mx.HwShaderGenerator.unbindLightShaders(genContext);\n\n const lightTypesBound = {};\n const lightData = [];\n let lightId = 1;\n for (let light of lights)\n {\n let nodeDef = light.getNodeDef();\n let nodeName = nodeDef.getName();\n if (!lightTypesBound[nodeName])\n {\n lightTypesBound[nodeName] = lightId;\n mx.HwShaderGenerator.bindLightShader(nodeDef, lightId++, genContext);\n }\n\n const lightDirection = light.getValueElement(\"direction\").getValue().getData().data();\n const lightColor = light.getValueElement(\"color\").getValue().getData().data();\n const lightIntensity = light.getValueElement(\"intensity\").getValue().getData();\n\n let rotatedLightDirection = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3(...lightDirection)\n rotatedLightDirection.transformDirection(getLightRotation())\n\n lightData.push({\n type: lightTypesBound[nodeName],\n direction: rotatedLightDirection,\n color: new three__WEBPACK_IMPORTED_MODULE_0__.Vector3(...lightColor),\n intensity: lightIntensity\n });\n }\n\n // Make sure max light count is large enough\n genContext.getOptions().hwMaxActiveLightSources = Math.max(genContext.getOptions().hwMaxActiveLightSources, lights.length);\n\n return lightData;\n}\n\n/**\n * Get uniform values for a shader\n * @param {mx.shaderStage} shaderStage\n * @param {THREE.TextureLoader} textureLoader\n */\nfunction getUniformValues(shaderStage, textureLoader, searchPath, flipY)\n{\n let threeUniforms = {};\n\n const uniformBlocks = Object.values(shaderStage.getUniformBlocks());\n uniformBlocks.forEach(uniforms =>\n {\n if (!uniforms.empty())\n {\n for (let i = 0; i < uniforms.size(); ++i)\n {\n const variable = uniforms.get(i);\n const value = variable.getValue()?.getData();\n const name = variable.getVariable();\n threeUniforms[name] = new three__WEBPACK_IMPORTED_MODULE_0__.Uniform(toThreeUniform(variable.getType().getName(), value, name, uniforms,\n textureLoader, searchPath, flipY));\n }\n }\n });\n\n return threeUniforms;\n}\n\n\n//# sourceURL=webpack://MaterialXView/./source/helper.js?"); + +/***/ }), + +/***/ "./source/index.js": +/*!*************************!*\ + !*** ./source/index.js ***! + \*************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! three */ \"./node_modules/three/build/three.module.js\");\n/* harmony import */ var _viewer_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./viewer.js */ \"./source/viewer.js\");\n/* harmony import */ var three_examples_jsm_controls_OrbitControls_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! three/examples/jsm/controls/OrbitControls.js */ \"./node_modules/three/examples/jsm/controls/OrbitControls.js\");\n/* harmony import */ var _dropHandling_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dropHandling.js */ \"./source/dropHandling.js\");\n//\n// Copyright Contributors to the MaterialX Project\n// SPDX-License-Identifier: Apache-2.0\n//\n\n\n\n\n\n\nlet renderer, orbitControls;\n\n// Turntable option. For now the step size is fixed.\nlet turntableEnabled = false;\nlet turntableSteps = 360;\nlet turntableStep = 0;\n\nlet captureRequested = false;\n\n// Get URL options. Fallback to defaults if not specified.\nlet materialFilename = new URLSearchParams(document.location.search).get(\"file\");\nif (!materialFilename)\n{\n materialFilename = 'Materials/Examples/StandardSurface/standard_surface_default.mtlx';\n}\n\nlet viewer = _viewer_js__WEBPACK_IMPORTED_MODULE_0__.Viewer.create();\ninit();\nviewer.getEditor().updateProperties(0.9);\n\n// Capture the current frame and save an image file.\nfunction captureFrame()\n{\n let canvas = document.getElementById('webglcanvas');\n var url = canvas.toDataURL();\n var link = document.createElement('a');\n link.setAttribute('href', url);\n link.setAttribute('target', '_blank');\n link.setAttribute('download', 'screenshot.png');\n link.click();\n}\n\nfunction init()\n{\n let canvas = document.getElementById('webglcanvas');\n\n // Handle material selection changes\n let materialsSelect = document.getElementById('materials');\n materialsSelect.value = materialFilename;\n materialsSelect.addEventListener('change', (e) =>\n {\n materialFilename = e.target.value;\n viewer.getEditor().initialize();\n viewer.getMaterial().loadMaterials(viewer, materialFilename);\n viewer.getEditor().updateProperties(0.9);\n viewer.getScene().setUpdateTransforms();\n });\n\n // Handle geometry selection changes\n const scene = viewer.getScene();\n let geometrySelect = document.getElementById('geometry');\n geometrySelect.value = scene.getGeometryURL();\n geometrySelect.addEventListener('change', (e) =>\n {\n console.log('Change geometry to:', e.target.value);\n scene.setGeometryURL(e.target.value);\n scene.loadGeometry(viewer, orbitControls);\n });\n\n // Set up scene\n scene.initialize();\n\n // Set up renderer\n renderer = new three__WEBPACK_IMPORTED_MODULE_2__.WebGLRenderer({ antialias: true, canvas });\n renderer.setSize(window.innerWidth, window.innerHeight);\n renderer.debug.checkShaderErrors = false;\n\n window.addEventListener('resize', onWindowResize);\n\n // Set up controls\n orbitControls = new three_examples_jsm_controls_OrbitControls_js__WEBPACK_IMPORTED_MODULE_3__.OrbitControls(scene.getCamera(), renderer.domElement);\n orbitControls.addEventListener('change', () =>\n {\n viewer.getScene().setUpdateTransforms();\n })\n\n // Add hotkey 'f' to capture the current frame and save an image file.\n // See check inside the render loop when a capture can be performed.\n document.addEventListener('keydown', (event) =>\n {\n if (event.key === 'f')\n {\n captureRequested = true;\n }\n });\n\n // Initialize editor\n viewer.getEditor().initialize();\n\n const hdrLoader = viewer.getHdrLoader();\n const fileLoader = viewer.getFileLoader();\n Promise.all([\n new Promise(resolve => hdrLoader.load('Lights/san_giuseppe_bridge_split.hdr', resolve)),\n new Promise(resolve => hdrLoader.load('Lights/irradiance/san_giuseppe_bridge_split.hdr', resolve)),\n new Promise(resolve => fileLoader.load('Lights/san_giuseppe_bridge_split.mtlx', resolve)),\n new Promise(function (resolve)\n {\n MaterialX().then((module) =>\n {\n resolve(module);\n });\n })\n ]).then(async ([radianceTexture, irradianceTexture, lightRigXml, mxIn]) =>\n {\n // Initialize viewer + lighting\n await viewer.initialize(mxIn, renderer, radianceTexture, irradianceTexture, lightRigXml);\n\n // Load geometry \n let scene = viewer.getScene();\n scene.loadGeometry(viewer, orbitControls);\n\n // Load materials\n viewer.getMaterial().loadMaterials(viewer, materialFilename);\n\n // Update assignments\n viewer.getMaterial().updateMaterialAssignments(viewer);\n\n canvas.addEventListener(\"keydown\", handleKeyEvents, true);\n\n }).then(() =>\n {\n animate();\n }).catch(err =>\n {\n console.error(Number.isInteger(err) ? this.getMx().getExceptionMessage(err) : err);\n })\n\n // allow dropping files and directories\n document.addEventListener('drop', _dropHandling_js__WEBPACK_IMPORTED_MODULE_1__.dropHandler, false);\n document.addEventListener('dragover', _dropHandling_js__WEBPACK_IMPORTED_MODULE_1__.dragOverHandler, false);\n\n (0,_dropHandling_js__WEBPACK_IMPORTED_MODULE_1__.setLoadingCallback)(file =>\n {\n materialFilename = file.fullPath || file.name;\n viewer.getEditor().initialize();\n viewer.getMaterial().loadMaterials(viewer, materialFilename);\n viewer.getEditor().updateProperties(0.9);\n viewer.getScene().setUpdateTransforms();\n });\n\n (0,_dropHandling_js__WEBPACK_IMPORTED_MODULE_1__.setSceneLoadingCallback)(file =>\n {\n let glbFileName = file.fullPath || file.name;\n console.log('Drop geometry to:', glbFileName);\n scene.setGeometryURL(glbFileName);\n scene.loadGeometry(viewer, orbitControls);\n });\n\n // enable three.js Cache so that dropped files can reference each other\n three__WEBPACK_IMPORTED_MODULE_2__.Cache.enabled = true;\n}\n\nfunction onWindowResize()\n{\n viewer.getScene().updateCamera();\n viewer.getScene().setUpdateTransforms();\n renderer.setSize(window.innerWidth, window.innerHeight);\n}\n\nfunction animate()\n{\n requestAnimationFrame(animate);\n\n if (turntableEnabled)\n {\n turntableStep = (turntableStep + 1) % 360;\n var turntableAngle = turntableStep * (360.0 / turntableSteps) / 180.0 * Math.PI;\n viewer.getScene()._scene.rotation.y = turntableAngle;\n viewer.getScene().setUpdateTransforms();\n }\n\n renderer.render(viewer.getScene().getScene(), viewer.getScene().getCamera());\n viewer.getScene().updateTransforms();\n\n if (captureRequested)\n {\n captureFrame();\n captureRequested = false;\n }\n}\n\nfunction handleKeyEvents(event)\n{\n const V_KEY = 86;\n const P_KEY = 80;\n\n if (event.keyCode == V_KEY)\n {\n viewer.getScene().toggleBackgroundTexture();\n }\n else if (event.keyCode == P_KEY)\n {\n turntableEnabled = !turntableEnabled;\n }\n}\n\n\n//# sourceURL=webpack://MaterialXView/./source/index.js?"); + +/***/ }), + +/***/ "./source/viewer.js": +/*!**************************!*\ + !*** ./source/viewer.js ***! + \**************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Editor: () => (/* binding */ Editor),\n/* harmony export */ Material: () => (/* binding */ Material),\n/* harmony export */ Scene: () => (/* binding */ Scene),\n/* harmony export */ Viewer: () => (/* binding */ Viewer)\n/* harmony export */ });\n/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ \"./node_modules/three/build/three.module.js\");\n/* harmony import */ var three_examples_jsm_loaders_GLTFLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! three/examples/jsm/loaders/GLTFLoader */ \"./node_modules/three/examples/jsm/loaders/GLTFLoader.js\");\n/* harmony import */ var three_examples_jsm_loaders_RGBELoader_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! three/examples/jsm/loaders/RGBELoader.js */ \"./node_modules/three/examples/jsm/loaders/RGBELoader.js\");\n/* harmony import */ var _helper_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./helper.js */ \"./source/helper.js\");\n/* harmony import */ var lil_gui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lil-gui */ \"./node_modules/lil-gui/dist/lil-gui.esm.js\");\n//\n// Copyright Contributors to the MaterialX Project\n// SPDX-License-Identifier: Apache-2.0\n//\n\n\n\n\n\n\n\n\n\nconst ALL_GEOMETRY_SPECIFIER = \"*\";\nconst NO_GEOMETRY_SPECIFIER = \"\";\nconst DAG_PATH_SEPERATOR = \"/\";\n\n// Logging toggle\nvar logDetailedTime = false;\n\n/*\n Scene management\n*/\nclass Scene\n{\n constructor()\n {\n this._geometryURL = new URLSearchParams(document.location.search).get(\"geom\");\n if (!this._geometryURL)\n {\n this._geometryURL = 'Geometry/shaderball.glb';\n }\n }\n\n initialize()\n {\n this._scene = new three__WEBPACK_IMPORTED_MODULE_1__.Scene();\n this._scene.background = new three__WEBPACK_IMPORTED_MODULE_1__.Color(this.#_backgroundColor);\n this._scene.background.convertSRGBToLinear();\n\n const aspectRatio = window.innerWidth / window.innerHeight;\n const cameraNearDist = 0.05;\n const cameraFarDist = 100.0;\n const cameraFOV = 60.0;\n this._camera = new three__WEBPACK_IMPORTED_MODULE_1__.PerspectiveCamera(cameraFOV, aspectRatio, cameraNearDist, cameraFarDist);\n\n this.#_gltfLoader = new three_examples_jsm_loaders_GLTFLoader__WEBPACK_IMPORTED_MODULE_2__.GLTFLoader();\n\n this.#_normalMat = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix3();\n this.#_viewProjMat = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();\n this.#_worldViewPos = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();\n }\n\n // Set whether to flip UVs in V for loaded geometry\n setFlipGeometryV(val)\n {\n this.#_flipV = val;\n }\n\n // Get whether to flip UVs in V for loaded geometry\n getFlipGeometryV()\n {\n return this.#_flipV;\n }\n\n // Utility to perform geometry file load\n loadGeometryFile(geometryFilename, loader)\n {\n return new Promise((resolve, reject) =>\n {\n loader.load(geometryFilename, data => resolve(data), null, reject);\n });\n }\n\n //\n // Load in geometry specified by a given file name,\n // then update the scene geometry and camera.\n //\n async loadGeometry(viewer, orbitControls)\n {\n var startTime = performance.now();\n var geomLoadTime = startTime;\n\n const gltfData = await this.loadGeometryFile(this.getGeometryURL(), this.#_gltfLoader);\n\n const scene = this.getScene();\n while (scene.children.length > 0)\n {\n scene.remove(scene.children[0]);\n }\n\n this.#_rootNode = null;\n const model = gltfData.scene;\n if (!model)\n {\n const geometry = new three__WEBPACK_IMPORTED_MODULE_1__.BoxGeometry(1, 1, 1);\n const material = new three__WEBPACK_IMPORTED_MODULE_1__.MeshBasicMaterial({ color: 0xdddddd });\n const cube = new three__WEBPACK_IMPORTED_MODULE_1__.Mesh(geometry, material);\n obj = new three__WEBPACK_IMPORTED_MODULE_1__.Group();\n obj.add(geometry);\n }\n else\n {\n this.#_rootNode = model;\n }\n scene.add(model);\n\n console.log(\"- Scene load time: \", performance.now() - geomLoadTime, \"ms\");\n\n // Always reset controls based on camera for each load. \n orbitControls.reset();\n this.updateScene(viewer, orbitControls);\n\n console.log(\"Total geometry load time: \", performance.now() - startTime, \" ms.\");\n\n viewer.getMaterial().clearSoloMaterialUI();\n viewer.getMaterial().updateMaterialAssignments(viewer, \"\");\n this.setUpdateTransforms();\n }\n\n //\n // Update the geometry buffer, assigned materials, and camera controls.\n //\n updateScene(viewer, orbitControls)\n {\n var startUpdateSceneTime = performance.now();\n var uvTime = 0;\n var normalTime = 0;\n var tangentTime = 0;\n var streamTime = 0;\n var bboxTime = 0;\n\n var startBboxTime = performance.now();\n const bbox = new three__WEBPACK_IMPORTED_MODULE_1__.Box3().setFromObject(this._scene);\n const bsphere = new three__WEBPACK_IMPORTED_MODULE_1__.Sphere();\n bbox.getBoundingSphere(bsphere);\n bboxTime = performance.now() - startBboxTime;\n\n let theScene = viewer.getScene();\n let flipV = theScene.getFlipGeometryV();\n\n\n this._scene.traverse((child) =>\n {\n if (child.isMesh)\n {\n var startUVTime = performance.now();\n if (!child.geometry.attributes.uv)\n {\n const posCount = child.geometry.attributes.position.count;\n const uvs = [];\n const pos = child.geometry.attributes.position.array;\n\n for (let i = 0; i < posCount; i++)\n {\n uvs.push((pos[i * 3] - bsphere.center.x) / bsphere.radius);\n uvs.push((pos[i * 3 + 1] - bsphere.center.y) / bsphere.radius);\n }\n\n child.geometry.setAttribute('uv', new three__WEBPACK_IMPORTED_MODULE_1__.BufferAttribute(new Float32Array(uvs), 2));\n }\n else if (flipV)\n {\n const uvCount = child.geometry.attributes.position.count;\n const uvs = child.geometry.attributes.uv.array;\n for (let i = 0; i < uvCount; i++)\n {\n let v = 1.0 - (uvs[i * 2 + 1]);\n uvs[i * 2 + 1] = v;\n }\n }\n uvTime += performance.now() - startUVTime;\n\n if (!child.geometry.attributes.normal)\n {\n var startNormalTime = performance.new();\n child.geometry.computeVertexNormals();\n normalTime += performance.now() - startNormalTime;\n }\n\n if (child.geometry.getIndex())\n {\n if (!child.geometry.attributes.tangent)\n {\n var startTangentTime = performance.now();\n child.geometry.computeTangents();\n tangentTime += performance.now() - startTangentTime;\n }\n }\n\n // Use default MaterialX naming convention.\n var startStreamTime = performance.now();\n child.geometry.attributes.i_position = child.geometry.attributes.position;\n child.geometry.attributes.i_normal = child.geometry.attributes.normal;\n child.geometry.attributes.i_tangent = child.geometry.attributes.tangent;\n child.geometry.attributes.i_texcoord_0 = child.geometry.attributes.uv;\n streamTime += performance.now() - startStreamTime;\n }\n });\n\n console.log(\"- Stream update time: \", performance.now() - startUpdateSceneTime, \"ms\");\n if (logDetailedTime)\n {\n console.log(' - UV time: ', uvTime);\n console.log(' - Normal time: ', normalTime);\n console.log(' - Tangent time: ', tangentTime);\n console.log(' - Stream Update time: ', streamTime);\n console.log(' - Bounds compute time: ', bboxTime);\n }\n\n // Update the background\n this._scene.background = this.getBackground();\n\n // Fit camera to model\n const camera = this.getCamera();\n camera.position.y = bsphere.center.y;\n camera.position.z = bsphere.radius * 2.0;\n camera.updateProjectionMatrix();\n\n orbitControls.target = bsphere.center;\n orbitControls.update();\n }\n\n setUpdateTransforms(val=true)\n {\n this.#_updateTransforms = val;\n }\n\n getUpdateTransforms()\n {\n return this.#_updateTransforms;\n }\n\n updateTransforms()\n {\n // Only update on demand versus continuously.\n // Call setUpdateTransforms() to trigger an update here.\n // Required for: scene geometry, camera change and viewport resize. \n if (!this.#_updateTransforms)\n {\n return;\n }\n this.setUpdateTransforms(false);\n\n const scene = this.getScene();\n const camera = this.getCamera();\n scene.traverse((child) =>\n {\n if (child.isMesh)\n {\n const uniforms = child.material.uniforms;\n if (uniforms)\n {\n uniforms.u_worldMatrix.value = child.matrixWorld;\n uniforms.u_viewProjectionMatrix.value = this.#_viewProjMat.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);\n\n if (uniforms.u_viewPosition)\n uniforms.u_viewPosition.value = camera.getWorldPosition(this.#_worldViewPos);\n\n if (uniforms.u_worldInverseTransposeMatrix)\n uniforms.u_worldInverseTransposeMatrix.value =\n new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4().setFromMatrix3(this.#_normalMat.getNormalMatrix(child.matrixWorld));\n }\n }\n });\n }\n\n // Determine string DAG path based on individual node names.\n getDagPath(node)\n {\n const rootNode = this.#_rootNode;\n\n let path = [node.name];\n while (node.parent)\n {\n node = node.parent;\n if (node)\n {\n // Stop at the root of the scene read in.\n if (node == rootNode)\n {\n break;\n }\n path.unshift(node.name);\n }\n }\n return path;\n }\n\n // Assign material shader to associated geometry\n updateMaterial(matassign)\n {\n let assigned = 0;\n\n const shader = matassign.getShader();\n const material = matassign.getMaterial().getName();\n const geometry = matassign.getGeometry();\n const collection = matassign.getCollection();\n\n const scene = this.getScene();\n const camera = this.getCamera();\n scene.traverse((child) =>\n {\n if (child.isMesh)\n {\n const dagPath = this.getDagPath(child).join('/');\n\n // Note that this is a very simplistic\n // assignment resolve and assumes basic\n // regular expression name match.\n let matches = (geometry == ALL_GEOMETRY_SPECIFIER);\n if (!matches)\n {\n if (collection)\n {\n if (collection.matchesGeomString(dagPath))\n {\n matches = true;\n }\n }\n else\n {\n if (geometry != NO_GEOMETRY_SPECIFIER)\n {\n const paths = geometry.split(',');\n for (let path of paths)\n {\n if (dagPath.match(path))\n {\n matches = true;\n break;\n }\n }\n }\n }\n }\n if (matches)\n {\n child.material = shader;\n assigned++;\n }\n }\n });\n\n return assigned;\n }\n\n updateCamera()\n {\n const camera = this.getCamera();\n camera.aspect = window.innerWidth / window.innerHeight;\n camera.updateProjectionMatrix();\n }\n\n getScene()\n {\n return this._scene;\n }\n\n getCamera()\n {\n return this._camera;\n }\n\n getGeometryURL()\n {\n return this._geometryURL;\n }\n\n setGeometryURL(url)\n {\n this._geometryURL = url;\n }\n\n setBackgroundTexture(texture)\n {\n this.#_backgroundTexture = texture;\n }\n\n getShowBackgroundTexture()\n {\n return this.#_showBackgroundTexture;\n }\n\n setShowBackgroundTexture(enable)\n {\n this.#_showBackgroundTexture = enable;\n }\n\n getBackground()\n {\n if (this.#_backgroundTexture && this.#_showBackgroundTexture)\n {\n return this.#_backgroundTexture;\n }\n var color = new three__WEBPACK_IMPORTED_MODULE_1__.Color(this.#_backgroundColor);\n color.convertSRGBToLinear();\n return color;\n }\n\n toggleBackgroundTexture()\n {\n this.#_showBackgroundTexture = !this.#_showBackgroundTexture;\n this._scene.background = this.getBackground();\n }\n\n // Geometry file\n #_geometryURL = '';\n // Geometry loader\n #_gltfLoader = null;\n // Flip V coordinate of texture coordinates.\n // Set to true to be consistent with desktop viewer.\n #_flipV = true;\n\n // Scene\n #_scene = null;\n\n // Camera\n #_camera = null;\n\n // Background color\n #_backgroundColor = 0x4c4c52;\n\n // Background texture\n #_backgroundTexture = null;\n #_showBackgroundTexture = true;\n\n // Transform matrices\n #_normalMat = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix3();\n #_viewProjMat = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();\n #_worldViewPos = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();\n #_updateTransforms = true;\n\n // Root node of imported scene\n #_rootNode = null;\n}\n\n/* \n Property editor\n*/\nclass Editor\n{\n // Initialize the editor, clearing any elements from previous materials.\n initialize()\n {\n Array.from(document.getElementsByClassName('lil-gui')).forEach(\n function (element, index, array)\n {\n if (element.className)\n {\n element.remove();\n }\n }\n );\n\n this._gui = new lil_gui__WEBPACK_IMPORTED_MODULE_3__[\"default\"]({ title: \"Property Editor\" });\n this._gui.close();\n }\n\n // Update ui properties\n // - Hide close button\n // - Update transparency so scene shows through if overlapping\n updateProperties(targetOpacity = 1)\n {\n // Set opacity\n Array.from(document.getElementsByClassName('dg')).forEach(\n function (element, index, array)\n {\n element.style.opacity = targetOpacity;\n }\n );\n }\n\n getGUI()\n {\n return this._gui;\n }\n\n _gui = null;\n}\n\nclass MaterialAssign\n{\n constructor(material, geometry, collection)\n {\n this._material = material;\n this._geometry = geometry;\n this._collection = collection;\n this._shader = null;\n this._materialUI = null;\n }\n\n setMaterialUI(value)\n {\n this._materialUI = value;\n }\n\n getMaterialUI()\n {\n return this._materialUI;\n }\n\n setShader(shader)\n {\n this._shader = shader;\n }\n\n getShader()\n {\n return this._shader;\n }\n\n getMaterial()\n {\n return this._material;\n }\n\n getGeometry()\n {\n return this._geometry;\n }\n\n setGeometry(value)\n {\n this._geometry = value;\n }\n\n getCollection()\n {\n return this._collection;\n }\n\n // MaterialX material node name\n _material;\n\n // MaterialX assignment geometry string\n _geometry;\n\n // MaterialX assignment collection\n _collection;\n\n // THREE.JS shader\n _shader;\n}\n\nclass Material\n{\n constructor()\n {\n this._materials = [];\n this._defaultMaterial = null;\n this._soloMaterial = \"\";\n }\n\n clearMaterials()\n {\n this._materials.length = 0;\n this._defaultMaterial = null;\n this._soloMaterial = \"\";\n }\n\n setSoloMaterial(value)\n {\n this._soloMaterial = value;\n }\n\n getSoloMaterial()\n {\n return this._soloMaterial;\n }\n\n // If no material file is selected, we programmatically create a default material as a fallback\n static createFallbackMaterial(doc)\n {\n let ssNode = doc.getChild('Generated_Default_Shader');\n if (ssNode)\n {\n return ssNode;\n }\n const ssName = 'Generated_Default_Shader';\n ssNode = doc.addChildOfCategory('standard_surface', ssName);\n ssNode.setType('surfaceshader');\n const smNode = doc.addChildOfCategory('surfacematerial', 'Default');\n smNode.setType('material');\n const shaderElement = smNode.addInput('surfaceshader');\n shaderElement.setType('surfaceshader');\n shaderElement.setNodeName(ssName);\n\n return ssNode;\n }\n\n async loadMaterialFile(loader, materialFilename)\n {\n return new Promise((resolve, reject) =>\n {\n loader.load(materialFilename, data => resolve(data), null, reject);\n });\n }\n\n async loadMaterials(viewer, materialFilename)\n {\n var startTime = performance.now();\n\n const mx = viewer.getMx();\n\n // Re-initialize document\n var startDocTime = performance.now();\n var doc = mx.createDocument();\n doc.importLibrary(viewer.getLibrary());\n viewer.setDocument(doc);\n\n const fileloader = viewer.getFileLoader();\n\n let mtlxMaterial = await viewer.getMaterial().loadMaterialFile(fileloader, materialFilename);\n\n // Load lighting setup into document\n doc.importLibrary(viewer.getLightRig());\n\n console.log(\"- Material document load time: \", performance.now() - startDocTime, \"ms.\");\n\n // Set search path. Assumes images are relative to current file\n // location.\n if (!materialFilename) materialFilename = \"/\";\n const paths = materialFilename.split('/');\n paths.pop();\n const searchPath = paths.join('/');\n\n // Load material\n if (mtlxMaterial)\n try { \n await mx.readFromXmlString(doc, mtlxMaterial, searchPath);\n }\n catch (error) {\n console.log('Error loading material file: ', error);\n }\n else\n Material.createFallbackMaterial(doc);\n\n // Check if there are any looks defined in the document\n // If so then traverse the looks for all material assignments.\n // Generate code and compile for any associated surface shader\n // and assign to the associated geometry. If there are no looks\n // then the first material is found and assignment to all the\n // geometry.\n this.clearMaterials();\n var looks = doc.getLooks();\n if (looks.length)\n {\n for (let look of looks)\n {\n const materialAssigns = look.getMaterialAssigns();\n for (let materialAssign of materialAssigns)\n {\n let matName = materialAssign.getMaterial();\n if (matName)\n {\n let mat = doc.getChild(matName);\n var shader;\n if (mat)\n {\n var shaders = mx.getShaderNodes(mat);\n if (shaders.length)\n {\n shader = shaders[0];\n }\n }\n let collection = materialAssign.getCollection();\n let geom = materialAssign.getGeom();\n let newAssignment;\n if (collection || geom)\n {\n // Remove leading \"/\" from collection and geom for \n // later assignment comparison checking\n if (collection && collection.charAt(0) == \"/\")\n {\n collection = collection.slice(1);\n }\n if (geom && geom.charAt(0) == \"/\")\n {\n geom = geom.slice(1);\n }\n newAssignment = new MaterialAssign(shader, geom, collection);\n }\n else\n {\n newAssignment = new MaterialAssign(shader, NO_GEOMETRY_SPECIFIER, null);\n }\n\n if (newAssignment)\n {\n this._materials.push(newAssignment);\n }\n }\n }\n }\n }\n else\n {\n // Search for any surface shaders. The first found\n // is assumed to be assigned to the entire scene\n // The identifier used is \"*\" to mean the entire scene. \n const materialNodes = doc.getMaterialNodes();\n let shaderList = [];\n let foundRenderable = false;\n for (let i = 0; i < materialNodes.length; ++i)\n {\n let materialNode = materialNodes[i];\n if (materialNode)\n {\n console.log('Scan material: ', materialNode.getNamePath());\n let shaderNodes = mx.getShaderNodes(materialNode)\n if (shaderNodes.length > 0)\n {\n let shaderNodePath = shaderNodes[0].getNamePath()\n if (!shaderList.includes(shaderNodePath))\n {\n let assignment = NO_GEOMETRY_SPECIFIER;\n if (foundRenderable == false)\n {\n assignment = ALL_GEOMETRY_SPECIFIER;\n foundRenderable = true;\n }\n console.log('-- add shader: ', shaderNodePath);\n shaderList.push(shaderNodePath);\n this._materials.push(new MaterialAssign(shaderNodes[0], assignment));\n }\n }\n }\n }\n const nodeGraphs = doc.getNodeGraphs();\n for (let i = 0; i < nodeGraphs.length; ++i)\n {\n let nodeGraph = nodeGraphs[i];\n if (nodeGraph)\n {\n if (nodeGraph.hasAttribute('nodedef') || nodeGraph.hasSourceUri())\n {\n continue;\n }\n // Skip any nodegraph that is connected to something downstream\n if (nodeGraph.getDownstreamPorts().length > 0)\n {\n continue\n }\n let outputs = nodeGraph.getOutputs();\n for (let j = 0; j < outputs.length; ++j)\n {\n let output = outputs[j];\n {\n let assignment = NO_GEOMETRY_SPECIFIER;\n if (foundRenderable == false)\n {\n assignment = ALL_GEOMETRY_SPECIFIER;\n foundRenderable = true;\n }\n let newMat = new MaterialAssign(output, assignment, null);\n this._materials.push(newMat);\n }\n }\n }\n }\n const outputs = doc.getOutputs();\n for (let i = 0; i < outputs.length; ++i)\n {\n let output = outputs[i];\n if (output)\n {\n let assignment = NO_GEOMETRY_SPECIFIER;\n if (foundRenderable == false)\n {\n assignment = ALL_GEOMETRY_SPECIFIER;\n foundRenderable = true;\n }\n this._materials.push(new MaterialAssign(output, assignment));\n }\n }\n\n const shaderNodes = [];\n for (let i = 0; i < shaderNodes.length; ++i)\n {\n let shaderNode = shaderNodes[i];\n let shaderNodePath = shaderNode.getNamePath()\n if (!shaderList.includes(shaderNodePath))\n {\n let assignment = NO_GEOMETRY_SPECIFIER;\n if (foundRenderable == false)\n {\n assignment = ALL_GEOMETRY_SPECIFIER;\n foundRenderable = true;\n }\n shaderList.push(shaderNodePath);\n this._materials.push(new MaterialAssign(shaderNode, assignment));\n }\n }\n }\n\n // Assign to default material if none found\n if (this._materials.length == 0)\n {\n const defaultNode = Material.createFallbackMaterial(doc);\n this._materials.push(new MaterialAssign(defaultNode, ALL_GEOMETRY_SPECIFIER));\n }\n\n // Create a new shader for each material node.\n // Only create the shader once even if assigned more than once.\n var startGenTime = performance.now();\n let shaderMap = new Map();\n let closeUI = false;\n for (let matassign of this._materials)\n {\n // Need to use path vs name to get a unique key.\n let materialName = matassign.getMaterial().getNamePath();\n let shader = shaderMap[materialName];\n if (!shader)\n {\n shader = viewer.getMaterial().generateMaterial(matassign, viewer, searchPath, closeUI);\n shaderMap[materialName] = shader;\n }\n matassign.setShader(shader);\n closeUI = true;\n }\n console.log(\"- Generate (\", this._materials.length, \") shader(s) time: \", performance.now() - startGenTime, \" ms.\",);\n\n // Update scene shader assignments\n this.updateMaterialAssignments(viewer, \"\");\n\n // Mark transform update\n viewer.getScene().setUpdateTransforms();\n\n console.log(\"Total material time: \", (performance.now() - startTime), \"ms\");\n }\n\n //\n // Update the assignments for scene objects based on the\n // material assignment information stored in the viewer.\n // Note: If none of the MaterialX assignments match the geometry\n // in the scene, then the first material assignment shader is assigned\n // to the entire scene.\n //\n async updateMaterialAssignments(viewer, soloMaterial)\n {\n console.log(\"Update material assignments. Solo=\", soloMaterial);\n var startTime = performance.now();\n\n let assigned = 0;\n let assignedSolo = false;\n for (let matassign of this._materials)\n {\n if (matassign.getShader())\n {\n if (soloMaterial.length)\n {\n if (matassign.getMaterial().getNamePath() == soloMaterial)\n {\n let temp = matassign.getGeometry();\n matassign.setGeometry(ALL_GEOMETRY_SPECIFIER);\n assigned += viewer.getScene().updateMaterial(matassign);\n matassign.setGeometry(temp);\n assignedSolo = true;\n break\n }\n }\n else\n {\n assigned += viewer.getScene().updateMaterial(matassign);\n }\n }\n }\n if (assigned == 0 && this._materials.length)\n {\n this._defaultMaterial = new MaterialAssign(this._materials[0].getMaterial(), ALL_GEOMETRY_SPECIFIER);\n this._defaultMaterial.setShader(this._materials[0].getShader());\n viewer.getScene().updateMaterial(this._defaultMaterial);\n }\n\n if (assigned > 0)\n {\n console.log('Material assignment time: ', performance.now() - startTime, \" ms.\");\n }\n }\n\n // \n // Generate a new material for a given element\n //\n generateMaterial(matassign, viewer, searchPath, closeUI)\n {\n var elem = matassign.getMaterial();\n\n var startGenerateMat = performance.now();\n\n const mx = viewer.getMx();\n const textureLoader = new three__WEBPACK_IMPORTED_MODULE_1__.TextureLoader();\n\n const lights = viewer.getLights();\n const lightData = viewer.getLightData();\n const radianceTexture = viewer.getRadianceTexture();\n const irradianceTexture = viewer.getIrradianceTexture();\n const gen = viewer.getGenerator();\n const genContext = viewer.getGenContext();\n genContext.getOptions().hwSrgbEncodeOutput = true;\n\n // Perform transparency check on renderable item\n var startTranspCheckTime = performance.now();\n const isTransparent = mx.isTransparentSurface(elem, gen.getTarget());\n genContext.getOptions().hwTransparency = isTransparent;\n // Always set to complete. \n // Can consider option to set to reduced as the parsing of large numbers of uniforms (e.g. on shading models)\n // can be quite expensive.\n genContext.getOptions().shaderInterfaceType = mx.ShaderInterfaceType.SHADER_INTERFACE_COMPLETE;\n\n if (logDetailedTime)\n console.log(\" - Transparency check time: \", performance.now() - startTranspCheckTime, \"ms\");\n\n // Generate GLES code\n var startMTLXGenTime = performance.now();\n let shader = gen.generate(elem.getNamePath(), elem, genContext);\n if (logDetailedTime)\n console.log(\" - MaterialX gen time: \", performance.now() - startMTLXGenTime, \"ms\");\n\n var startUniformUpdate = performance.now();\n\n // Get shaders and uniform values\n let vShader = shader.getSourceCode(\"vertex\");\n let fShader = shader.getSourceCode(\"pixel\");\n\n let theScene = viewer.getScene();\n let flipV = theScene.getFlipGeometryV();\n let uniforms = {\n ...(0,_helper_js__WEBPACK_IMPORTED_MODULE_0__.getUniformValues)(shader.getStage('vertex'), textureLoader, searchPath, flipV),\n ...(0,_helper_js__WEBPACK_IMPORTED_MODULE_0__.getUniformValues)(shader.getStage('pixel'), textureLoader, searchPath, flipV),\n }\n\n Object.assign(uniforms, {\n u_numActiveLightSources: { value: lights.length },\n u_lightData: { value: lightData },\n u_envMatrix: { value: (0,_helper_js__WEBPACK_IMPORTED_MODULE_0__.getLightRotation)() },\n u_envRadiance: { value: radianceTexture },\n u_envRadianceMips: { value: Math.trunc(Math.log2(Math.max(radianceTexture.image.width, radianceTexture.image.height))) + 1 },\n u_envRadianceSamples: { value: 16 },\n u_envIrradiance: { value: irradianceTexture },\n u_refractionEnv: { value: true }\n });\n\n // Create Three JS Material\n let newMaterial = new three__WEBPACK_IMPORTED_MODULE_1__.RawShaderMaterial({\n uniforms: uniforms,\n vertexShader: vShader,\n fragmentShader: fShader,\n transparent: isTransparent,\n blendEquation: three__WEBPACK_IMPORTED_MODULE_1__.AddEquation,\n blendSrc: three__WEBPACK_IMPORTED_MODULE_1__.OneMinusSrcAlphaFactor,\n blendDst: three__WEBPACK_IMPORTED_MODULE_1__.SrcAlphaFactor,\n side: three__WEBPACK_IMPORTED_MODULE_1__.DoubleSide\n });\n\n if (logDetailedTime)\n console.log(\" - Three material update time: \", performance.now() - startUniformUpdate, \"ms\");\n\n // Update property editor\n const gui = viewer.getEditor().getGUI();\n this.updateEditor(matassign, shader, newMaterial, gui, closeUI, viewer);\n\n if (logDetailedTime)\n console.log(\"- Per material generate time: \", performance.now() - startGenerateMat, \"ms\");\n\n return newMaterial;\n }\n\n clearSoloMaterialUI()\n {\n for (let i = 0; i < this._materials.length; ++i)\n {\n let matassign = this._materials[i];\n let matUI = matassign.getMaterialUI();\n if (matUI)\n {\n let matTitle = matUI.domElement.getElementsByClassName('title')[0];\n matTitle.classList.remove('peditor_material_assigned');\n let img = matTitle.getElementsByTagName('img')[0];\n img.src = 'public/shader_ball.svg';\n //matTitle.classList.remove('peditor_material_unassigned');\n }\n }\n }\n\n static updateSoloMaterial(viewer, elemPath, materials, event)\n {\n // Prevent the event from being passed to parent folder\n event.stopPropagation();\n\n for (let i = 0; i < materials.length; ++i)\n {\n let matassign = materials[i];\n // Need to use path vs name to get a unique key.\n let materialName = matassign.getMaterial().getNamePath();\n var matUI = matassign.getMaterialUI();\n let matTitle = matUI.domElement.getElementsByClassName('title')[0];\n let img = matTitle.getElementsByTagName('img')[0];\n if (materialName == elemPath)\n {\n if (this._soloMaterial == elemPath)\n {\n img.src = 'public/shader_ball.svg';\n matTitle.classList.remove('peditor_material_assigned');\n this._soloMaterial = \"\";\n }\n else\n {\n img.src = 'public/shader_ball2.svg';\n matTitle.classList.add('peditor_material_assigned');\n this._soloMaterial = elemPath;\n }\n }\n else\n {\n img.src = 'public/shader_ball.svg';\n matTitle.classList.remove('peditor_material_assigned');\n }\n }\n viewer.getMaterial().updateMaterialAssignments(viewer, this._soloMaterial);\n viewer.getScene().setUpdateTransforms();\n }\n\n //\n // Update property editor for a given MaterialX element, it's shader, and\n // Three material\n //\n updateEditor(matassign, shader, material, gui, closeUI, viewer)\n {\n var elem = matassign.getMaterial();\n var materials = this._materials;\n\n const DEFAULT_MIN = 0;\n const DEFAULT_MAX = 100;\n\n var startTime = performance.now();\n\n const elemPath = elem.getNamePath();\n\n // Create and cache associated UI\n var matUI = gui.addFolder(elemPath);\n matassign.setMaterialUI(matUI);\n\n let matTitle = matUI.domElement.getElementsByClassName('title')[0];\n // Add a icon to the title to allow for assigning the material to geometry\n // Clicking on the icon will \"solo\" the material to the geometry.\n // Clicking on the title will open/close the material folder.\n matTitle.innerHTML = \"\" + elem.getNamePath();\n let img = matTitle.getElementsByTagName('img')[0];\n if (img)\n {\n // Add event listener to icon to call updateSoloMaterial function\n img.addEventListener('click', function (event)\n {\n Material.updateSoloMaterial(viewer, elemPath, materials, event);\n });\n }\n\n if (closeUI)\n {\n matUI.close();\n }\n const uniformBlocks = Object.values(shader.getStage('pixel').getUniformBlocks());\n var uniformToUpdate;\n const ignoreList = ['u_envRadianceMips', 'u_envRadianceSamples', 'u_alphaThreshold'];\n\n var folderList = new Map();\n folderList[elemPath] = matUI;\n\n uniformBlocks.forEach(uniforms =>\n {\n if (!uniforms.empty())\n {\n for (let i = 0; i < uniforms.size(); ++i)\n {\n const variable = uniforms.get(i);\n const value = variable.getValue()?.getData();\n let name = variable.getVariable();\n\n if (ignoreList.includes(name))\n {\n continue;\n }\n\n let currentFolder = matUI;\n let currentElemPath = variable.getPath();\n if (!currentElemPath || currentElemPath.length == 0)\n {\n continue;\n }\n let currentElem = elem.getDocument().getDescendant(currentElemPath);\n if (!currentElem)\n {\n continue;\n }\n \n // Skip non-input types and anything > 2 levels deep \n if (!currentElem.asAInput() || currentElem.getNamePath().split('/').length > 2)\n {\n continue;\n }\n\n let currentNode = null;\n if (currentElem.getParent() && currentElem.getParent().getNamePath() != \"\")\n {\n currentNode = currentElem.getParent();\n }\n let uiname = \"\";\n let nodeDefInput = null;\n if (currentNode)\n {\n\n let currentNodePath = currentNode.getNamePath();\n var pathSplit = currentNodePath.split('/');\n if (pathSplit.length)\n {\n currentNodePath = pathSplit[0];\n }\n currentFolder = folderList[currentNodePath];\n if (!currentFolder)\n {\n currentFolder = matUI.addFolder(currentNodePath);\n folderList[currentNodePath] = currentFolder;\n }\n\n // Check for ui attributes\n var nodeDef = currentNode.getNodeDef();\n if (nodeDef)\n {\n // Remove node name from shader uniform name for non root nodes\n let lookup_name = name.replace(currentNode.getName() + '_', '');\n nodeDefInput = nodeDef.getActiveInput(lookup_name);\n if (nodeDefInput)\n {\n uiname = nodeDefInput.getAttribute('uiname');\n let uifolderName = nodeDefInput.getAttribute('uifolder');\n if (uifolderName && uifolderName.length)\n {\n let newFolderName = currentNodePath + '/' + uifolderName;\n currentFolder = folderList[newFolderName];\n if (!currentFolder)\n {\n currentFolder = matUI.addFolder(uifolderName);\n currentFolder.domElement.classList.add('peditorfolder');\n folderList[newFolderName] = currentFolder;\n }\n }\n }\n }\n }\n\n // Determine UI name to use\n let path = name;\n let interfaceName = currentElem.getAttribute(\"interfacename\");\n if (interfaceName && interfaceName.length)\n {\n const graph = currentNode.getParent();\n if (graph)\n {\n const graphInput = graph.getInput(interfaceName);\n if (graphInput)\n {\n let uiname = graphInput.getAttribute('uiname');\n if (uiname.length)\n {\n path = uiname;\n }\n else\n {\n path = graphInput.getName();\n }\n }\n }\n else\n {\n path = interfaceName;\n }\n }\n else\n {\n if (!uiname)\n {\n uiname = currentElem.getAttribute('uiname');\n }\n if (uiname && uiname.length)\n {\n path = uiname;\n }\n }\n\n // Skip if already added to current folder \n let found = false;\n for (let i = 0; i < currentFolder.children.length; ++i)\n {\n if (currentFolder.children[i]._name == path)\n {\n found = true;\n break;\n }\n } \n if (found)\n {\n continue;\n }\n\n switch (variable.getType().getName())\n {\n case 'float':\n uniformToUpdate = material.uniforms[name];\n if (uniformToUpdate && value != null)\n {\n var minValue = DEFAULT_MIN;\n if (value < minValue)\n {\n minValue = value;\n }\n var maxValue = DEFAULT_MAX;\n if (value > maxValue)\n {\n maxValue = value;\n }\n var step = 0;\n if (nodeDefInput)\n {\n if (nodeDefInput.hasAttribute('uisoftmin'))\n minValue = parseFloat(nodeDefInput.getAttribute('uisoftmin'));\n else if (nodeDefInput.hasAttribute('uimin'))\n minValue = parseFloat(nodeDefInput.getAttribute('uimin'));\n\n if (nodeDefInput.hasAttribute('uisoftmax'))\n maxValue = parseFloat(nodeDefInput.getAttribute('uisoftmax'));\n else if (nodeDefInput.hasAttribute('uimax'))\n maxValue = parseFloat(nodeDefInput.getAttribute('uimax'));\n\n if (nodeDefInput.hasAttribute('uistep'))\n step = parseFloat(nodeDefInput.getAttribute('uistep'));\n }\n if (step == 0)\n {\n step = (maxValue - minValue) / 1000.0;\n }\n const w = currentFolder.add(material.uniforms[name], 'value', minValue, maxValue, step).name(path);\n w.domElement.classList.add('peditoritem');\n }\n break;\n\n case 'integer':\n uniformToUpdate = material.uniforms[name];\n if (uniformToUpdate && value != null)\n {\n var minValue = DEFAULT_MIN;\n if (value < minValue)\n {\n minValue = value;\n }\n var maxValue = DEFAULT_MAX;\n if (value > maxValue)\n {\n maxValue = value;\n }\n var step = 0;\n var enumList = []\n var enumValues = []\n if (nodeDefInput)\n {\n if (nodeDefInput.hasAttribute('enum'))\n {\n // Get enum and enum values attributes (if present)\n enumList = nodeDefInput.getAttribute('enum').split(',');\n if (nodeDefInput.hasAttribute('enumvalues'))\n {\n enumValues = nodeDefInput.getAttribute('enumvalues').split(',').map(Number);\n }\n }\n else\n {\n if (nodeDefInput.hasAttribute('uisoftmin'))\n minValue = parseInt(nodeDefInput.getAttribute('uisoftmin'));\n else if (nodeDefInput.hasAttribute('uimin'))\n minValue = parseInt(nodeDefInput.getAttribute('uimin'));\n\n if (nodeDefInput.hasAttribute('uisoftmax'))\n maxValue = parseInt(nodeDefInput.getAttribute('uisoftmax'));\n else if (nodeDefInput.hasAttribute('uimax'))\n maxValue = parseInt(nodeDefInput.getAttribute('uimax'));\n\n if (nodeDefInput.hasAttribute('uistep'))\n step = parseInt(nodeDefInput.getAttribute('uistep'));\n }\n }\n if (enumList.length == 0)\n {\n if (step == 0)\n {\n step = 1 / (maxValue - minValue);\n step = Math.ceil(step);\n if (step == 0)\n {\n step = 1;\n }\n }\n }\n if (enumList.length == 0)\n {\n let w = currentFolder.add(material.uniforms[name], 'value', minValue, maxValue, step).name(path);\n w.domElement.classList.add('peditoritem');\n }\n else\n {\n // Map enumList strings to values\n // Map to 0..N if no values are specified via enumvalues attribute\n if (enumValues.length == 0)\n {\n for (let i = 0; i < enumList.length; ++i)\n {\n enumValues.push(i);\n }\n }\n const enumeration = {};\n enumList.forEach((str, index) =>\n {\n enumeration[str] = enumValues[index];\n });\n\n // Function to handle enum drop-down\n function handleDropdownChange(value)\n {\n if (material.uniforms[name])\n {\n material.uniforms[name].value = value;\n }\n }\n const defaultOption = enumList[value]; // Set the default selected option\n const dropdownController = currentFolder.add(enumeration, defaultOption, enumeration).name(path);\n dropdownController.onChange(handleDropdownChange);\n dropdownController.domElement.classList.add('peditoritem');\n }\n }\n break;\n\n case 'boolean':\n uniformToUpdate = material.uniforms[name];\n if (uniformToUpdate && value != null)\n {\n let w = currentFolder.add(material.uniforms[name], 'value').name(path);\n w.domElement.classList.add('peditoritem');\n }\n break;\n\n case 'vector2':\n case 'vector3':\n case 'vector4':\n uniformToUpdate = material.uniforms[name];\n if (uniformToUpdate && value != null)\n {\n var minValue = [DEFAULT_MIN, DEFAULT_MIN, DEFAULT_MIN, DEFAULT_MIN];\n var maxValue = [DEFAULT_MAX, DEFAULT_MAX, DEFAULT_MAX, DEFAULT_MAX];\n var step = [0, 0, 0, 0];\n\n if (nodeDefInput)\n {\n if (nodeDefInput.hasAttribute('uisoftmin'))\n minValue = nodeDefInput.getAttribute('uisoftmin').split(',').map(Number);\n else if (nodeDefInput.hasAttribute('uimin'))\n minValue = nodeDefInput.getAttribute('uimin').split(',').map(Number);\n\n if (nodeDefInput.hasAttribute('uisoftmax'))\n maxValue = nodeDefInput.getAttribute('uisoftmax').split(',').map(Number);\n else if (nodeDefInput.hasAttribute('uimax'))\n maxValue = nodeDefInput.getAttribute('uimax').split(',').map(Number);\n\n if (nodeDefInput.hasAttribute('uistep'))\n step = nodeDefInput.getAttribute('uistep').split(',').map(Number);\n }\n for (let i = 0; i < 4; ++i)\n {\n if (step[i] == 0)\n {\n step[i] = 1 / (maxValue[i] - minValue[i]);\n }\n }\n\n const keyString = [\"x\", \"y\", \"z\", \"w\"];\n let vecFolder = currentFolder.addFolder(path);\n Object.keys(material.uniforms[name].value).forEach((key) =>\n {\n let w = vecFolder.add(material.uniforms[name].value,\n key, minValue[key], maxValue[key], step[key]).name(keyString[key]);\n w.domElement.classList.add('peditoritem');\n })\n }\n break;\n\n case 'color3':\n // Irksome way to map arrays to colors and back\n uniformToUpdate = material.uniforms[name];\n if (uniformToUpdate && value != null)\n {\n var dummy =\n {\n color: 0xFF0000\n };\n const color3 = new three__WEBPACK_IMPORTED_MODULE_1__.Color(dummy.color);\n color3.fromArray(material.uniforms[name].value);\n dummy.color = color3.getHex();\n let w = currentFolder.addColor(dummy, 'color').name(path)\n .onChange(function (value)\n {\n const color3 = new three__WEBPACK_IMPORTED_MODULE_1__.Color(value);\n material.uniforms[name].value.set(color3.toArray());\n });\n w.domElement.classList.add('peditoritem');\n }\n break;\n\n case 'color4':\n break;\n\n case 'matrix33':\n case 'matrix44':\n case 'samplerCube':\n case 'filename':\n break;\n case 'string':\n if (value != null)\n {\n var dummy =\n {\n thevalue: value\n }\n let item = currentFolder.add(dummy, 'thevalue');\n item.name(path);\n item.disable(true);\n item.domElement.classList.add('peditoritem');\n }\n break;\n default:\n break;\n }\n }\n }\n });\n\n if (logDetailedTime)\n {\n console.log(\" - Editor update time: \", performance.now() - startTime, \"ms\");\n }\n }\n\n // List of material assignments: { MaterialX node, geometry assignment string, and hardware shader }\n _materials;\n\n // Fallback material if nothing was assigned explicitly\n _defaultMaterial;\n}\n\n/*\n Viewer class\n\n Keeps track of local scene, and property editor as well as current MaterialX document \n and assocaited material, shader and lighting information.\n*/\nclass Viewer\n{\n static create()\n {\n return new Viewer();\n }\n\n constructor()\n {\n this.scene = new Scene();\n this.editor = new Editor();\n this.materials.push(new Material());\n\n this.fileLoader = new three__WEBPACK_IMPORTED_MODULE_1__.FileLoader();\n this.hdrLoader = new three_examples_jsm_loaders_RGBELoader_js__WEBPACK_IMPORTED_MODULE_4__.RGBELoader();\n }\n\n //\n // Create shader generator, generation context and \"base\" document which\n // contains the standard definition libraries and lighting elements.\n //\n async initialize(mtlxIn, renderer, radianceTexture, irradianceTexture, lightRigXml)\n {\n this.mx = mtlxIn;\n\n // Initialize base document\n this.generator = new this.mx.EsslShaderGenerator();\n this.genContext = new this.mx.GenContext(this.generator);\n\n this.document = this.mx.createDocument();\n this.stdlib = this.mx.loadStandardLibraries(this.genContext);\n this.document.importLibrary(this.stdlib);\n\n this.initializeLighting(renderer, radianceTexture, irradianceTexture, lightRigXml);\n\n radianceTexture.mapping = three__WEBPACK_IMPORTED_MODULE_1__.EquirectangularReflectionMapping;\n this.getScene().setBackgroundTexture(radianceTexture);\n }\n\n //\n // Load in lighting rig document and register lights with generation context\n // Initialize environment lighting (IBLs).\n //\n async initializeLighting(renderer, radianceTexture, irradianceTexture, lightRigXml)\n {\n // Load lighting setup into document\n const mx = this.getMx();\n this.lightRigDoc = mx.createDocument();\n await mx.readFromXmlString(this.lightRigDoc, lightRigXml);\n this.document.importLibrary(this.lightRigDoc);\n\n // Register lights with generation context\n this.lights = (0,_helper_js__WEBPACK_IMPORTED_MODULE_0__.findLights)(this.document);\n this.lightData = (0,_helper_js__WEBPACK_IMPORTED_MODULE_0__.registerLights)(mx, this.lights, this.genContext);\n\n this.radianceTexture = (0,_helper_js__WEBPACK_IMPORTED_MODULE_0__.prepareEnvTexture)(radianceTexture, renderer.capabilities);\n this.irradianceTexture = (0,_helper_js__WEBPACK_IMPORTED_MODULE_0__.prepareEnvTexture)(irradianceTexture, renderer.capabilities);\n }\n\n getEditor()\n {\n return this.editor;\n }\n\n getScene()\n {\n return this.scene;\n }\n\n getMaterial()\n {\n return this.materials[0];\n }\n\n getFileLoader()\n {\n return this.fileLoader;\n }\n\n getHdrLoader()\n {\n return this.hdrLoader;\n }\n\n setDocument(doc)\n {\n this.doc = doc;\n }\n getDocument()\n {\n return this.doc;\n }\n\n getLibrary()\n {\n return this.stdlib;\n }\n\n getLightRig()\n {\n return this.lightRigDoc;\n }\n\n getMx()\n {\n return this.mx;\n }\n\n getGenerator()\n {\n return this.generator;\n }\n\n getGenContext()\n {\n return this.genContext;\n }\n\n getLights()\n {\n return this.lights;\n }\n\n getLightData()\n {\n return this.lightData;\n }\n\n getRadianceTexture()\n {\n return this.radianceTexture;\n }\n\n getIrradianceTexture()\n {\n return this.irradianceTexture;\n }\n\n // Three scene and materials. \n scene = null;\n materials = [];\n\n // Property editor\n editor = null;\n\n // Utility loaders\n fileloader = null;\n hdrLoader = null;\n\n // MaterialX module, current document and support documents.\n mx = null;\n doc = null;\n stdlib = null;\n lightRigDoc = null;\n\n // MaterialX code generator and context\n generator = null;\n genContext = null;\n\n // Lighting information\n lights = null;\n lightData = null;\n radianceTexture = null;\n irradianceTexture = null;\n}\n\n\n//# sourceURL=webpack://MaterialXView/./source/viewer.js?"); + +/***/ }), + +/***/ "./node_modules/lil-gui/dist/lil-gui.esm.js": +/*!**************************************************!*\ + !*** ./node_modules/lil-gui/dist/lil-gui.esm.js ***! + \**************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BooleanController: () => (/* binding */ BooleanController),\n/* harmony export */ ColorController: () => (/* binding */ ColorController),\n/* harmony export */ Controller: () => (/* binding */ Controller),\n/* harmony export */ FunctionController: () => (/* binding */ FunctionController),\n/* harmony export */ GUI: () => (/* binding */ GUI),\n/* harmony export */ NumberController: () => (/* binding */ NumberController),\n/* harmony export */ OptionController: () => (/* binding */ OptionController),\n/* harmony export */ StringController: () => (/* binding */ StringController),\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/**\n * lil-gui\n * https://lil-gui.georgealways.com\n * @version 0.19.2\n * @author George Michael Brower\n * @license MIT\n */\n\n/**\n * Base class for all controllers.\n */\nclass Controller {\n\n\tconstructor( parent, object, property, className, elementType = 'div' ) {\n\n\t\t/**\n\t\t * The GUI that contains this controller.\n\t\t * @type {GUI}\n\t\t */\n\t\tthis.parent = parent;\n\n\t\t/**\n\t\t * The object this controller will modify.\n\t\t * @type {object}\n\t\t */\n\t\tthis.object = object;\n\n\t\t/**\n\t\t * The name of the property to control.\n\t\t * @type {string}\n\t\t */\n\t\tthis.property = property;\n\n\t\t/**\n\t\t * Used to determine if the controller is disabled.\n\t\t * Use `controller.disable( true|false )` to modify this value.\n\t\t * @type {boolean}\n\t\t */\n\t\tthis._disabled = false;\n\n\t\t/**\n\t\t * Used to determine if the Controller is hidden.\n\t\t * Use `controller.show()` or `controller.hide()` to change this.\n\t\t * @type {boolean}\n\t\t */\n\t\tthis._hidden = false;\n\n\t\t/**\n\t\t * The value of `object[ property ]` when the controller was created.\n\t\t * @type {any}\n\t\t */\n\t\tthis.initialValue = this.getValue();\n\n\t\t/**\n\t\t * The outermost container DOM element for this controller.\n\t\t * @type {HTMLElement}\n\t\t */\n\t\tthis.domElement = document.createElement( elementType );\n\t\tthis.domElement.classList.add( 'controller' );\n\t\tthis.domElement.classList.add( className );\n\n\t\t/**\n\t\t * The DOM element that contains the controller's name.\n\t\t * @type {HTMLElement}\n\t\t */\n\t\tthis.$name = document.createElement( 'div' );\n\t\tthis.$name.classList.add( 'name' );\n\n\t\tController.nextNameID = Controller.nextNameID || 0;\n\t\tthis.$name.id = `lil-gui-name-${++Controller.nextNameID}`;\n\n\t\t/**\n\t\t * The DOM element that contains the controller's \"widget\" (which differs by controller type).\n\t\t * @type {HTMLElement}\n\t\t */\n\t\tthis.$widget = document.createElement( 'div' );\n\t\tthis.$widget.classList.add( 'widget' );\n\n\t\t/**\n\t\t * The DOM element that receives the disabled attribute when using disable().\n\t\t * @type {HTMLElement}\n\t\t */\n\t\tthis.$disable = this.$widget;\n\n\t\tthis.domElement.appendChild( this.$name );\n\t\tthis.domElement.appendChild( this.$widget );\n\n\t\t// Don't fire global key events while typing in a controller\n\t\tthis.domElement.addEventListener( 'keydown', e => e.stopPropagation() );\n\t\tthis.domElement.addEventListener( 'keyup', e => e.stopPropagation() );\n\n\t\tthis.parent.children.push( this );\n\t\tthis.parent.controllers.push( this );\n\n\t\tthis.parent.$children.appendChild( this.domElement );\n\n\t\tthis._listenCallback = this._listenCallback.bind( this );\n\n\t\tthis.name( property );\n\n\t}\n\n\t/**\n\t * Sets the name of the controller and its label in the GUI.\n\t * @param {string} name\n\t * @returns {this}\n\t */\n\tname( name ) {\n\t\t/**\n\t\t * The controller's name. Use `controller.name( 'Name' )` to modify this value.\n\t\t * @type {string}\n\t\t */\n\t\tthis._name = name;\n\t\tthis.$name.textContent = name;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Pass a function to be called whenever the value is modified by this controller.\n\t * The function receives the new value as its first parameter. The value of `this` will be the\n\t * controller.\n\t *\n\t * For function controllers, the `onChange` callback will be fired on click, after the function\n\t * executes.\n\t * @param {Function} callback\n\t * @returns {this}\n\t * @example\n\t * const controller = gui.add( object, 'property' );\n\t *\n\t * controller.onChange( function( v ) {\n\t * \tconsole.log( 'The value is now ' + v );\n\t * \tconsole.assert( this === controller );\n\t * } );\n\t */\n\tonChange( callback ) {\n\t\t/**\n\t\t * Used to access the function bound to `onChange` events. Don't modify this value directly.\n\t\t * Use the `controller.onChange( callback )` method instead.\n\t\t * @type {Function}\n\t\t */\n\t\tthis._onChange = callback;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Calls the onChange methods of this controller and its parent GUI.\n\t * @protected\n\t */\n\t_callOnChange() {\n\n\t\tthis.parent._callOnChange( this );\n\n\t\tif ( this._onChange !== undefined ) {\n\t\t\tthis._onChange.call( this, this.getValue() );\n\t\t}\n\n\t\tthis._changed = true;\n\n\t}\n\n\t/**\n\t * Pass a function to be called after this controller has been modified and loses focus.\n\t * @param {Function} callback\n\t * @returns {this}\n\t * @example\n\t * const controller = gui.add( object, 'property' );\n\t *\n\t * controller.onFinishChange( function( v ) {\n\t * \tconsole.log( 'Changes complete: ' + v );\n\t * \tconsole.assert( this === controller );\n\t * } );\n\t */\n\tonFinishChange( callback ) {\n\t\t/**\n\t\t * Used to access the function bound to `onFinishChange` events. Don't modify this value\n\t\t * directly. Use the `controller.onFinishChange( callback )` method instead.\n\t\t * @type {Function}\n\t\t */\n\t\tthis._onFinishChange = callback;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Should be called by Controller when its widgets lose focus.\n\t * @protected\n\t */\n\t_callOnFinishChange() {\n\n\t\tif ( this._changed ) {\n\n\t\t\tthis.parent._callOnFinishChange( this );\n\n\t\t\tif ( this._onFinishChange !== undefined ) {\n\t\t\t\tthis._onFinishChange.call( this, this.getValue() );\n\t\t\t}\n\n\t\t}\n\n\t\tthis._changed = false;\n\n\t}\n\n\t/**\n\t * Sets the controller back to its initial value.\n\t * @returns {this}\n\t */\n\treset() {\n\t\tthis.setValue( this.initialValue );\n\t\tthis._callOnFinishChange();\n\t\treturn this;\n\t}\n\n\t/**\n\t * Enables this controller.\n\t * @param {boolean} enabled\n\t * @returns {this}\n\t * @example\n\t * controller.enable();\n\t * controller.enable( false ); // disable\n\t * controller.enable( controller._disabled ); // toggle\n\t */\n\tenable( enabled = true ) {\n\t\treturn this.disable( !enabled );\n\t}\n\n\t/**\n\t * Disables this controller.\n\t * @param {boolean} disabled\n\t * @returns {this}\n\t * @example\n\t * controller.disable();\n\t * controller.disable( false ); // enable\n\t * controller.disable( !controller._disabled ); // toggle\n\t */\n\tdisable( disabled = true ) {\n\n\t\tif ( disabled === this._disabled ) return this;\n\n\t\tthis._disabled = disabled;\n\n\t\tthis.domElement.classList.toggle( 'disabled', disabled );\n\t\tthis.$disable.toggleAttribute( 'disabled', disabled );\n\n\t\treturn this;\n\n\t}\n\n\t/**\n\t * Shows the Controller after it's been hidden.\n\t * @param {boolean} show\n\t * @returns {this}\n\t * @example\n\t * controller.show();\n\t * controller.show( false ); // hide\n\t * controller.show( controller._hidden ); // toggle\n\t */\n\tshow( show = true ) {\n\n\t\tthis._hidden = !show;\n\n\t\tthis.domElement.style.display = this._hidden ? 'none' : '';\n\n\t\treturn this;\n\n\t}\n\n\t/**\n\t * Hides the Controller.\n\t * @returns {this}\n\t */\n\thide() {\n\t\treturn this.show( false );\n\t}\n\n\t/**\n\t * Changes this controller into a dropdown of options.\n\t *\n\t * Calling this method on an option controller will simply update the options. However, if this\n\t * controller was not already an option controller, old references to this controller are\n\t * destroyed, and a new controller is added to the end of the GUI.\n\t * @example\n\t * // safe usage\n\t *\n\t * gui.add( obj, 'prop1' ).options( [ 'a', 'b', 'c' ] );\n\t * gui.add( obj, 'prop2' ).options( { Big: 10, Small: 1 } );\n\t * gui.add( obj, 'prop3' );\n\t *\n\t * // danger\n\t *\n\t * const ctrl1 = gui.add( obj, 'prop1' );\n\t * gui.add( obj, 'prop2' );\n\t *\n\t * // calling options out of order adds a new controller to the end...\n\t * const ctrl2 = ctrl1.options( [ 'a', 'b', 'c' ] );\n\t *\n\t * // ...and ctrl1 now references a controller that doesn't exist\n\t * assert( ctrl2 !== ctrl1 )\n\t * @param {object|Array} options\n\t * @returns {Controller}\n\t */\n\toptions( options ) {\n\t\tconst controller = this.parent.add( this.object, this.property, options );\n\t\tcontroller.name( this._name );\n\t\tthis.destroy();\n\t\treturn controller;\n\t}\n\n\t/**\n\t * Sets the minimum value. Only works on number controllers.\n\t * @param {number} min\n\t * @returns {this}\n\t */\n\tmin( min ) {\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum value. Only works on number controllers.\n\t * @param {number} max\n\t * @returns {this}\n\t */\n\tmax( max ) {\n\t\treturn this;\n\t}\n\n\t/**\n\t * Values set by this controller will be rounded to multiples of `step`. Only works on number\n\t * controllers.\n\t * @param {number} step\n\t * @returns {this}\n\t */\n\tstep( step ) {\n\t\treturn this;\n\t}\n\n\t/**\n\t * Rounds the displayed value to a fixed number of decimals, without affecting the actual value\n\t * like `step()`. Only works on number controllers.\n\t * @example\n\t * gui.add( object, 'property' ).listen().decimals( 4 );\n\t * @param {number} decimals\n\t * @returns {this}\n\t */\n\tdecimals( decimals ) {\n\t\treturn this;\n\t}\n\n\t/**\n\t * Calls `updateDisplay()` every animation frame. Pass `false` to stop listening.\n\t * @param {boolean} listen\n\t * @returns {this}\n\t */\n\tlisten( listen = true ) {\n\n\t\t/**\n\t\t * Used to determine if the controller is currently listening. Don't modify this value\n\t\t * directly. Use the `controller.listen( true|false )` method instead.\n\t\t * @type {boolean}\n\t\t */\n\t\tthis._listening = listen;\n\n\t\tif ( this._listenCallbackID !== undefined ) {\n\t\t\tcancelAnimationFrame( this._listenCallbackID );\n\t\t\tthis._listenCallbackID = undefined;\n\t\t}\n\n\t\tif ( this._listening ) {\n\t\t\tthis._listenCallback();\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t_listenCallback() {\n\n\t\tthis._listenCallbackID = requestAnimationFrame( this._listenCallback );\n\n\t\t// To prevent framerate loss, make sure the value has changed before updating the display.\n\t\t// Note: save() is used here instead of getValue() only because of ColorController. The !== operator\n\t\t// won't work for color objects or arrays, but ColorController.save() always returns a string.\n\n\t\tconst curValue = this.save();\n\n\t\tif ( curValue !== this._listenPrevValue ) {\n\t\t\tthis.updateDisplay();\n\t\t}\n\n\t\tthis._listenPrevValue = curValue;\n\n\t}\n\n\t/**\n\t * Returns `object[ property ]`.\n\t * @returns {any}\n\t */\n\tgetValue() {\n\t\treturn this.object[ this.property ];\n\t}\n\n\t/**\n\t * Sets the value of `object[ property ]`, invokes any `onChange` handlers and updates the display.\n\t * @param {any} value\n\t * @returns {this}\n\t */\n\tsetValue( value ) {\n\n\t\tif ( this.getValue() !== value ) {\n\n\t\t\tthis.object[ this.property ] = value;\n\t\t\tthis._callOnChange();\n\t\t\tthis.updateDisplay();\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t/**\n\t * Updates the display to keep it in sync with the current value. Useful for updating your\n\t * controllers when their values have been modified outside of the GUI.\n\t * @returns {this}\n\t */\n\tupdateDisplay() {\n\t\treturn this;\n\t}\n\n\tload( value ) {\n\t\tthis.setValue( value );\n\t\tthis._callOnFinishChange();\n\t\treturn this;\n\t}\n\n\tsave() {\n\t\treturn this.getValue();\n\t}\n\n\t/**\n\t * Destroys this controller and removes it from the parent GUI.\n\t */\n\tdestroy() {\n\t\tthis.listen( false );\n\t\tthis.parent.children.splice( this.parent.children.indexOf( this ), 1 );\n\t\tthis.parent.controllers.splice( this.parent.controllers.indexOf( this ), 1 );\n\t\tthis.parent.$children.removeChild( this.domElement );\n\t}\n\n}\n\nclass BooleanController extends Controller {\n\n\tconstructor( parent, object, property ) {\n\n\t\tsuper( parent, object, property, 'boolean', 'label' );\n\n\t\tthis.$input = document.createElement( 'input' );\n\t\tthis.$input.setAttribute( 'type', 'checkbox' );\n\t\tthis.$input.setAttribute( 'aria-labelledby', this.$name.id );\n\n\t\tthis.$widget.appendChild( this.$input );\n\n\t\tthis.$input.addEventListener( 'change', () => {\n\t\t\tthis.setValue( this.$input.checked );\n\t\t\tthis._callOnFinishChange();\n\t\t} );\n\n\t\tthis.$disable = this.$input;\n\n\t\tthis.updateDisplay();\n\n\t}\n\n\tupdateDisplay() {\n\t\tthis.$input.checked = this.getValue();\n\t\treturn this;\n\t}\n\n}\n\nfunction normalizeColorString( string ) {\n\n\tlet match, result;\n\n\tif ( match = string.match( /(#|0x)?([a-f0-9]{6})/i ) ) {\n\n\t\tresult = match[ 2 ];\n\n\t} else if ( match = string.match( /rgb\\(\\s*(\\d*)\\s*,\\s*(\\d*)\\s*,\\s*(\\d*)\\s*\\)/ ) ) {\n\n\t\tresult = parseInt( match[ 1 ] ).toString( 16 ).padStart( 2, 0 )\n\t\t\t+ parseInt( match[ 2 ] ).toString( 16 ).padStart( 2, 0 )\n\t\t\t+ parseInt( match[ 3 ] ).toString( 16 ).padStart( 2, 0 );\n\n\t} else if ( match = string.match( /^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i ) ) {\n\n\t\tresult = match[ 1 ] + match[ 1 ] + match[ 2 ] + match[ 2 ] + match[ 3 ] + match[ 3 ];\n\n\t}\n\n\tif ( result ) {\n\t\treturn '#' + result;\n\t}\n\n\treturn false;\n\n}\n\nconst STRING = {\n\tisPrimitive: true,\n\tmatch: v => typeof v === 'string',\n\tfromHexString: normalizeColorString,\n\ttoHexString: normalizeColorString\n};\n\nconst INT = {\n\tisPrimitive: true,\n\tmatch: v => typeof v === 'number',\n\tfromHexString: string => parseInt( string.substring( 1 ), 16 ),\n\ttoHexString: value => '#' + value.toString( 16 ).padStart( 6, 0 )\n};\n\nconst ARRAY = {\n\tisPrimitive: false,\n\n\t// The arrow function is here to appease tree shakers like esbuild or webpack.\n\t// See https://esbuild.github.io/api/#tree-shaking\n\tmatch: v => Array.isArray( v ),\n\n\tfromHexString( string, target, rgbScale = 1 ) {\n\n\t\tconst int = INT.fromHexString( string );\n\n\t\ttarget[ 0 ] = ( int >> 16 & 255 ) / 255 * rgbScale;\n\t\ttarget[ 1 ] = ( int >> 8 & 255 ) / 255 * rgbScale;\n\t\ttarget[ 2 ] = ( int & 255 ) / 255 * rgbScale;\n\n\t},\n\ttoHexString( [ r, g, b ], rgbScale = 1 ) {\n\n\t\trgbScale = 255 / rgbScale;\n\n\t\tconst int = ( r * rgbScale ) << 16 ^\n\t\t\t( g * rgbScale ) << 8 ^\n\t\t\t( b * rgbScale ) << 0;\n\n\t\treturn INT.toHexString( int );\n\n\t}\n};\n\nconst OBJECT = {\n\tisPrimitive: false,\n\tmatch: v => Object( v ) === v,\n\tfromHexString( string, target, rgbScale = 1 ) {\n\n\t\tconst int = INT.fromHexString( string );\n\n\t\ttarget.r = ( int >> 16 & 255 ) / 255 * rgbScale;\n\t\ttarget.g = ( int >> 8 & 255 ) / 255 * rgbScale;\n\t\ttarget.b = ( int & 255 ) / 255 * rgbScale;\n\n\t},\n\ttoHexString( { r, g, b }, rgbScale = 1 ) {\n\n\t\trgbScale = 255 / rgbScale;\n\n\t\tconst int = ( r * rgbScale ) << 16 ^\n\t\t\t( g * rgbScale ) << 8 ^\n\t\t\t( b * rgbScale ) << 0;\n\n\t\treturn INT.toHexString( int );\n\n\t}\n};\n\nconst FORMATS = [ STRING, INT, ARRAY, OBJECT ];\n\nfunction getColorFormat( value ) {\n\treturn FORMATS.find( format => format.match( value ) );\n}\n\nclass ColorController extends Controller {\n\n\tconstructor( parent, object, property, rgbScale ) {\n\n\t\tsuper( parent, object, property, 'color' );\n\n\t\tthis.$input = document.createElement( 'input' );\n\t\tthis.$input.setAttribute( 'type', 'color' );\n\t\tthis.$input.setAttribute( 'tabindex', -1 );\n\t\tthis.$input.setAttribute( 'aria-labelledby', this.$name.id );\n\n\t\tthis.$text = document.createElement( 'input' );\n\t\tthis.$text.setAttribute( 'type', 'text' );\n\t\tthis.$text.setAttribute( 'spellcheck', 'false' );\n\t\tthis.$text.setAttribute( 'aria-labelledby', this.$name.id );\n\n\t\tthis.$display = document.createElement( 'div' );\n\t\tthis.$display.classList.add( 'display' );\n\n\t\tthis.$display.appendChild( this.$input );\n\t\tthis.$widget.appendChild( this.$display );\n\t\tthis.$widget.appendChild( this.$text );\n\n\t\tthis._format = getColorFormat( this.initialValue );\n\t\tthis._rgbScale = rgbScale;\n\n\t\tthis._initialValueHexString = this.save();\n\t\tthis._textFocused = false;\n\n\t\tthis.$input.addEventListener( 'input', () => {\n\t\t\tthis._setValueFromHexString( this.$input.value );\n\t\t} );\n\n\t\tthis.$input.addEventListener( 'blur', () => {\n\t\t\tthis._callOnFinishChange();\n\t\t} );\n\n\t\tthis.$text.addEventListener( 'input', () => {\n\t\t\tconst tryParse = normalizeColorString( this.$text.value );\n\t\t\tif ( tryParse ) {\n\t\t\t\tthis._setValueFromHexString( tryParse );\n\t\t\t}\n\t\t} );\n\n\t\tthis.$text.addEventListener( 'focus', () => {\n\t\t\tthis._textFocused = true;\n\t\t\tthis.$text.select();\n\t\t} );\n\n\t\tthis.$text.addEventListener( 'blur', () => {\n\t\t\tthis._textFocused = false;\n\t\t\tthis.updateDisplay();\n\t\t\tthis._callOnFinishChange();\n\t\t} );\n\n\t\tthis.$disable = this.$text;\n\n\t\tthis.updateDisplay();\n\n\t}\n\n\treset() {\n\t\tthis._setValueFromHexString( this._initialValueHexString );\n\t\treturn this;\n\t}\n\n\t_setValueFromHexString( value ) {\n\n\t\tif ( this._format.isPrimitive ) {\n\n\t\t\tconst newValue = this._format.fromHexString( value );\n\t\t\tthis.setValue( newValue );\n\n\t\t} else {\n\n\t\t\tthis._format.fromHexString( value, this.getValue(), this._rgbScale );\n\t\t\tthis._callOnChange();\n\t\t\tthis.updateDisplay();\n\n\t\t}\n\n\t}\n\n\tsave() {\n\t\treturn this._format.toHexString( this.getValue(), this._rgbScale );\n\t}\n\n\tload( value ) {\n\t\tthis._setValueFromHexString( value );\n\t\tthis._callOnFinishChange();\n\t\treturn this;\n\t}\n\n\tupdateDisplay() {\n\t\tthis.$input.value = this._format.toHexString( this.getValue(), this._rgbScale );\n\t\tif ( !this._textFocused ) {\n\t\t\tthis.$text.value = this.$input.value.substring( 1 );\n\t\t}\n\t\tthis.$display.style.backgroundColor = this.$input.value;\n\t\treturn this;\n\t}\n\n}\n\nclass FunctionController extends Controller {\n\n\tconstructor( parent, object, property ) {\n\n\t\tsuper( parent, object, property, 'function' );\n\n\t\t// Buttons are the only case where widget contains name\n\t\tthis.$button = document.createElement( 'button' );\n\t\tthis.$button.appendChild( this.$name );\n\t\tthis.$widget.appendChild( this.$button );\n\n\t\tthis.$button.addEventListener( 'click', e => {\n\t\t\te.preventDefault();\n\t\t\tthis.getValue().call( this.object );\n\t\t\tthis._callOnChange();\n\t\t} );\n\n\t\t// enables :active pseudo class on mobile\n\t\tthis.$button.addEventListener( 'touchstart', () => {}, { passive: true } );\n\n\t\tthis.$disable = this.$button;\n\n\t}\n\n}\n\nclass NumberController extends Controller {\n\n\tconstructor( parent, object, property, min, max, step ) {\n\n\t\tsuper( parent, object, property, 'number' );\n\n\t\tthis._initInput();\n\n\t\tthis.min( min );\n\t\tthis.max( max );\n\n\t\tconst stepExplicit = step !== undefined;\n\t\tthis.step( stepExplicit ? step : this._getImplicitStep(), stepExplicit );\n\n\t\tthis.updateDisplay();\n\n\t}\n\n\tdecimals( decimals ) {\n\t\tthis._decimals = decimals;\n\t\tthis.updateDisplay();\n\t\treturn this;\n\t}\n\n\tmin( min ) {\n\t\tthis._min = min;\n\t\tthis._onUpdateMinMax();\n\t\treturn this;\n\t}\n\n\tmax( max ) {\n\t\tthis._max = max;\n\t\tthis._onUpdateMinMax();\n\t\treturn this;\n\t}\n\n\tstep( step, explicit = true ) {\n\t\tthis._step = step;\n\t\tthis._stepExplicit = explicit;\n\t\treturn this;\n\t}\n\n\tupdateDisplay() {\n\n\t\tconst value = this.getValue();\n\n\t\tif ( this._hasSlider ) {\n\n\t\t\tlet percent = ( value - this._min ) / ( this._max - this._min );\n\t\t\tpercent = Math.max( 0, Math.min( percent, 1 ) );\n\n\t\t\tthis.$fill.style.width = percent * 100 + '%';\n\n\t\t}\n\n\t\tif ( !this._inputFocused ) {\n\t\t\tthis.$input.value = this._decimals === undefined ? value : value.toFixed( this._decimals );\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t_initInput() {\n\n\t\tthis.$input = document.createElement( 'input' );\n\t\tthis.$input.setAttribute( 'type', 'text' );\n\t\tthis.$input.setAttribute( 'aria-labelledby', this.$name.id );\n\n\t\t// On touch devices only, use input[type=number] to force a numeric keyboard.\n\t\t// Ideally we could use one input type everywhere, but [type=number] has quirks\n\t\t// on desktop, and [inputmode=decimal] has quirks on iOS.\n\t\t// See https://github.com/georgealways/lil-gui/pull/16\n\n\t\tconst isTouch = window.matchMedia( '(pointer: coarse)' ).matches;\n\n\t\tif ( isTouch ) {\n\t\t\tthis.$input.setAttribute( 'type', 'number' );\n\t\t\tthis.$input.setAttribute( 'step', 'any' );\n\t\t}\n\n\t\tthis.$widget.appendChild( this.$input );\n\n\t\tthis.$disable = this.$input;\n\n\t\tconst onInput = () => {\n\n\t\t\tlet value = parseFloat( this.$input.value );\n\n\t\t\tif ( isNaN( value ) ) return;\n\n\t\t\tif ( this._stepExplicit ) {\n\t\t\t\tvalue = this._snap( value );\n\t\t\t}\n\n\t\t\tthis.setValue( this._clamp( value ) );\n\n\t\t};\n\n\t\t// Keys & mouse wheel\n\t\t// ---------------------------------------------------------------------\n\n\t\tconst increment = delta => {\n\n\t\t\tconst value = parseFloat( this.$input.value );\n\n\t\t\tif ( isNaN( value ) ) return;\n\n\t\t\tthis._snapClampSetValue( value + delta );\n\n\t\t\t// Force the input to updateDisplay when it's focused\n\t\t\tthis.$input.value = this.getValue();\n\n\t\t};\n\n\t\tconst onKeyDown = e => {\n\t\t\t// Using `e.key` instead of `e.code` also catches NumpadEnter\n\t\t\tif ( e.key === 'Enter' ) {\n\t\t\t\tthis.$input.blur();\n\t\t\t}\n\t\t\tif ( e.code === 'ArrowUp' ) {\n\t\t\t\te.preventDefault();\n\t\t\t\tincrement( this._step * this._arrowKeyMultiplier( e ) );\n\t\t\t}\n\t\t\tif ( e.code === 'ArrowDown' ) {\n\t\t\t\te.preventDefault();\n\t\t\t\tincrement( this._step * this._arrowKeyMultiplier( e ) * -1 );\n\t\t\t}\n\t\t};\n\n\t\tconst onWheel = e => {\n\t\t\tif ( this._inputFocused ) {\n\t\t\t\te.preventDefault();\n\t\t\t\tincrement( this._step * this._normalizeMouseWheel( e ) );\n\t\t\t}\n\t\t};\n\n\t\t// Vertical drag\n\t\t// ---------------------------------------------------------------------\n\n\t\tlet testingForVerticalDrag = false,\n\t\t\tinitClientX,\n\t\t\tinitClientY,\n\t\t\tprevClientY,\n\t\t\tinitValue,\n\t\t\tdragDelta;\n\n\t\t// Once the mouse is dragged more than DRAG_THRESH px on any axis, we decide\n\t\t// on the user's intent: horizontal means highlight, vertical means drag.\n\t\tconst DRAG_THRESH = 5;\n\n\t\tconst onMouseDown = e => {\n\n\t\t\tinitClientX = e.clientX;\n\t\t\tinitClientY = prevClientY = e.clientY;\n\t\t\ttestingForVerticalDrag = true;\n\n\t\t\tinitValue = this.getValue();\n\t\t\tdragDelta = 0;\n\n\t\t\twindow.addEventListener( 'mousemove', onMouseMove );\n\t\t\twindow.addEventListener( 'mouseup', onMouseUp );\n\n\t\t};\n\n\t\tconst onMouseMove = e => {\n\n\t\t\tif ( testingForVerticalDrag ) {\n\n\t\t\t\tconst dx = e.clientX - initClientX;\n\t\t\t\tconst dy = e.clientY - initClientY;\n\n\t\t\t\tif ( Math.abs( dy ) > DRAG_THRESH ) {\n\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tthis.$input.blur();\n\t\t\t\t\ttestingForVerticalDrag = false;\n\t\t\t\t\tthis._setDraggingStyle( true, 'vertical' );\n\n\t\t\t\t} else if ( Math.abs( dx ) > DRAG_THRESH ) {\n\n\t\t\t\t\tonMouseUp();\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// This isn't an else so that the first move counts towards dragDelta\n\t\t\tif ( !testingForVerticalDrag ) {\n\n\t\t\t\tconst dy = e.clientY - prevClientY;\n\n\t\t\t\tdragDelta -= dy * this._step * this._arrowKeyMultiplier( e );\n\n\t\t\t\t// Clamp dragDelta so we don't have 'dead space' after dragging past bounds.\n\t\t\t\t// We're okay with the fact that bounds can be undefined here.\n\t\t\t\tif ( initValue + dragDelta > this._max ) {\n\t\t\t\t\tdragDelta = this._max - initValue;\n\t\t\t\t} else if ( initValue + dragDelta < this._min ) {\n\t\t\t\t\tdragDelta = this._min - initValue;\n\t\t\t\t}\n\n\t\t\t\tthis._snapClampSetValue( initValue + dragDelta );\n\n\t\t\t}\n\n\t\t\tprevClientY = e.clientY;\n\n\t\t};\n\n\t\tconst onMouseUp = () => {\n\t\t\tthis._setDraggingStyle( false, 'vertical' );\n\t\t\tthis._callOnFinishChange();\n\t\t\twindow.removeEventListener( 'mousemove', onMouseMove );\n\t\t\twindow.removeEventListener( 'mouseup', onMouseUp );\n\t\t};\n\n\t\t// Focus state & onFinishChange\n\t\t// ---------------------------------------------------------------------\n\n\t\tconst onFocus = () => {\n\t\t\tthis._inputFocused = true;\n\t\t};\n\n\t\tconst onBlur = () => {\n\t\t\tthis._inputFocused = false;\n\t\t\tthis.updateDisplay();\n\t\t\tthis._callOnFinishChange();\n\t\t};\n\n\t\tthis.$input.addEventListener( 'input', onInput );\n\t\tthis.$input.addEventListener( 'keydown', onKeyDown );\n\t\tthis.$input.addEventListener( 'wheel', onWheel, { passive: false } );\n\t\tthis.$input.addEventListener( 'mousedown', onMouseDown );\n\t\tthis.$input.addEventListener( 'focus', onFocus );\n\t\tthis.$input.addEventListener( 'blur', onBlur );\n\n\t}\n\n\t_initSlider() {\n\n\t\tthis._hasSlider = true;\n\n\t\t// Build DOM\n\t\t// ---------------------------------------------------------------------\n\n\t\tthis.$slider = document.createElement( 'div' );\n\t\tthis.$slider.classList.add( 'slider' );\n\n\t\tthis.$fill = document.createElement( 'div' );\n\t\tthis.$fill.classList.add( 'fill' );\n\n\t\tthis.$slider.appendChild( this.$fill );\n\t\tthis.$widget.insertBefore( this.$slider, this.$input );\n\n\t\tthis.domElement.classList.add( 'hasSlider' );\n\n\t\t// Map clientX to value\n\t\t// ---------------------------------------------------------------------\n\n\t\tconst map = ( v, a, b, c, d ) => {\n\t\t\treturn ( v - a ) / ( b - a ) * ( d - c ) + c;\n\t\t};\n\n\t\tconst setValueFromX = clientX => {\n\t\t\tconst rect = this.$slider.getBoundingClientRect();\n\t\t\tlet value = map( clientX, rect.left, rect.right, this._min, this._max );\n\t\t\tthis._snapClampSetValue( value );\n\t\t};\n\n\t\t// Mouse drag\n\t\t// ---------------------------------------------------------------------\n\n\t\tconst mouseDown = e => {\n\t\t\tthis._setDraggingStyle( true );\n\t\t\tsetValueFromX( e.clientX );\n\t\t\twindow.addEventListener( 'mousemove', mouseMove );\n\t\t\twindow.addEventListener( 'mouseup', mouseUp );\n\t\t};\n\n\t\tconst mouseMove = e => {\n\t\t\tsetValueFromX( e.clientX );\n\t\t};\n\n\t\tconst mouseUp = () => {\n\t\t\tthis._callOnFinishChange();\n\t\t\tthis._setDraggingStyle( false );\n\t\t\twindow.removeEventListener( 'mousemove', mouseMove );\n\t\t\twindow.removeEventListener( 'mouseup', mouseUp );\n\t\t};\n\n\t\t// Touch drag\n\t\t// ---------------------------------------------------------------------\n\n\t\tlet testingForScroll = false, prevClientX, prevClientY;\n\n\t\tconst beginTouchDrag = e => {\n\t\t\te.preventDefault();\n\t\t\tthis._setDraggingStyle( true );\n\t\t\tsetValueFromX( e.touches[ 0 ].clientX );\n\t\t\ttestingForScroll = false;\n\t\t};\n\n\t\tconst onTouchStart = e => {\n\n\t\t\tif ( e.touches.length > 1 ) return;\n\n\t\t\t// If we're in a scrollable container, we should wait for the first\n\t\t\t// touchmove to see if the user is trying to slide or scroll.\n\t\t\tif ( this._hasScrollBar ) {\n\n\t\t\t\tprevClientX = e.touches[ 0 ].clientX;\n\t\t\t\tprevClientY = e.touches[ 0 ].clientY;\n\t\t\t\ttestingForScroll = true;\n\n\t\t\t} else {\n\n\t\t\t\t// Otherwise, we can set the value straight away on touchstart.\n\t\t\t\tbeginTouchDrag( e );\n\n\t\t\t}\n\n\t\t\twindow.addEventListener( 'touchmove', onTouchMove, { passive: false } );\n\t\t\twindow.addEventListener( 'touchend', onTouchEnd );\n\n\t\t};\n\n\t\tconst onTouchMove = e => {\n\n\t\t\tif ( testingForScroll ) {\n\n\t\t\t\tconst dx = e.touches[ 0 ].clientX - prevClientX;\n\t\t\t\tconst dy = e.touches[ 0 ].clientY - prevClientY;\n\n\t\t\t\tif ( Math.abs( dx ) > Math.abs( dy ) ) {\n\n\t\t\t\t\t// We moved horizontally, set the value and stop checking.\n\t\t\t\t\tbeginTouchDrag( e );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// This was, in fact, an attempt to scroll. Abort.\n\t\t\t\t\twindow.removeEventListener( 'touchmove', onTouchMove );\n\t\t\t\t\twindow.removeEventListener( 'touchend', onTouchEnd );\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\te.preventDefault();\n\t\t\t\tsetValueFromX( e.touches[ 0 ].clientX );\n\n\t\t\t}\n\n\t\t};\n\n\t\tconst onTouchEnd = () => {\n\t\t\tthis._callOnFinishChange();\n\t\t\tthis._setDraggingStyle( false );\n\t\t\twindow.removeEventListener( 'touchmove', onTouchMove );\n\t\t\twindow.removeEventListener( 'touchend', onTouchEnd );\n\t\t};\n\n\t\t// Mouse wheel\n\t\t// ---------------------------------------------------------------------\n\n\t\t// We have to use a debounced function to call onFinishChange because\n\t\t// there's no way to tell when the user is \"done\" mouse-wheeling.\n\t\tconst callOnFinishChange = this._callOnFinishChange.bind( this );\n\t\tconst WHEEL_DEBOUNCE_TIME = 400;\n\t\tlet wheelFinishChangeTimeout;\n\n\t\tconst onWheel = e => {\n\n\t\t\t// ignore vertical wheels if there's a scrollbar\n\t\t\tconst isVertical = Math.abs( e.deltaX ) < Math.abs( e.deltaY );\n\t\t\tif ( isVertical && this._hasScrollBar ) return;\n\n\t\t\te.preventDefault();\n\n\t\t\t// set value\n\t\t\tconst delta = this._normalizeMouseWheel( e ) * this._step;\n\t\t\tthis._snapClampSetValue( this.getValue() + delta );\n\n\t\t\t// force the input to updateDisplay when it's focused\n\t\t\tthis.$input.value = this.getValue();\n\n\t\t\t// debounce onFinishChange\n\t\t\tclearTimeout( wheelFinishChangeTimeout );\n\t\t\twheelFinishChangeTimeout = setTimeout( callOnFinishChange, WHEEL_DEBOUNCE_TIME );\n\n\t\t};\n\n\t\tthis.$slider.addEventListener( 'mousedown', mouseDown );\n\t\tthis.$slider.addEventListener( 'touchstart', onTouchStart, { passive: false } );\n\t\tthis.$slider.addEventListener( 'wheel', onWheel, { passive: false } );\n\n\t}\n\n\t_setDraggingStyle( active, axis = 'horizontal' ) {\n\t\tif ( this.$slider ) {\n\t\t\tthis.$slider.classList.toggle( 'active', active );\n\t\t}\n\t\tdocument.body.classList.toggle( 'lil-gui-dragging', active );\n\t\tdocument.body.classList.toggle( `lil-gui-${axis}`, active );\n\t}\n\n\t_getImplicitStep() {\n\n\t\tif ( this._hasMin && this._hasMax ) {\n\t\t\treturn ( this._max - this._min ) / 1000;\n\t\t}\n\n\t\treturn 0.1;\n\n\t}\n\n\t_onUpdateMinMax() {\n\n\t\tif ( !this._hasSlider && this._hasMin && this._hasMax ) {\n\n\t\t\t// If this is the first time we're hearing about min and max\n\t\t\t// and we haven't explicitly stated what our step is, let's\n\t\t\t// update that too.\n\t\t\tif ( !this._stepExplicit ) {\n\t\t\t\tthis.step( this._getImplicitStep(), false );\n\t\t\t}\n\n\t\t\tthis._initSlider();\n\t\t\tthis.updateDisplay();\n\n\t\t}\n\n\t}\n\n\t_normalizeMouseWheel( e ) {\n\n\t\tlet { deltaX, deltaY } = e;\n\n\t\t// Safari and Chrome report weird non-integral values for a notched wheel,\n\t\t// but still expose actual lines scrolled via wheelDelta. Notched wheels\n\t\t// should behave the same way as arrow keys.\n\t\tif ( Math.floor( e.deltaY ) !== e.deltaY && e.wheelDelta ) {\n\t\t\tdeltaX = 0;\n\t\t\tdeltaY = -e.wheelDelta / 120;\n\t\t\tdeltaY *= this._stepExplicit ? 1 : 10;\n\t\t}\n\n\t\tconst wheel = deltaX + -deltaY;\n\n\t\treturn wheel;\n\n\t}\n\n\t_arrowKeyMultiplier( e ) {\n\n\t\tlet mult = this._stepExplicit ? 1 : 10;\n\n\t\tif ( e.shiftKey ) {\n\t\t\tmult *= 10;\n\t\t} else if ( e.altKey ) {\n\t\t\tmult /= 10;\n\t\t}\n\n\t\treturn mult;\n\n\t}\n\n\t_snap( value ) {\n\n\t\t// This would be the logical way to do things, but floating point errors.\n\t\t// return Math.round( value / this._step ) * this._step;\n\n\t\t// Using inverse step solves a lot of them, but not all\n\t\t// const inverseStep = 1 / this._step;\n\t\t// return Math.round( value * inverseStep ) / inverseStep;\n\n\t\t// Not happy about this, but haven't seen it break.\n\t\tconst r = Math.round( value / this._step ) * this._step;\n\t\treturn parseFloat( r.toPrecision( 15 ) );\n\n\t}\n\n\t_clamp( value ) {\n\t\t// either condition is false if min or max is undefined\n\t\tif ( value < this._min ) value = this._min;\n\t\tif ( value > this._max ) value = this._max;\n\t\treturn value;\n\t}\n\n\t_snapClampSetValue( value ) {\n\t\tthis.setValue( this._clamp( this._snap( value ) ) );\n\t}\n\n\tget _hasScrollBar() {\n\t\tconst root = this.parent.root.$children;\n\t\treturn root.scrollHeight > root.clientHeight;\n\t}\n\n\tget _hasMin() {\n\t\treturn this._min !== undefined;\n\t}\n\n\tget _hasMax() {\n\t\treturn this._max !== undefined;\n\t}\n\n}\n\nclass OptionController extends Controller {\n\n\tconstructor( parent, object, property, options ) {\n\n\t\tsuper( parent, object, property, 'option' );\n\n\t\tthis.$select = document.createElement( 'select' );\n\t\tthis.$select.setAttribute( 'aria-labelledby', this.$name.id );\n\n\t\tthis.$display = document.createElement( 'div' );\n\t\tthis.$display.classList.add( 'display' );\n\n\t\tthis.$select.addEventListener( 'change', () => {\n\t\t\tthis.setValue( this._values[ this.$select.selectedIndex ] );\n\t\t\tthis._callOnFinishChange();\n\t\t} );\n\n\t\tthis.$select.addEventListener( 'focus', () => {\n\t\t\tthis.$display.classList.add( 'focus' );\n\t\t} );\n\n\t\tthis.$select.addEventListener( 'blur', () => {\n\t\t\tthis.$display.classList.remove( 'focus' );\n\t\t} );\n\n\t\tthis.$widget.appendChild( this.$select );\n\t\tthis.$widget.appendChild( this.$display );\n\n\t\tthis.$disable = this.$select;\n\n\t\tthis.options( options );\n\n\t}\n\n\toptions( options ) {\n\n\t\tthis._values = Array.isArray( options ) ? options : Object.values( options );\n\t\tthis._names = Array.isArray( options ) ? options : Object.keys( options );\n\n\t\tthis.$select.replaceChildren();\n\n\t\tthis._names.forEach( name => {\n\t\t\tconst $option = document.createElement( 'option' );\n\t\t\t$option.textContent = name;\n\t\t\tthis.$select.appendChild( $option );\n\t\t} );\n\n\t\tthis.updateDisplay();\n\n\t\treturn this;\n\n\t}\n\n\tupdateDisplay() {\n\t\tconst value = this.getValue();\n\t\tconst index = this._values.indexOf( value );\n\t\tthis.$select.selectedIndex = index;\n\t\tthis.$display.textContent = index === -1 ? value : this._names[ index ];\n\t\treturn this;\n\t}\n\n}\n\nclass StringController extends Controller {\n\n\tconstructor( parent, object, property ) {\n\n\t\tsuper( parent, object, property, 'string' );\n\n\t\tthis.$input = document.createElement( 'input' );\n\t\tthis.$input.setAttribute( 'type', 'text' );\n\t\tthis.$input.setAttribute( 'spellcheck', 'false' );\n\t\tthis.$input.setAttribute( 'aria-labelledby', this.$name.id );\n\n\t\tthis.$input.addEventListener( 'input', () => {\n\t\t\tthis.setValue( this.$input.value );\n\t\t} );\n\n\t\tthis.$input.addEventListener( 'keydown', e => {\n\t\t\tif ( e.code === 'Enter' ) {\n\t\t\t\tthis.$input.blur();\n\t\t\t}\n\t\t} );\n\n\t\tthis.$input.addEventListener( 'blur', () => {\n\t\t\tthis._callOnFinishChange();\n\t\t} );\n\n\t\tthis.$widget.appendChild( this.$input );\n\n\t\tthis.$disable = this.$input;\n\n\t\tthis.updateDisplay();\n\n\t}\n\n\tupdateDisplay() {\n\t\tthis.$input.value = this.getValue();\n\t\treturn this;\n\t}\n\n}\n\nconst stylesheet = `.lil-gui {\n font-family: var(--font-family);\n font-size: var(--font-size);\n line-height: 1;\n font-weight: normal;\n font-style: normal;\n text-align: left;\n color: var(--text-color);\n user-select: none;\n -webkit-user-select: none;\n touch-action: manipulation;\n --background-color: #1f1f1f;\n --text-color: #ebebeb;\n --title-background-color: #111111;\n --title-text-color: #ebebeb;\n --widget-color: #424242;\n --hover-color: #4f4f4f;\n --focus-color: #595959;\n --number-color: #2cc9ff;\n --string-color: #a2db3c;\n --font-size: 11px;\n --input-font-size: 11px;\n --font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Arial, sans-serif;\n --font-family-mono: Menlo, Monaco, Consolas, \"Droid Sans Mono\", monospace;\n --padding: 4px;\n --spacing: 4px;\n --widget-height: 20px;\n --title-height: calc(var(--widget-height) + var(--spacing) * 1.25);\n --name-width: 45%;\n --slider-knob-width: 2px;\n --slider-input-width: 27%;\n --color-input-width: 27%;\n --slider-input-min-width: 45px;\n --color-input-min-width: 45px;\n --folder-indent: 7px;\n --widget-padding: 0 0 0 3px;\n --widget-border-radius: 2px;\n --checkbox-size: calc(0.75 * var(--widget-height));\n --scrollbar-width: 5px;\n}\n.lil-gui, .lil-gui * {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n}\n.lil-gui.root {\n width: var(--width, 245px);\n display: flex;\n flex-direction: column;\n background: var(--background-color);\n}\n.lil-gui.root > .title {\n background: var(--title-background-color);\n color: var(--title-text-color);\n}\n.lil-gui.root > .children {\n overflow-x: hidden;\n overflow-y: auto;\n}\n.lil-gui.root > .children::-webkit-scrollbar {\n width: var(--scrollbar-width);\n height: var(--scrollbar-width);\n background: var(--background-color);\n}\n.lil-gui.root > .children::-webkit-scrollbar-thumb {\n border-radius: var(--scrollbar-width);\n background: var(--focus-color);\n}\n@media (pointer: coarse) {\n .lil-gui.allow-touch-styles, .lil-gui.allow-touch-styles .lil-gui {\n --widget-height: 28px;\n --padding: 6px;\n --spacing: 6px;\n --font-size: 13px;\n --input-font-size: 16px;\n --folder-indent: 10px;\n --scrollbar-width: 7px;\n --slider-input-min-width: 50px;\n --color-input-min-width: 65px;\n }\n}\n.lil-gui.force-touch-styles, .lil-gui.force-touch-styles .lil-gui {\n --widget-height: 28px;\n --padding: 6px;\n --spacing: 6px;\n --font-size: 13px;\n --input-font-size: 16px;\n --folder-indent: 10px;\n --scrollbar-width: 7px;\n --slider-input-min-width: 50px;\n --color-input-min-width: 65px;\n}\n.lil-gui.autoPlace {\n max-height: 100%;\n position: fixed;\n top: 0;\n right: 15px;\n z-index: 1001;\n}\n\n.lil-gui .controller {\n display: flex;\n align-items: center;\n padding: 0 var(--padding);\n margin: var(--spacing) 0;\n}\n.lil-gui .controller.disabled {\n opacity: 0.5;\n}\n.lil-gui .controller.disabled, .lil-gui .controller.disabled * {\n pointer-events: none !important;\n}\n.lil-gui .controller > .name {\n min-width: var(--name-width);\n flex-shrink: 0;\n white-space: pre;\n padding-right: var(--spacing);\n line-height: var(--widget-height);\n}\n.lil-gui .controller .widget {\n position: relative;\n display: flex;\n align-items: center;\n width: 100%;\n min-height: var(--widget-height);\n}\n.lil-gui .controller.string input {\n color: var(--string-color);\n}\n.lil-gui .controller.boolean {\n cursor: pointer;\n}\n.lil-gui .controller.color .display {\n width: 100%;\n height: var(--widget-height);\n border-radius: var(--widget-border-radius);\n position: relative;\n}\n@media (hover: hover) {\n .lil-gui .controller.color .display:hover:before {\n content: \" \";\n display: block;\n position: absolute;\n border-radius: var(--widget-border-radius);\n border: 1px solid #fff9;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n}\n.lil-gui .controller.color input[type=color] {\n opacity: 0;\n width: 100%;\n height: 100%;\n cursor: pointer;\n}\n.lil-gui .controller.color input[type=text] {\n margin-left: var(--spacing);\n font-family: var(--font-family-mono);\n min-width: var(--color-input-min-width);\n width: var(--color-input-width);\n flex-shrink: 0;\n}\n.lil-gui .controller.option select {\n opacity: 0;\n position: absolute;\n width: 100%;\n max-width: 100%;\n}\n.lil-gui .controller.option .display {\n position: relative;\n pointer-events: none;\n border-radius: var(--widget-border-radius);\n height: var(--widget-height);\n line-height: var(--widget-height);\n max-width: 100%;\n overflow: hidden;\n word-break: break-all;\n padding-left: 0.55em;\n padding-right: 1.75em;\n background: var(--widget-color);\n}\n@media (hover: hover) {\n .lil-gui .controller.option .display.focus {\n background: var(--focus-color);\n }\n}\n.lil-gui .controller.option .display.active {\n background: var(--focus-color);\n}\n.lil-gui .controller.option .display:after {\n font-family: \"lil-gui\";\n content: \"↕\";\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n padding-right: 0.375em;\n}\n.lil-gui .controller.option .widget,\n.lil-gui .controller.option select {\n cursor: pointer;\n}\n@media (hover: hover) {\n .lil-gui .controller.option .widget:hover .display {\n background: var(--hover-color);\n }\n}\n.lil-gui .controller.number input {\n color: var(--number-color);\n}\n.lil-gui .controller.number.hasSlider input {\n margin-left: var(--spacing);\n width: var(--slider-input-width);\n min-width: var(--slider-input-min-width);\n flex-shrink: 0;\n}\n.lil-gui .controller.number .slider {\n width: 100%;\n height: var(--widget-height);\n background: var(--widget-color);\n border-radius: var(--widget-border-radius);\n padding-right: var(--slider-knob-width);\n overflow: hidden;\n cursor: ew-resize;\n touch-action: pan-y;\n}\n@media (hover: hover) {\n .lil-gui .controller.number .slider:hover {\n background: var(--hover-color);\n }\n}\n.lil-gui .controller.number .slider.active {\n background: var(--focus-color);\n}\n.lil-gui .controller.number .slider.active .fill {\n opacity: 0.95;\n}\n.lil-gui .controller.number .fill {\n height: 100%;\n border-right: var(--slider-knob-width) solid var(--number-color);\n box-sizing: content-box;\n}\n\n.lil-gui-dragging .lil-gui {\n --hover-color: var(--widget-color);\n}\n.lil-gui-dragging * {\n cursor: ew-resize !important;\n}\n\n.lil-gui-dragging.lil-gui-vertical * {\n cursor: ns-resize !important;\n}\n\n.lil-gui .title {\n height: var(--title-height);\n line-height: calc(var(--title-height) - 4px);\n font-weight: 600;\n padding: 0 var(--padding);\n -webkit-tap-highlight-color: transparent;\n cursor: pointer;\n outline: none;\n text-decoration-skip: objects;\n}\n.lil-gui .title:before {\n font-family: \"lil-gui\";\n content: \"▾\";\n padding-right: 2px;\n display: inline-block;\n}\n.lil-gui .title:active {\n background: var(--title-background-color);\n opacity: 0.75;\n}\n@media (hover: hover) {\n body:not(.lil-gui-dragging) .lil-gui .title:hover {\n background: var(--title-background-color);\n opacity: 0.85;\n }\n .lil-gui .title:focus {\n text-decoration: underline var(--focus-color);\n }\n}\n.lil-gui.root > .title:focus {\n text-decoration: none !important;\n}\n.lil-gui.closed > .title:before {\n content: \"▸\";\n}\n.lil-gui.closed > .children {\n transform: translateY(-7px);\n opacity: 0;\n}\n.lil-gui.closed:not(.transition) > .children {\n display: none;\n}\n.lil-gui.transition > .children {\n transition-duration: 300ms;\n transition-property: height, opacity, transform;\n transition-timing-function: cubic-bezier(0.2, 0.6, 0.35, 1);\n overflow: hidden;\n pointer-events: none;\n}\n.lil-gui .children:empty:before {\n content: \"Empty\";\n padding: 0 var(--padding);\n margin: var(--spacing) 0;\n display: block;\n height: var(--widget-height);\n font-style: italic;\n line-height: var(--widget-height);\n opacity: 0.5;\n}\n.lil-gui.root > .children > .lil-gui > .title {\n border: 0 solid var(--widget-color);\n border-width: 1px 0;\n transition: border-color 300ms;\n}\n.lil-gui.root > .children > .lil-gui.closed > .title {\n border-bottom-color: transparent;\n}\n.lil-gui + .controller {\n border-top: 1px solid var(--widget-color);\n margin-top: 0;\n padding-top: var(--spacing);\n}\n.lil-gui .lil-gui .lil-gui > .title {\n border: none;\n}\n.lil-gui .lil-gui .lil-gui > .children {\n border: none;\n margin-left: var(--folder-indent);\n border-left: 2px solid var(--widget-color);\n}\n.lil-gui .lil-gui .controller {\n border: none;\n}\n\n.lil-gui label, .lil-gui input, .lil-gui button {\n -webkit-tap-highlight-color: transparent;\n}\n.lil-gui input {\n border: 0;\n outline: none;\n font-family: var(--font-family);\n font-size: var(--input-font-size);\n border-radius: var(--widget-border-radius);\n height: var(--widget-height);\n background: var(--widget-color);\n color: var(--text-color);\n width: 100%;\n}\n@media (hover: hover) {\n .lil-gui input:hover {\n background: var(--hover-color);\n }\n .lil-gui input:active {\n background: var(--focus-color);\n }\n}\n.lil-gui input:disabled {\n opacity: 1;\n}\n.lil-gui input[type=text],\n.lil-gui input[type=number] {\n padding: var(--widget-padding);\n -moz-appearance: textfield;\n}\n.lil-gui input[type=text]:focus,\n.lil-gui input[type=number]:focus {\n background: var(--focus-color);\n}\n.lil-gui input[type=checkbox] {\n appearance: none;\n width: var(--checkbox-size);\n height: var(--checkbox-size);\n border-radius: var(--widget-border-radius);\n text-align: center;\n cursor: pointer;\n}\n.lil-gui input[type=checkbox]:checked:before {\n font-family: \"lil-gui\";\n content: \"✓\";\n font-size: var(--checkbox-size);\n line-height: var(--checkbox-size);\n}\n@media (hover: hover) {\n .lil-gui input[type=checkbox]:focus {\n box-shadow: inset 0 0 0 1px var(--focus-color);\n }\n}\n.lil-gui button {\n outline: none;\n cursor: pointer;\n font-family: var(--font-family);\n font-size: var(--font-size);\n color: var(--text-color);\n width: 100%;\n height: var(--widget-height);\n text-transform: none;\n background: var(--widget-color);\n border-radius: var(--widget-border-radius);\n border: none;\n}\n@media (hover: hover) {\n .lil-gui button:hover {\n background: var(--hover-color);\n }\n .lil-gui button:focus {\n box-shadow: inset 0 0 0 1px var(--focus-color);\n }\n}\n.lil-gui button:active {\n background: var(--focus-color);\n}\n\n@font-face {\n font-family: \"lil-gui\";\n src: url(\"data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAAUsAAsAAAAACJwAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAAH4AAADAImwmYE9TLzIAAAGIAAAAPwAAAGBKqH5SY21hcAAAAcgAAAD0AAACrukyyJBnbHlmAAACvAAAAF8AAACEIZpWH2hlYWQAAAMcAAAAJwAAADZfcj2zaGhlYQAAA0QAAAAYAAAAJAC5AHhobXR4AAADXAAAABAAAABMAZAAAGxvY2EAAANsAAAAFAAAACgCEgIybWF4cAAAA4AAAAAeAAAAIAEfABJuYW1lAAADoAAAASIAAAIK9SUU/XBvc3QAAATEAAAAZgAAAJCTcMc2eJxVjbEOgjAURU+hFRBK1dGRL+ALnAiToyMLEzFpnPz/eAshwSa97517c/MwwJmeB9kwPl+0cf5+uGPZXsqPu4nvZabcSZldZ6kfyWnomFY/eScKqZNWupKJO6kXN3K9uCVoL7iInPr1X5baXs3tjuMqCtzEuagm/AAlzQgPAAB4nGNgYRBlnMDAysDAYM/gBiT5oLQBAwuDJAMDEwMrMwNWEJDmmsJwgCFeXZghBcjlZMgFCzOiKOIFAB71Bb8AeJy1kjFuwkAQRZ+DwRAwBtNQRUGKQ8OdKCAWUhAgKLhIuAsVSpWz5Bbkj3dEgYiUIszqWdpZe+Z7/wB1oCYmIoboiwiLT2WjKl/jscrHfGg/pKdMkyklC5Zs2LEfHYpjcRoPzme9MWWmk3dWbK9ObkWkikOetJ554fWyoEsmdSlt+uR0pCJR34b6t/TVg1SY3sYvdf8vuiKrpyaDXDISiegp17p7579Gp3p++y7HPAiY9pmTibljrr85qSidtlg4+l25GLCaS8e6rRxNBmsnERunKbaOObRz7N72ju5vdAjYpBXHgJylOAVsMseDAPEP8LYoUHicY2BiAAEfhiAGJgZWBgZ7RnFRdnVJELCQlBSRlATJMoLV2DK4glSYs6ubq5vbKrJLSbGrgEmovDuDJVhe3VzcXFwNLCOILB/C4IuQ1xTn5FPilBTj5FPmBAB4WwoqAHicY2BkYGAA4sk1sR/j+W2+MnAzpDBgAyEMQUCSg4EJxAEAwUgFHgB4nGNgZGBgSGFggJMhDIwMqEAYAByHATJ4nGNgAIIUNEwmAABl3AGReJxjYAACIQYlBiMGJ3wQAEcQBEV4nGNgZGBgEGZgY2BiAAEQyQWEDAz/wXwGAAsPATIAAHicXdBNSsNAHAXwl35iA0UQXYnMShfS9GPZA7T7LgIu03SSpkwzYTIt1BN4Ak/gKTyAeCxfw39jZkjymzcvAwmAW/wgwHUEGDb36+jQQ3GXGot79L24jxCP4gHzF/EIr4jEIe7wxhOC3g2TMYy4Q7+Lu/SHuEd/ivt4wJd4wPxbPEKMX3GI5+DJFGaSn4qNzk8mcbKSR6xdXdhSzaOZJGtdapd4vVPbi6rP+cL7TGXOHtXKll4bY1Xl7EGnPtp7Xy2n00zyKLVHfkHBa4IcJ2oD3cgggWvt/V/FbDrUlEUJhTn/0azVWbNTNr0Ens8de1tceK9xZmfB1CPjOmPH4kitmvOubcNpmVTN3oFJyjzCvnmrwhJTzqzVj9jiSX911FjeAAB4nG3HMRKCMBBA0f0giiKi4DU8k0V2GWbIZDOh4PoWWvq6J5V8If9NVNQcaDhyouXMhY4rPTcG7jwYmXhKq8Wz+p762aNaeYXom2n3m2dLTVgsrCgFJ7OTmIkYbwIbC6vIB7WmFfAAAA==\") format(\"woff\");\n}`;\n\nfunction _injectStyles( cssContent ) {\n\tconst injected = document.createElement( 'style' );\n\tinjected.innerHTML = cssContent;\n\tconst before = document.querySelector( 'head link[rel=stylesheet], head style' );\n\tif ( before ) {\n\t\tdocument.head.insertBefore( injected, before );\n\t} else {\n\t\tdocument.head.appendChild( injected );\n\t}\n}\n\nlet stylesInjected = false;\n\nclass GUI {\n\n\t/**\n\t * Creates a panel that holds controllers.\n\t * @example\n\t * new GUI();\n\t * new GUI( { container: document.getElementById( 'custom' ) } );\n\t *\n\t * @param {object} [options]\n\t * @param {boolean} [options.autoPlace=true]\n\t * Adds the GUI to `document.body` and fixes it to the top right of the page.\n\t *\n\t * @param {HTMLElement} [options.container]\n\t * Adds the GUI to this DOM element. Overrides `autoPlace`.\n\t *\n\t * @param {number} [options.width=245]\n\t * Width of the GUI in pixels, usually set when name labels become too long. Note that you can make\n\t * name labels wider in CSS with `.lil‑gui { ‑‑name‑width: 55% }`.\n\t *\n\t * @param {string} [options.title=Controls]\n\t * Name to display in the title bar.\n\t *\n\t * @param {boolean} [options.closeFolders=false]\n\t * Pass `true` to close all folders in this GUI by default.\n\t *\n\t * @param {boolean} [options.injectStyles=true]\n\t * Injects the default stylesheet into the page if this is the first GUI.\n\t * Pass `false` to use your own stylesheet.\n\t *\n\t * @param {number} [options.touchStyles=true]\n\t * Makes controllers larger on touch devices. Pass `false` to disable touch styles.\n\t *\n\t * @param {GUI} [options.parent]\n\t * Adds this GUI as a child in another GUI. Usually this is done for you by `addFolder()`.\n\t *\n\t */\n\tconstructor( {\n\t\tparent,\n\t\tautoPlace = parent === undefined,\n\t\tcontainer,\n\t\twidth,\n\t\ttitle = 'Controls',\n\t\tcloseFolders = false,\n\t\tinjectStyles = true,\n\t\ttouchStyles = true\n\t} = {} ) {\n\n\t\t/**\n\t\t * The GUI containing this folder, or `undefined` if this is the root GUI.\n\t\t * @type {GUI}\n\t\t */\n\t\tthis.parent = parent;\n\n\t\t/**\n\t\t * The top level GUI containing this folder, or `this` if this is the root GUI.\n\t\t * @type {GUI}\n\t\t */\n\t\tthis.root = parent ? parent.root : this;\n\n\t\t/**\n\t\t * The list of controllers and folders contained by this GUI.\n\t\t * @type {Array}\n\t\t */\n\t\tthis.children = [];\n\n\t\t/**\n\t\t * The list of controllers contained by this GUI.\n\t\t * @type {Array}\n\t\t */\n\t\tthis.controllers = [];\n\n\t\t/**\n\t\t * The list of folders contained by this GUI.\n\t\t * @type {Array}\n\t\t */\n\t\tthis.folders = [];\n\n\t\t/**\n\t\t * Used to determine if the GUI is closed. Use `gui.open()` or `gui.close()` to change this.\n\t\t * @type {boolean}\n\t\t */\n\t\tthis._closed = false;\n\n\t\t/**\n\t\t * Used to determine if the GUI is hidden. Use `gui.show()` or `gui.hide()` to change this.\n\t\t * @type {boolean}\n\t\t */\n\t\tthis._hidden = false;\n\n\t\t/**\n\t\t * The outermost container element.\n\t\t * @type {HTMLElement}\n\t\t */\n\t\tthis.domElement = document.createElement( 'div' );\n\t\tthis.domElement.classList.add( 'lil-gui' );\n\n\t\t/**\n\t\t * The DOM element that contains the title.\n\t\t * @type {HTMLElement}\n\t\t */\n\t\tthis.$title = document.createElement( 'div' );\n\t\tthis.$title.classList.add( 'title' );\n\t\tthis.$title.setAttribute( 'role', 'button' );\n\t\tthis.$title.setAttribute( 'aria-expanded', true );\n\t\tthis.$title.setAttribute( 'tabindex', 0 );\n\n\t\tthis.$title.addEventListener( 'click', () => this.openAnimated( this._closed ) );\n\t\tthis.$title.addEventListener( 'keydown', e => {\n\t\t\tif ( e.code === 'Enter' || e.code === 'Space' ) {\n\t\t\t\te.preventDefault();\n\t\t\t\tthis.$title.click();\n\t\t\t}\n\t\t} );\n\n\t\t// enables :active pseudo class on mobile\n\t\tthis.$title.addEventListener( 'touchstart', () => {}, { passive: true } );\n\n\t\t/**\n\t\t * The DOM element that contains children.\n\t\t * @type {HTMLElement}\n\t\t */\n\t\tthis.$children = document.createElement( 'div' );\n\t\tthis.$children.classList.add( 'children' );\n\n\t\tthis.domElement.appendChild( this.$title );\n\t\tthis.domElement.appendChild( this.$children );\n\n\t\tthis.title( title );\n\n\t\tif ( this.parent ) {\n\n\t\t\tthis.parent.children.push( this );\n\t\t\tthis.parent.folders.push( this );\n\n\t\t\tthis.parent.$children.appendChild( this.domElement );\n\n\t\t\t// Stop the constructor early, everything onward only applies to root GUI's\n\t\t\treturn;\n\n\t\t}\n\n\t\tthis.domElement.classList.add( 'root' );\n\n\t\tif ( touchStyles ) {\n\t\t\tthis.domElement.classList.add( 'allow-touch-styles' );\n\t\t}\n\n\t\t// Inject stylesheet if we haven't done that yet\n\t\tif ( !stylesInjected && injectStyles ) {\n\t\t\t_injectStyles( stylesheet );\n\t\t\tstylesInjected = true;\n\t\t}\n\n\t\tif ( container ) {\n\n\t\t\tcontainer.appendChild( this.domElement );\n\n\t\t} else if ( autoPlace ) {\n\n\t\t\tthis.domElement.classList.add( 'autoPlace' );\n\t\t\tdocument.body.appendChild( this.domElement );\n\n\t\t}\n\n\t\tif ( width ) {\n\t\t\tthis.domElement.style.setProperty( '--width', width + 'px' );\n\t\t}\n\n\t\tthis._closeFolders = closeFolders;\n\n\t}\n\n\t/**\n\t * Adds a controller to the GUI, inferring controller type using the `typeof` operator.\n\t * @example\n\t * gui.add( object, 'property' );\n\t * gui.add( object, 'number', 0, 100, 1 );\n\t * gui.add( object, 'options', [ 1, 2, 3 ] );\n\t *\n\t * @param {object} object The object the controller will modify.\n\t * @param {string} property Name of the property to control.\n\t * @param {number|object|Array} [$1] Minimum value for number controllers, or the set of\n\t * selectable values for a dropdown.\n\t * @param {number} [max] Maximum value for number controllers.\n\t * @param {number} [step] Step value for number controllers.\n\t * @returns {Controller}\n\t */\n\tadd( object, property, $1, max, step ) {\n\n\t\tif ( Object( $1 ) === $1 ) {\n\n\t\t\treturn new OptionController( this, object, property, $1 );\n\n\t\t}\n\n\t\tconst initialValue = object[ property ];\n\n\t\tswitch ( typeof initialValue ) {\n\n\t\t\tcase 'number':\n\n\t\t\t\treturn new NumberController( this, object, property, $1, max, step );\n\n\t\t\tcase 'boolean':\n\n\t\t\t\treturn new BooleanController( this, object, property );\n\n\t\t\tcase 'string':\n\n\t\t\t\treturn new StringController( this, object, property );\n\n\t\t\tcase 'function':\n\n\t\t\t\treturn new FunctionController( this, object, property );\n\n\t\t}\n\n\t\tconsole.error( `gui.add failed\n\tproperty:`, property, `\n\tobject:`, object, `\n\tvalue:`, initialValue );\n\n\t}\n\n\t/**\n\t * Adds a color controller to the GUI.\n\t * @example\n\t * params = {\n\t * \tcssColor: '#ff00ff',\n\t * \trgbColor: { r: 0, g: 0.2, b: 0.4 },\n\t * \tcustomRange: [ 0, 127, 255 ],\n\t * };\n\t *\n\t * gui.addColor( params, 'cssColor' );\n\t * gui.addColor( params, 'rgbColor' );\n\t * gui.addColor( params, 'customRange', 255 );\n\t *\n\t * @param {object} object The object the controller will modify.\n\t * @param {string} property Name of the property to control.\n\t * @param {number} rgbScale Maximum value for a color channel when using an RGB color. You may\n\t * need to set this to 255 if your colors are too bright.\n\t * @returns {Controller}\n\t */\n\taddColor( object, property, rgbScale = 1 ) {\n\t\treturn new ColorController( this, object, property, rgbScale );\n\t}\n\n\t/**\n\t * Adds a folder to the GUI, which is just another GUI. This method returns\n\t * the nested GUI so you can add controllers to it.\n\t * @example\n\t * const folder = gui.addFolder( 'Position' );\n\t * folder.add( position, 'x' );\n\t * folder.add( position, 'y' );\n\t * folder.add( position, 'z' );\n\t *\n\t * @param {string} title Name to display in the folder's title bar.\n\t * @returns {GUI}\n\t */\n\taddFolder( title ) {\n\t\tconst folder = new GUI( { parent: this, title } );\n\t\tif ( this.root._closeFolders ) folder.close();\n\t\treturn folder;\n\t}\n\n\t/**\n\t * Recalls values that were saved with `gui.save()`.\n\t * @param {object} obj\n\t * @param {boolean} recursive Pass false to exclude folders descending from this GUI.\n\t * @returns {this}\n\t */\n\tload( obj, recursive = true ) {\n\n\t\tif ( obj.controllers ) {\n\n\t\t\tthis.controllers.forEach( c => {\n\n\t\t\t\tif ( c instanceof FunctionController ) return;\n\n\t\t\t\tif ( c._name in obj.controllers ) {\n\t\t\t\t\tc.load( obj.controllers[ c._name ] );\n\t\t\t\t}\n\n\t\t\t} );\n\n\t\t}\n\n\t\tif ( recursive && obj.folders ) {\n\n\t\t\tthis.folders.forEach( f => {\n\n\t\t\t\tif ( f._title in obj.folders ) {\n\t\t\t\t\tf.load( obj.folders[ f._title ] );\n\t\t\t\t}\n\n\t\t\t} );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t/**\n\t * Returns an object mapping controller names to values. The object can be passed to `gui.load()` to\n\t * recall these values.\n\t * @example\n\t * {\n\t * \tcontrollers: {\n\t * \t\tprop1: 1,\n\t * \t\tprop2: 'value',\n\t * \t\t...\n\t * \t},\n\t * \tfolders: {\n\t * \t\tfolderName1: { controllers, folders },\n\t * \t\tfolderName2: { controllers, folders }\n\t * \t\t...\n\t * \t}\n\t * }\n\t *\n\t * @param {boolean} recursive Pass false to exclude folders descending from this GUI.\n\t * @returns {object}\n\t */\n\tsave( recursive = true ) {\n\n\t\tconst obj = {\n\t\t\tcontrollers: {},\n\t\t\tfolders: {}\n\t\t};\n\n\t\tthis.controllers.forEach( c => {\n\n\t\t\tif ( c instanceof FunctionController ) return;\n\n\t\t\tif ( c._name in obj.controllers ) {\n\t\t\t\tthrow new Error( `Cannot save GUI with duplicate property \"${c._name}\"` );\n\t\t\t}\n\n\t\t\tobj.controllers[ c._name ] = c.save();\n\n\t\t} );\n\n\t\tif ( recursive ) {\n\n\t\t\tthis.folders.forEach( f => {\n\n\t\t\t\tif ( f._title in obj.folders ) {\n\t\t\t\t\tthrow new Error( `Cannot save GUI with duplicate folder \"${f._title}\"` );\n\t\t\t\t}\n\n\t\t\t\tobj.folders[ f._title ] = f.save();\n\n\t\t\t} );\n\n\t\t}\n\n\t\treturn obj;\n\n\t}\n\n\t/**\n\t * Opens a GUI or folder. GUI and folders are open by default.\n\t * @param {boolean} open Pass false to close.\n\t * @returns {this}\n\t * @example\n\t * gui.open(); // open\n\t * gui.open( false ); // close\n\t * gui.open( gui._closed ); // toggle\n\t */\n\topen( open = true ) {\n\n\t\tthis._setClosed( !open );\n\n\t\tthis.$title.setAttribute( 'aria-expanded', !this._closed );\n\t\tthis.domElement.classList.toggle( 'closed', this._closed );\n\n\t\treturn this;\n\n\t}\n\n\t/**\n\t * Closes the GUI.\n\t * @returns {this}\n\t */\n\tclose() {\n\t\treturn this.open( false );\n\t}\n\n\t_setClosed( closed ) {\n\t\tif ( this._closed === closed ) return;\n\t\tthis._closed = closed;\n\t\tthis._callOnOpenClose( this );\n\t}\n\n\t/**\n\t * Shows the GUI after it's been hidden.\n\t * @param {boolean} show\n\t * @returns {this}\n\t * @example\n\t * gui.show();\n\t * gui.show( false ); // hide\n\t * gui.show( gui._hidden ); // toggle\n\t */\n\tshow( show = true ) {\n\n\t\tthis._hidden = !show;\n\n\t\tthis.domElement.style.display = this._hidden ? 'none' : '';\n\n\t\treturn this;\n\n\t}\n\n\t/**\n\t * Hides the GUI.\n\t * @returns {this}\n\t */\n\thide() {\n\t\treturn this.show( false );\n\t}\n\n\topenAnimated( open = true ) {\n\n\t\t// set state immediately\n\t\tthis._setClosed( !open );\n\n\t\tthis.$title.setAttribute( 'aria-expanded', !this._closed );\n\n\t\t// wait for next frame to measure $children\n\t\trequestAnimationFrame( () => {\n\n\t\t\t// explicitly set initial height for transition\n\t\t\tconst initialHeight = this.$children.clientHeight;\n\t\t\tthis.$children.style.height = initialHeight + 'px';\n\n\t\t\tthis.domElement.classList.add( 'transition' );\n\n\t\t\tconst onTransitionEnd = e => {\n\t\t\t\tif ( e.target !== this.$children ) return;\n\t\t\t\tthis.$children.style.height = '';\n\t\t\t\tthis.domElement.classList.remove( 'transition' );\n\t\t\t\tthis.$children.removeEventListener( 'transitionend', onTransitionEnd );\n\t\t\t};\n\n\t\t\tthis.$children.addEventListener( 'transitionend', onTransitionEnd );\n\n\t\t\t// todo: this is wrong if children's scrollHeight makes for a gui taller than maxHeight\n\t\t\tconst targetHeight = !open ? 0 : this.$children.scrollHeight;\n\n\t\t\tthis.domElement.classList.toggle( 'closed', !open );\n\n\t\t\trequestAnimationFrame( () => {\n\t\t\t\tthis.$children.style.height = targetHeight + 'px';\n\t\t\t} );\n\n\t\t} );\n\n\t\treturn this;\n\n\t}\n\n\t/**\n\t * Change the title of this GUI.\n\t * @param {string} title\n\t * @returns {this}\n\t */\n\ttitle( title ) {\n\t\t/**\n\t\t * Current title of the GUI. Use `gui.title( 'Title' )` to modify this value.\n\t\t * @type {string}\n\t\t */\n\t\tthis._title = title;\n\t\tthis.$title.textContent = title;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Resets all controllers to their initial values.\n\t * @param {boolean} recursive Pass false to exclude folders descending from this GUI.\n\t * @returns {this}\n\t */\n\treset( recursive = true ) {\n\t\tconst controllers = recursive ? this.controllersRecursive() : this.controllers;\n\t\tcontrollers.forEach( c => c.reset() );\n\t\treturn this;\n\t}\n\n\t/**\n\t * Pass a function to be called whenever a controller in this GUI changes.\n\t * @param {function({object:object, property:string, value:any, controller:Controller})} callback\n\t * @returns {this}\n\t * @example\n\t * gui.onChange( event => {\n\t * \tevent.object // object that was modified\n\t * \tevent.property // string, name of property\n\t * \tevent.value // new value of controller\n\t * \tevent.controller // controller that was modified\n\t * } );\n\t */\n\tonChange( callback ) {\n\t\t/**\n\t\t * Used to access the function bound to `onChange` events. Don't modify this value\n\t\t * directly. Use the `gui.onChange( callback )` method instead.\n\t\t * @type {Function}\n\t\t */\n\t\tthis._onChange = callback;\n\t\treturn this;\n\t}\n\n\t_callOnChange( controller ) {\n\n\t\tif ( this.parent ) {\n\t\t\tthis.parent._callOnChange( controller );\n\t\t}\n\n\t\tif ( this._onChange !== undefined ) {\n\t\t\tthis._onChange.call( this, {\n\t\t\t\tobject: controller.object,\n\t\t\t\tproperty: controller.property,\n\t\t\t\tvalue: controller.getValue(),\n\t\t\t\tcontroller\n\t\t\t} );\n\t\t}\n\t}\n\n\t/**\n\t * Pass a function to be called whenever a controller in this GUI has finished changing.\n\t * @param {function({object:object, property:string, value:any, controller:Controller})} callback\n\t * @returns {this}\n\t * @example\n\t * gui.onFinishChange( event => {\n\t * \tevent.object // object that was modified\n\t * \tevent.property // string, name of property\n\t * \tevent.value // new value of controller\n\t * \tevent.controller // controller that was modified\n\t * } );\n\t */\n\tonFinishChange( callback ) {\n\t\t/**\n\t\t * Used to access the function bound to `onFinishChange` events. Don't modify this value\n\t\t * directly. Use the `gui.onFinishChange( callback )` method instead.\n\t\t * @type {Function}\n\t\t */\n\t\tthis._onFinishChange = callback;\n\t\treturn this;\n\t}\n\n\t_callOnFinishChange( controller ) {\n\n\t\tif ( this.parent ) {\n\t\t\tthis.parent._callOnFinishChange( controller );\n\t\t}\n\n\t\tif ( this._onFinishChange !== undefined ) {\n\t\t\tthis._onFinishChange.call( this, {\n\t\t\t\tobject: controller.object,\n\t\t\t\tproperty: controller.property,\n\t\t\t\tvalue: controller.getValue(),\n\t\t\t\tcontroller\n\t\t\t} );\n\t\t}\n\t}\n\n\t/**\n\t * Pass a function to be called when this GUI or its descendants are opened or closed.\n\t * @param {function(GUI)} callback\n\t * @returns {this}\n\t * @example\n\t * gui.onOpenClose( changedGUI => {\n\t * \tconsole.log( changedGUI._closed );\n\t * } );\n\t */\n\tonOpenClose( callback ) {\n\t\tthis._onOpenClose = callback;\n\t\treturn this;\n\t}\n\n\t_callOnOpenClose( changedGUI ) {\n\t\tif ( this.parent ) {\n\t\t\tthis.parent._callOnOpenClose( changedGUI );\n\t\t}\n\n\t\tif ( this._onOpenClose !== undefined ) {\n\t\t\tthis._onOpenClose.call( this, changedGUI );\n\t\t}\n\t}\n\n\t/**\n\t * Destroys all DOM elements and event listeners associated with this GUI.\n\t */\n\tdestroy() {\n\n\t\tif ( this.parent ) {\n\t\t\tthis.parent.children.splice( this.parent.children.indexOf( this ), 1 );\n\t\t\tthis.parent.folders.splice( this.parent.folders.indexOf( this ), 1 );\n\t\t}\n\n\t\tif ( this.domElement.parentElement ) {\n\t\t\tthis.domElement.parentElement.removeChild( this.domElement );\n\t\t}\n\n\t\tArray.from( this.children ).forEach( c => c.destroy() );\n\n\t}\n\n\t/**\n\t * Returns an array of controllers contained by this GUI and its descendents.\n\t * @returns {Controller[]}\n\t */\n\tcontrollersRecursive() {\n\t\tlet controllers = Array.from( this.controllers );\n\t\tthis.folders.forEach( f => {\n\t\t\tcontrollers = controllers.concat( f.controllersRecursive() );\n\t\t} );\n\t\treturn controllers;\n\t}\n\n\t/**\n\t * Returns an array of folders contained by this GUI and its descendents.\n\t * @returns {GUI[]}\n\t */\n\tfoldersRecursive() {\n\t\tlet folders = Array.from( this.folders );\n\t\tthis.folders.forEach( f => {\n\t\t\tfolders = folders.concat( f.foldersRecursive() );\n\t\t} );\n\t\treturn folders;\n\t}\n\n}\n\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (GUI);\n\n\n\n//# sourceURL=webpack://MaterialXView/./node_modules/lil-gui/dist/lil-gui.esm.js?"); + +/***/ }), + +/***/ "./node_modules/three/build/three.module.js": +/*!**************************************************!*\ + !*** ./node_modules/three/build/three.module.js ***! + \**************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ACESFilmicToneMapping: () => (/* binding */ ACESFilmicToneMapping),\n/* harmony export */ AddEquation: () => (/* binding */ AddEquation),\n/* harmony export */ AddOperation: () => (/* binding */ AddOperation),\n/* harmony export */ AdditiveAnimationBlendMode: () => (/* binding */ AdditiveAnimationBlendMode),\n/* harmony export */ AdditiveBlending: () => (/* binding */ AdditiveBlending),\n/* harmony export */ AlphaFormat: () => (/* binding */ AlphaFormat),\n/* harmony export */ AlwaysDepth: () => (/* binding */ AlwaysDepth),\n/* harmony export */ AlwaysStencilFunc: () => (/* binding */ AlwaysStencilFunc),\n/* harmony export */ AmbientLight: () => (/* binding */ AmbientLight),\n/* harmony export */ AmbientLightProbe: () => (/* binding */ AmbientLightProbe),\n/* harmony export */ AnimationAction: () => (/* binding */ AnimationAction),\n/* harmony export */ AnimationClip: () => (/* binding */ AnimationClip),\n/* harmony export */ AnimationLoader: () => (/* binding */ AnimationLoader),\n/* harmony export */ AnimationMixer: () => (/* binding */ AnimationMixer),\n/* harmony export */ AnimationObjectGroup: () => (/* binding */ AnimationObjectGroup),\n/* harmony export */ AnimationUtils: () => (/* binding */ AnimationUtils),\n/* harmony export */ ArcCurve: () => (/* binding */ ArcCurve),\n/* harmony export */ ArrayCamera: () => (/* binding */ ArrayCamera),\n/* harmony export */ ArrowHelper: () => (/* binding */ ArrowHelper),\n/* harmony export */ Audio: () => (/* binding */ Audio),\n/* harmony export */ AudioAnalyser: () => (/* binding */ AudioAnalyser),\n/* harmony export */ AudioContext: () => (/* binding */ AudioContext),\n/* harmony export */ AudioListener: () => (/* binding */ AudioListener),\n/* harmony export */ AudioLoader: () => (/* binding */ AudioLoader),\n/* harmony export */ AxesHelper: () => (/* binding */ AxesHelper),\n/* harmony export */ BackSide: () => (/* binding */ BackSide),\n/* harmony export */ BasicDepthPacking: () => (/* binding */ BasicDepthPacking),\n/* harmony export */ BasicShadowMap: () => (/* binding */ BasicShadowMap),\n/* harmony export */ Bone: () => (/* binding */ Bone),\n/* harmony export */ BooleanKeyframeTrack: () => (/* binding */ BooleanKeyframeTrack),\n/* harmony export */ Box2: () => (/* binding */ Box2),\n/* harmony export */ Box3: () => (/* binding */ Box3),\n/* harmony export */ Box3Helper: () => (/* binding */ Box3Helper),\n/* harmony export */ BoxBufferGeometry: () => (/* binding */ BoxBufferGeometry),\n/* harmony export */ BoxGeometry: () => (/* binding */ BoxGeometry),\n/* harmony export */ BoxHelper: () => (/* binding */ BoxHelper),\n/* harmony export */ BufferAttribute: () => (/* binding */ BufferAttribute),\n/* harmony export */ BufferGeometry: () => (/* binding */ BufferGeometry),\n/* harmony export */ BufferGeometryLoader: () => (/* binding */ BufferGeometryLoader),\n/* harmony export */ ByteType: () => (/* binding */ ByteType),\n/* harmony export */ Cache: () => (/* binding */ Cache),\n/* harmony export */ Camera: () => (/* binding */ Camera),\n/* harmony export */ CameraHelper: () => (/* binding */ CameraHelper),\n/* harmony export */ CanvasTexture: () => (/* binding */ CanvasTexture),\n/* harmony export */ CapsuleBufferGeometry: () => (/* binding */ CapsuleBufferGeometry),\n/* harmony export */ CapsuleGeometry: () => (/* binding */ CapsuleGeometry),\n/* harmony export */ CatmullRomCurve3: () => (/* binding */ CatmullRomCurve3),\n/* harmony export */ CineonToneMapping: () => (/* binding */ CineonToneMapping),\n/* harmony export */ CircleBufferGeometry: () => (/* binding */ CircleBufferGeometry),\n/* harmony export */ CircleGeometry: () => (/* binding */ CircleGeometry),\n/* harmony export */ ClampToEdgeWrapping: () => (/* binding */ ClampToEdgeWrapping),\n/* harmony export */ Clock: () => (/* binding */ Clock),\n/* harmony export */ Color: () => (/* binding */ Color),\n/* harmony export */ ColorKeyframeTrack: () => (/* binding */ ColorKeyframeTrack),\n/* harmony export */ ColorManagement: () => (/* binding */ ColorManagement),\n/* harmony export */ CompressedArrayTexture: () => (/* binding */ CompressedArrayTexture),\n/* harmony export */ CompressedTexture: () => (/* binding */ CompressedTexture),\n/* harmony export */ CompressedTextureLoader: () => (/* binding */ CompressedTextureLoader),\n/* harmony export */ ConeBufferGeometry: () => (/* binding */ ConeBufferGeometry),\n/* harmony export */ ConeGeometry: () => (/* binding */ ConeGeometry),\n/* harmony export */ CubeCamera: () => (/* binding */ CubeCamera),\n/* harmony export */ CubeReflectionMapping: () => (/* binding */ CubeReflectionMapping),\n/* harmony export */ CubeRefractionMapping: () => (/* binding */ CubeRefractionMapping),\n/* harmony export */ CubeTexture: () => (/* binding */ CubeTexture),\n/* harmony export */ CubeTextureLoader: () => (/* binding */ CubeTextureLoader),\n/* harmony export */ CubeUVReflectionMapping: () => (/* binding */ CubeUVReflectionMapping),\n/* harmony export */ CubicBezierCurve: () => (/* binding */ CubicBezierCurve),\n/* harmony export */ CubicBezierCurve3: () => (/* binding */ CubicBezierCurve3),\n/* harmony export */ CubicInterpolant: () => (/* binding */ CubicInterpolant),\n/* harmony export */ CullFaceBack: () => (/* binding */ CullFaceBack),\n/* harmony export */ CullFaceFront: () => (/* binding */ CullFaceFront),\n/* harmony export */ CullFaceFrontBack: () => (/* binding */ CullFaceFrontBack),\n/* harmony export */ CullFaceNone: () => (/* binding */ CullFaceNone),\n/* harmony export */ Curve: () => (/* binding */ Curve),\n/* harmony export */ CurvePath: () => (/* binding */ CurvePath),\n/* harmony export */ CustomBlending: () => (/* binding */ CustomBlending),\n/* harmony export */ CustomToneMapping: () => (/* binding */ CustomToneMapping),\n/* harmony export */ CylinderBufferGeometry: () => (/* binding */ CylinderBufferGeometry),\n/* harmony export */ CylinderGeometry: () => (/* binding */ CylinderGeometry),\n/* harmony export */ Cylindrical: () => (/* binding */ Cylindrical),\n/* harmony export */ Data3DTexture: () => (/* binding */ Data3DTexture),\n/* harmony export */ DataArrayTexture: () => (/* binding */ DataArrayTexture),\n/* harmony export */ DataTexture: () => (/* binding */ DataTexture),\n/* harmony export */ DataTextureLoader: () => (/* binding */ DataTextureLoader),\n/* harmony export */ DataUtils: () => (/* binding */ DataUtils),\n/* harmony export */ DecrementStencilOp: () => (/* binding */ DecrementStencilOp),\n/* harmony export */ DecrementWrapStencilOp: () => (/* binding */ DecrementWrapStencilOp),\n/* harmony export */ DefaultLoadingManager: () => (/* binding */ DefaultLoadingManager),\n/* harmony export */ DepthFormat: () => (/* binding */ DepthFormat),\n/* harmony export */ DepthStencilFormat: () => (/* binding */ DepthStencilFormat),\n/* harmony export */ DepthTexture: () => (/* binding */ DepthTexture),\n/* harmony export */ DirectionalLight: () => (/* binding */ DirectionalLight),\n/* harmony export */ DirectionalLightHelper: () => (/* binding */ DirectionalLightHelper),\n/* harmony export */ DiscreteInterpolant: () => (/* binding */ DiscreteInterpolant),\n/* harmony export */ DisplayP3ColorSpace: () => (/* binding */ DisplayP3ColorSpace),\n/* harmony export */ DodecahedronBufferGeometry: () => (/* binding */ DodecahedronBufferGeometry),\n/* harmony export */ DodecahedronGeometry: () => (/* binding */ DodecahedronGeometry),\n/* harmony export */ DoubleSide: () => (/* binding */ DoubleSide),\n/* harmony export */ DstAlphaFactor: () => (/* binding */ DstAlphaFactor),\n/* harmony export */ DstColorFactor: () => (/* binding */ DstColorFactor),\n/* harmony export */ DynamicCopyUsage: () => (/* binding */ DynamicCopyUsage),\n/* harmony export */ DynamicDrawUsage: () => (/* binding */ DynamicDrawUsage),\n/* harmony export */ DynamicReadUsage: () => (/* binding */ DynamicReadUsage),\n/* harmony export */ EdgesGeometry: () => (/* binding */ EdgesGeometry),\n/* harmony export */ EllipseCurve: () => (/* binding */ EllipseCurve),\n/* harmony export */ EqualDepth: () => (/* binding */ EqualDepth),\n/* harmony export */ EqualStencilFunc: () => (/* binding */ EqualStencilFunc),\n/* harmony export */ EquirectangularReflectionMapping: () => (/* binding */ EquirectangularReflectionMapping),\n/* harmony export */ EquirectangularRefractionMapping: () => (/* binding */ EquirectangularRefractionMapping),\n/* harmony export */ Euler: () => (/* binding */ Euler),\n/* harmony export */ EventDispatcher: () => (/* binding */ EventDispatcher),\n/* harmony export */ ExtrudeBufferGeometry: () => (/* binding */ ExtrudeBufferGeometry),\n/* harmony export */ ExtrudeGeometry: () => (/* binding */ ExtrudeGeometry),\n/* harmony export */ FileLoader: () => (/* binding */ FileLoader),\n/* harmony export */ Float16BufferAttribute: () => (/* binding */ Float16BufferAttribute),\n/* harmony export */ Float32BufferAttribute: () => (/* binding */ Float32BufferAttribute),\n/* harmony export */ Float64BufferAttribute: () => (/* binding */ Float64BufferAttribute),\n/* harmony export */ FloatType: () => (/* binding */ FloatType),\n/* harmony export */ Fog: () => (/* binding */ Fog),\n/* harmony export */ FogExp2: () => (/* binding */ FogExp2),\n/* harmony export */ FramebufferTexture: () => (/* binding */ FramebufferTexture),\n/* harmony export */ FrontSide: () => (/* binding */ FrontSide),\n/* harmony export */ Frustum: () => (/* binding */ Frustum),\n/* harmony export */ GLBufferAttribute: () => (/* binding */ GLBufferAttribute),\n/* harmony export */ GLSL1: () => (/* binding */ GLSL1),\n/* harmony export */ GLSL3: () => (/* binding */ GLSL3),\n/* harmony export */ GreaterDepth: () => (/* binding */ GreaterDepth),\n/* harmony export */ GreaterEqualDepth: () => (/* binding */ GreaterEqualDepth),\n/* harmony export */ GreaterEqualStencilFunc: () => (/* binding */ GreaterEqualStencilFunc),\n/* harmony export */ GreaterStencilFunc: () => (/* binding */ GreaterStencilFunc),\n/* harmony export */ GridHelper: () => (/* binding */ GridHelper),\n/* harmony export */ Group: () => (/* binding */ Group),\n/* harmony export */ HalfFloatType: () => (/* binding */ HalfFloatType),\n/* harmony export */ HemisphereLight: () => (/* binding */ HemisphereLight),\n/* harmony export */ HemisphereLightHelper: () => (/* binding */ HemisphereLightHelper),\n/* harmony export */ HemisphereLightProbe: () => (/* binding */ HemisphereLightProbe),\n/* harmony export */ IcosahedronBufferGeometry: () => (/* binding */ IcosahedronBufferGeometry),\n/* harmony export */ IcosahedronGeometry: () => (/* binding */ IcosahedronGeometry),\n/* harmony export */ ImageBitmapLoader: () => (/* binding */ ImageBitmapLoader),\n/* harmony export */ ImageLoader: () => (/* binding */ ImageLoader),\n/* harmony export */ ImageUtils: () => (/* binding */ ImageUtils),\n/* harmony export */ IncrementStencilOp: () => (/* binding */ IncrementStencilOp),\n/* harmony export */ IncrementWrapStencilOp: () => (/* binding */ IncrementWrapStencilOp),\n/* harmony export */ InstancedBufferAttribute: () => (/* binding */ InstancedBufferAttribute),\n/* harmony export */ InstancedBufferGeometry: () => (/* binding */ InstancedBufferGeometry),\n/* harmony export */ InstancedInterleavedBuffer: () => (/* binding */ InstancedInterleavedBuffer),\n/* harmony export */ InstancedMesh: () => (/* binding */ InstancedMesh),\n/* harmony export */ Int16BufferAttribute: () => (/* binding */ Int16BufferAttribute),\n/* harmony export */ Int32BufferAttribute: () => (/* binding */ Int32BufferAttribute),\n/* harmony export */ Int8BufferAttribute: () => (/* binding */ Int8BufferAttribute),\n/* harmony export */ IntType: () => (/* binding */ IntType),\n/* harmony export */ InterleavedBuffer: () => (/* binding */ InterleavedBuffer),\n/* harmony export */ InterleavedBufferAttribute: () => (/* binding */ InterleavedBufferAttribute),\n/* harmony export */ Interpolant: () => (/* binding */ Interpolant),\n/* harmony export */ InterpolateDiscrete: () => (/* binding */ InterpolateDiscrete),\n/* harmony export */ InterpolateLinear: () => (/* binding */ InterpolateLinear),\n/* harmony export */ InterpolateSmooth: () => (/* binding */ InterpolateSmooth),\n/* harmony export */ InvertStencilOp: () => (/* binding */ InvertStencilOp),\n/* harmony export */ KeepStencilOp: () => (/* binding */ KeepStencilOp),\n/* harmony export */ KeyframeTrack: () => (/* binding */ KeyframeTrack),\n/* harmony export */ LOD: () => (/* binding */ LOD),\n/* harmony export */ LatheBufferGeometry: () => (/* binding */ LatheBufferGeometry),\n/* harmony export */ LatheGeometry: () => (/* binding */ LatheGeometry),\n/* harmony export */ Layers: () => (/* binding */ Layers),\n/* harmony export */ LessDepth: () => (/* binding */ LessDepth),\n/* harmony export */ LessEqualDepth: () => (/* binding */ LessEqualDepth),\n/* harmony export */ LessEqualStencilFunc: () => (/* binding */ LessEqualStencilFunc),\n/* harmony export */ LessStencilFunc: () => (/* binding */ LessStencilFunc),\n/* harmony export */ Light: () => (/* binding */ Light),\n/* harmony export */ LightProbe: () => (/* binding */ LightProbe),\n/* harmony export */ Line: () => (/* binding */ Line),\n/* harmony export */ Line3: () => (/* binding */ Line3),\n/* harmony export */ LineBasicMaterial: () => (/* binding */ LineBasicMaterial),\n/* harmony export */ LineCurve: () => (/* binding */ LineCurve),\n/* harmony export */ LineCurve3: () => (/* binding */ LineCurve3),\n/* harmony export */ LineDashedMaterial: () => (/* binding */ LineDashedMaterial),\n/* harmony export */ LineLoop: () => (/* binding */ LineLoop),\n/* harmony export */ LineSegments: () => (/* binding */ LineSegments),\n/* harmony export */ LinearEncoding: () => (/* binding */ LinearEncoding),\n/* harmony export */ LinearFilter: () => (/* binding */ LinearFilter),\n/* harmony export */ LinearInterpolant: () => (/* binding */ LinearInterpolant),\n/* harmony export */ LinearMipMapLinearFilter: () => (/* binding */ LinearMipMapLinearFilter),\n/* harmony export */ LinearMipMapNearestFilter: () => (/* binding */ LinearMipMapNearestFilter),\n/* harmony export */ LinearMipmapLinearFilter: () => (/* binding */ LinearMipmapLinearFilter),\n/* harmony export */ LinearMipmapNearestFilter: () => (/* binding */ LinearMipmapNearestFilter),\n/* harmony export */ LinearSRGBColorSpace: () => (/* binding */ LinearSRGBColorSpace),\n/* harmony export */ LinearToneMapping: () => (/* binding */ LinearToneMapping),\n/* harmony export */ Loader: () => (/* binding */ Loader),\n/* harmony export */ LoaderUtils: () => (/* binding */ LoaderUtils),\n/* harmony export */ LoadingManager: () => (/* binding */ LoadingManager),\n/* harmony export */ LoopOnce: () => (/* binding */ LoopOnce),\n/* harmony export */ LoopPingPong: () => (/* binding */ LoopPingPong),\n/* harmony export */ LoopRepeat: () => (/* binding */ LoopRepeat),\n/* harmony export */ LuminanceAlphaFormat: () => (/* binding */ LuminanceAlphaFormat),\n/* harmony export */ LuminanceFormat: () => (/* binding */ LuminanceFormat),\n/* harmony export */ MOUSE: () => (/* binding */ MOUSE),\n/* harmony export */ Material: () => (/* binding */ Material),\n/* harmony export */ MaterialLoader: () => (/* binding */ MaterialLoader),\n/* harmony export */ MathUtils: () => (/* binding */ MathUtils),\n/* harmony export */ Matrix3: () => (/* binding */ Matrix3),\n/* harmony export */ Matrix4: () => (/* binding */ Matrix4),\n/* harmony export */ MaxEquation: () => (/* binding */ MaxEquation),\n/* harmony export */ Mesh: () => (/* binding */ Mesh),\n/* harmony export */ MeshBasicMaterial: () => (/* binding */ MeshBasicMaterial),\n/* harmony export */ MeshDepthMaterial: () => (/* binding */ MeshDepthMaterial),\n/* harmony export */ MeshDistanceMaterial: () => (/* binding */ MeshDistanceMaterial),\n/* harmony export */ MeshLambertMaterial: () => (/* binding */ MeshLambertMaterial),\n/* harmony export */ MeshMatcapMaterial: () => (/* binding */ MeshMatcapMaterial),\n/* harmony export */ MeshNormalMaterial: () => (/* binding */ MeshNormalMaterial),\n/* harmony export */ MeshPhongMaterial: () => (/* binding */ MeshPhongMaterial),\n/* harmony export */ MeshPhysicalMaterial: () => (/* binding */ MeshPhysicalMaterial),\n/* harmony export */ MeshStandardMaterial: () => (/* binding */ MeshStandardMaterial),\n/* harmony export */ MeshToonMaterial: () => (/* binding */ MeshToonMaterial),\n/* harmony export */ MinEquation: () => (/* binding */ MinEquation),\n/* harmony export */ MirroredRepeatWrapping: () => (/* binding */ MirroredRepeatWrapping),\n/* harmony export */ MixOperation: () => (/* binding */ MixOperation),\n/* harmony export */ MultiplyBlending: () => (/* binding */ MultiplyBlending),\n/* harmony export */ MultiplyOperation: () => (/* binding */ MultiplyOperation),\n/* harmony export */ NearestFilter: () => (/* binding */ NearestFilter),\n/* harmony export */ NearestMipMapLinearFilter: () => (/* binding */ NearestMipMapLinearFilter),\n/* harmony export */ NearestMipMapNearestFilter: () => (/* binding */ NearestMipMapNearestFilter),\n/* harmony export */ NearestMipmapLinearFilter: () => (/* binding */ NearestMipmapLinearFilter),\n/* harmony export */ NearestMipmapNearestFilter: () => (/* binding */ NearestMipmapNearestFilter),\n/* harmony export */ NeverDepth: () => (/* binding */ NeverDepth),\n/* harmony export */ NeverStencilFunc: () => (/* binding */ NeverStencilFunc),\n/* harmony export */ NoBlending: () => (/* binding */ NoBlending),\n/* harmony export */ NoColorSpace: () => (/* binding */ NoColorSpace),\n/* harmony export */ NoToneMapping: () => (/* binding */ NoToneMapping),\n/* harmony export */ NormalAnimationBlendMode: () => (/* binding */ NormalAnimationBlendMode),\n/* harmony export */ NormalBlending: () => (/* binding */ NormalBlending),\n/* harmony export */ NotEqualDepth: () => (/* binding */ NotEqualDepth),\n/* harmony export */ NotEqualStencilFunc: () => (/* binding */ NotEqualStencilFunc),\n/* harmony export */ NumberKeyframeTrack: () => (/* binding */ NumberKeyframeTrack),\n/* harmony export */ Object3D: () => (/* binding */ Object3D),\n/* harmony export */ ObjectLoader: () => (/* binding */ ObjectLoader),\n/* harmony export */ ObjectSpaceNormalMap: () => (/* binding */ ObjectSpaceNormalMap),\n/* harmony export */ OctahedronBufferGeometry: () => (/* binding */ OctahedronBufferGeometry),\n/* harmony export */ OctahedronGeometry: () => (/* binding */ OctahedronGeometry),\n/* harmony export */ OneFactor: () => (/* binding */ OneFactor),\n/* harmony export */ OneMinusDstAlphaFactor: () => (/* binding */ OneMinusDstAlphaFactor),\n/* harmony export */ OneMinusDstColorFactor: () => (/* binding */ OneMinusDstColorFactor),\n/* harmony export */ OneMinusSrcAlphaFactor: () => (/* binding */ OneMinusSrcAlphaFactor),\n/* harmony export */ OneMinusSrcColorFactor: () => (/* binding */ OneMinusSrcColorFactor),\n/* harmony export */ OrthographicCamera: () => (/* binding */ OrthographicCamera),\n/* harmony export */ PCFShadowMap: () => (/* binding */ PCFShadowMap),\n/* harmony export */ PCFSoftShadowMap: () => (/* binding */ PCFSoftShadowMap),\n/* harmony export */ PMREMGenerator: () => (/* binding */ PMREMGenerator),\n/* harmony export */ Path: () => (/* binding */ Path),\n/* harmony export */ PerspectiveCamera: () => (/* binding */ PerspectiveCamera),\n/* harmony export */ Plane: () => (/* binding */ Plane),\n/* harmony export */ PlaneBufferGeometry: () => (/* binding */ PlaneBufferGeometry),\n/* harmony export */ PlaneGeometry: () => (/* binding */ PlaneGeometry),\n/* harmony export */ PlaneHelper: () => (/* binding */ PlaneHelper),\n/* harmony export */ PointLight: () => (/* binding */ PointLight),\n/* harmony export */ PointLightHelper: () => (/* binding */ PointLightHelper),\n/* harmony export */ Points: () => (/* binding */ Points),\n/* harmony export */ PointsMaterial: () => (/* binding */ PointsMaterial),\n/* harmony export */ PolarGridHelper: () => (/* binding */ PolarGridHelper),\n/* harmony export */ PolyhedronBufferGeometry: () => (/* binding */ PolyhedronBufferGeometry),\n/* harmony export */ PolyhedronGeometry: () => (/* binding */ PolyhedronGeometry),\n/* harmony export */ PositionalAudio: () => (/* binding */ PositionalAudio),\n/* harmony export */ PropertyBinding: () => (/* binding */ PropertyBinding),\n/* harmony export */ PropertyMixer: () => (/* binding */ PropertyMixer),\n/* harmony export */ QuadraticBezierCurve: () => (/* binding */ QuadraticBezierCurve),\n/* harmony export */ QuadraticBezierCurve3: () => (/* binding */ QuadraticBezierCurve3),\n/* harmony export */ Quaternion: () => (/* binding */ Quaternion),\n/* harmony export */ QuaternionKeyframeTrack: () => (/* binding */ QuaternionKeyframeTrack),\n/* harmony export */ QuaternionLinearInterpolant: () => (/* binding */ QuaternionLinearInterpolant),\n/* harmony export */ RED_GREEN_RGTC2_Format: () => (/* binding */ RED_GREEN_RGTC2_Format),\n/* harmony export */ RED_RGTC1_Format: () => (/* binding */ RED_RGTC1_Format),\n/* harmony export */ REVISION: () => (/* binding */ REVISION),\n/* harmony export */ RGBADepthPacking: () => (/* binding */ RGBADepthPacking),\n/* harmony export */ RGBAFormat: () => (/* binding */ RGBAFormat),\n/* harmony export */ RGBAIntegerFormat: () => (/* binding */ RGBAIntegerFormat),\n/* harmony export */ RGBA_ASTC_10x10_Format: () => (/* binding */ RGBA_ASTC_10x10_Format),\n/* harmony export */ RGBA_ASTC_10x5_Format: () => (/* binding */ RGBA_ASTC_10x5_Format),\n/* harmony export */ RGBA_ASTC_10x6_Format: () => (/* binding */ RGBA_ASTC_10x6_Format),\n/* harmony export */ RGBA_ASTC_10x8_Format: () => (/* binding */ RGBA_ASTC_10x8_Format),\n/* harmony export */ RGBA_ASTC_12x10_Format: () => (/* binding */ RGBA_ASTC_12x10_Format),\n/* harmony export */ RGBA_ASTC_12x12_Format: () => (/* binding */ RGBA_ASTC_12x12_Format),\n/* harmony export */ RGBA_ASTC_4x4_Format: () => (/* binding */ RGBA_ASTC_4x4_Format),\n/* harmony export */ RGBA_ASTC_5x4_Format: () => (/* binding */ RGBA_ASTC_5x4_Format),\n/* harmony export */ RGBA_ASTC_5x5_Format: () => (/* binding */ RGBA_ASTC_5x5_Format),\n/* harmony export */ RGBA_ASTC_6x5_Format: () => (/* binding */ RGBA_ASTC_6x5_Format),\n/* harmony export */ RGBA_ASTC_6x6_Format: () => (/* binding */ RGBA_ASTC_6x6_Format),\n/* harmony export */ RGBA_ASTC_8x5_Format: () => (/* binding */ RGBA_ASTC_8x5_Format),\n/* harmony export */ RGBA_ASTC_8x6_Format: () => (/* binding */ RGBA_ASTC_8x6_Format),\n/* harmony export */ RGBA_ASTC_8x8_Format: () => (/* binding */ RGBA_ASTC_8x8_Format),\n/* harmony export */ RGBA_BPTC_Format: () => (/* binding */ RGBA_BPTC_Format),\n/* harmony export */ RGBA_ETC2_EAC_Format: () => (/* binding */ RGBA_ETC2_EAC_Format),\n/* harmony export */ RGBA_PVRTC_2BPPV1_Format: () => (/* binding */ RGBA_PVRTC_2BPPV1_Format),\n/* harmony export */ RGBA_PVRTC_4BPPV1_Format: () => (/* binding */ RGBA_PVRTC_4BPPV1_Format),\n/* harmony export */ RGBA_S3TC_DXT1_Format: () => (/* binding */ RGBA_S3TC_DXT1_Format),\n/* harmony export */ RGBA_S3TC_DXT3_Format: () => (/* binding */ RGBA_S3TC_DXT3_Format),\n/* harmony export */ RGBA_S3TC_DXT5_Format: () => (/* binding */ RGBA_S3TC_DXT5_Format),\n/* harmony export */ RGB_ETC1_Format: () => (/* binding */ RGB_ETC1_Format),\n/* harmony export */ RGB_ETC2_Format: () => (/* binding */ RGB_ETC2_Format),\n/* harmony export */ RGB_PVRTC_2BPPV1_Format: () => (/* binding */ RGB_PVRTC_2BPPV1_Format),\n/* harmony export */ RGB_PVRTC_4BPPV1_Format: () => (/* binding */ RGB_PVRTC_4BPPV1_Format),\n/* harmony export */ RGB_S3TC_DXT1_Format: () => (/* binding */ RGB_S3TC_DXT1_Format),\n/* harmony export */ RGFormat: () => (/* binding */ RGFormat),\n/* harmony export */ RGIntegerFormat: () => (/* binding */ RGIntegerFormat),\n/* harmony export */ RawShaderMaterial: () => (/* binding */ RawShaderMaterial),\n/* harmony export */ Ray: () => (/* binding */ Ray),\n/* harmony export */ Raycaster: () => (/* binding */ Raycaster),\n/* harmony export */ RectAreaLight: () => (/* binding */ RectAreaLight),\n/* harmony export */ RedFormat: () => (/* binding */ RedFormat),\n/* harmony export */ RedIntegerFormat: () => (/* binding */ RedIntegerFormat),\n/* harmony export */ ReinhardToneMapping: () => (/* binding */ ReinhardToneMapping),\n/* harmony export */ RepeatWrapping: () => (/* binding */ RepeatWrapping),\n/* harmony export */ ReplaceStencilOp: () => (/* binding */ ReplaceStencilOp),\n/* harmony export */ ReverseSubtractEquation: () => (/* binding */ ReverseSubtractEquation),\n/* harmony export */ RingBufferGeometry: () => (/* binding */ RingBufferGeometry),\n/* harmony export */ RingGeometry: () => (/* binding */ RingGeometry),\n/* harmony export */ SIGNED_RED_GREEN_RGTC2_Format: () => (/* binding */ SIGNED_RED_GREEN_RGTC2_Format),\n/* harmony export */ SIGNED_RED_RGTC1_Format: () => (/* binding */ SIGNED_RED_RGTC1_Format),\n/* harmony export */ SRGBColorSpace: () => (/* binding */ SRGBColorSpace),\n/* harmony export */ Scene: () => (/* binding */ Scene),\n/* harmony export */ ShaderChunk: () => (/* binding */ ShaderChunk),\n/* harmony export */ ShaderLib: () => (/* binding */ ShaderLib),\n/* harmony export */ ShaderMaterial: () => (/* binding */ ShaderMaterial),\n/* harmony export */ ShadowMaterial: () => (/* binding */ ShadowMaterial),\n/* harmony export */ Shape: () => (/* binding */ Shape),\n/* harmony export */ ShapeBufferGeometry: () => (/* binding */ ShapeBufferGeometry),\n/* harmony export */ ShapeGeometry: () => (/* binding */ ShapeGeometry),\n/* harmony export */ ShapePath: () => (/* binding */ ShapePath),\n/* harmony export */ ShapeUtils: () => (/* binding */ ShapeUtils),\n/* harmony export */ ShortType: () => (/* binding */ ShortType),\n/* harmony export */ Skeleton: () => (/* binding */ Skeleton),\n/* harmony export */ SkeletonHelper: () => (/* binding */ SkeletonHelper),\n/* harmony export */ SkinnedMesh: () => (/* binding */ SkinnedMesh),\n/* harmony export */ Source: () => (/* binding */ Source),\n/* harmony export */ Sphere: () => (/* binding */ Sphere),\n/* harmony export */ SphereBufferGeometry: () => (/* binding */ SphereBufferGeometry),\n/* harmony export */ SphereGeometry: () => (/* binding */ SphereGeometry),\n/* harmony export */ Spherical: () => (/* binding */ Spherical),\n/* harmony export */ SphericalHarmonics3: () => (/* binding */ SphericalHarmonics3),\n/* harmony export */ SplineCurve: () => (/* binding */ SplineCurve),\n/* harmony export */ SpotLight: () => (/* binding */ SpotLight),\n/* harmony export */ SpotLightHelper: () => (/* binding */ SpotLightHelper),\n/* harmony export */ Sprite: () => (/* binding */ Sprite),\n/* harmony export */ SpriteMaterial: () => (/* binding */ SpriteMaterial),\n/* harmony export */ SrcAlphaFactor: () => (/* binding */ SrcAlphaFactor),\n/* harmony export */ SrcAlphaSaturateFactor: () => (/* binding */ SrcAlphaSaturateFactor),\n/* harmony export */ SrcColorFactor: () => (/* binding */ SrcColorFactor),\n/* harmony export */ StaticCopyUsage: () => (/* binding */ StaticCopyUsage),\n/* harmony export */ StaticDrawUsage: () => (/* binding */ StaticDrawUsage),\n/* harmony export */ StaticReadUsage: () => (/* binding */ StaticReadUsage),\n/* harmony export */ StereoCamera: () => (/* binding */ StereoCamera),\n/* harmony export */ StreamCopyUsage: () => (/* binding */ StreamCopyUsage),\n/* harmony export */ StreamDrawUsage: () => (/* binding */ StreamDrawUsage),\n/* harmony export */ StreamReadUsage: () => (/* binding */ StreamReadUsage),\n/* harmony export */ StringKeyframeTrack: () => (/* binding */ StringKeyframeTrack),\n/* harmony export */ SubtractEquation: () => (/* binding */ SubtractEquation),\n/* harmony export */ SubtractiveBlending: () => (/* binding */ SubtractiveBlending),\n/* harmony export */ TOUCH: () => (/* binding */ TOUCH),\n/* harmony export */ TangentSpaceNormalMap: () => (/* binding */ TangentSpaceNormalMap),\n/* harmony export */ TetrahedronBufferGeometry: () => (/* binding */ TetrahedronBufferGeometry),\n/* harmony export */ TetrahedronGeometry: () => (/* binding */ TetrahedronGeometry),\n/* harmony export */ Texture: () => (/* binding */ Texture),\n/* harmony export */ TextureLoader: () => (/* binding */ TextureLoader),\n/* harmony export */ TorusBufferGeometry: () => (/* binding */ TorusBufferGeometry),\n/* harmony export */ TorusGeometry: () => (/* binding */ TorusGeometry),\n/* harmony export */ TorusKnotBufferGeometry: () => (/* binding */ TorusKnotBufferGeometry),\n/* harmony export */ TorusKnotGeometry: () => (/* binding */ TorusKnotGeometry),\n/* harmony export */ Triangle: () => (/* binding */ Triangle),\n/* harmony export */ TriangleFanDrawMode: () => (/* binding */ TriangleFanDrawMode),\n/* harmony export */ TriangleStripDrawMode: () => (/* binding */ TriangleStripDrawMode),\n/* harmony export */ TrianglesDrawMode: () => (/* binding */ TrianglesDrawMode),\n/* harmony export */ TubeBufferGeometry: () => (/* binding */ TubeBufferGeometry),\n/* harmony export */ TubeGeometry: () => (/* binding */ TubeGeometry),\n/* harmony export */ TwoPassDoubleSide: () => (/* binding */ TwoPassDoubleSide),\n/* harmony export */ UVMapping: () => (/* binding */ UVMapping),\n/* harmony export */ Uint16BufferAttribute: () => (/* binding */ Uint16BufferAttribute),\n/* harmony export */ Uint32BufferAttribute: () => (/* binding */ Uint32BufferAttribute),\n/* harmony export */ Uint8BufferAttribute: () => (/* binding */ Uint8BufferAttribute),\n/* harmony export */ Uint8ClampedBufferAttribute: () => (/* binding */ Uint8ClampedBufferAttribute),\n/* harmony export */ Uniform: () => (/* binding */ Uniform),\n/* harmony export */ UniformsGroup: () => (/* binding */ UniformsGroup),\n/* harmony export */ UniformsLib: () => (/* binding */ UniformsLib),\n/* harmony export */ UniformsUtils: () => (/* binding */ UniformsUtils),\n/* harmony export */ UnsignedByteType: () => (/* binding */ UnsignedByteType),\n/* harmony export */ UnsignedInt248Type: () => (/* binding */ UnsignedInt248Type),\n/* harmony export */ UnsignedIntType: () => (/* binding */ UnsignedIntType),\n/* harmony export */ UnsignedShort4444Type: () => (/* binding */ UnsignedShort4444Type),\n/* harmony export */ UnsignedShort5551Type: () => (/* binding */ UnsignedShort5551Type),\n/* harmony export */ UnsignedShortType: () => (/* binding */ UnsignedShortType),\n/* harmony export */ VSMShadowMap: () => (/* binding */ VSMShadowMap),\n/* harmony export */ Vector2: () => (/* binding */ Vector2),\n/* harmony export */ Vector3: () => (/* binding */ Vector3),\n/* harmony export */ Vector4: () => (/* binding */ Vector4),\n/* harmony export */ VectorKeyframeTrack: () => (/* binding */ VectorKeyframeTrack),\n/* harmony export */ VideoTexture: () => (/* binding */ VideoTexture),\n/* harmony export */ WebGL1Renderer: () => (/* binding */ WebGL1Renderer),\n/* harmony export */ WebGL3DRenderTarget: () => (/* binding */ WebGL3DRenderTarget),\n/* harmony export */ WebGLArrayRenderTarget: () => (/* binding */ WebGLArrayRenderTarget),\n/* harmony export */ WebGLCubeRenderTarget: () => (/* binding */ WebGLCubeRenderTarget),\n/* harmony export */ WebGLMultipleRenderTargets: () => (/* binding */ WebGLMultipleRenderTargets),\n/* harmony export */ WebGLRenderTarget: () => (/* binding */ WebGLRenderTarget),\n/* harmony export */ WebGLRenderer: () => (/* binding */ WebGLRenderer),\n/* harmony export */ WebGLUtils: () => (/* binding */ WebGLUtils),\n/* harmony export */ WireframeGeometry: () => (/* binding */ WireframeGeometry),\n/* harmony export */ WrapAroundEnding: () => (/* binding */ WrapAroundEnding),\n/* harmony export */ ZeroCurvatureEnding: () => (/* binding */ ZeroCurvatureEnding),\n/* harmony export */ ZeroFactor: () => (/* binding */ ZeroFactor),\n/* harmony export */ ZeroSlopeEnding: () => (/* binding */ ZeroSlopeEnding),\n/* harmony export */ ZeroStencilOp: () => (/* binding */ ZeroStencilOp),\n/* harmony export */ _SRGBAFormat: () => (/* binding */ _SRGBAFormat),\n/* harmony export */ sRGBEncoding: () => (/* binding */ sRGBEncoding)\n/* harmony export */ });\n/**\n * @license\n * Copyright 2010-2023 Three.js Authors\n * SPDX-License-Identifier: MIT\n */\nconst REVISION = '152';\n\nconst MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };\nconst TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };\nconst CullFaceNone = 0;\nconst CullFaceBack = 1;\nconst CullFaceFront = 2;\nconst CullFaceFrontBack = 3;\nconst BasicShadowMap = 0;\nconst PCFShadowMap = 1;\nconst PCFSoftShadowMap = 2;\nconst VSMShadowMap = 3;\nconst FrontSide = 0;\nconst BackSide = 1;\nconst DoubleSide = 2;\nconst TwoPassDoubleSide = 2; // r149\nconst NoBlending = 0;\nconst NormalBlending = 1;\nconst AdditiveBlending = 2;\nconst SubtractiveBlending = 3;\nconst MultiplyBlending = 4;\nconst CustomBlending = 5;\nconst AddEquation = 100;\nconst SubtractEquation = 101;\nconst ReverseSubtractEquation = 102;\nconst MinEquation = 103;\nconst MaxEquation = 104;\nconst ZeroFactor = 200;\nconst OneFactor = 201;\nconst SrcColorFactor = 202;\nconst OneMinusSrcColorFactor = 203;\nconst SrcAlphaFactor = 204;\nconst OneMinusSrcAlphaFactor = 205;\nconst DstAlphaFactor = 206;\nconst OneMinusDstAlphaFactor = 207;\nconst DstColorFactor = 208;\nconst OneMinusDstColorFactor = 209;\nconst SrcAlphaSaturateFactor = 210;\nconst NeverDepth = 0;\nconst AlwaysDepth = 1;\nconst LessDepth = 2;\nconst LessEqualDepth = 3;\nconst EqualDepth = 4;\nconst GreaterEqualDepth = 5;\nconst GreaterDepth = 6;\nconst NotEqualDepth = 7;\nconst MultiplyOperation = 0;\nconst MixOperation = 1;\nconst AddOperation = 2;\nconst NoToneMapping = 0;\nconst LinearToneMapping = 1;\nconst ReinhardToneMapping = 2;\nconst CineonToneMapping = 3;\nconst ACESFilmicToneMapping = 4;\nconst CustomToneMapping = 5;\n\nconst UVMapping = 300;\nconst CubeReflectionMapping = 301;\nconst CubeRefractionMapping = 302;\nconst EquirectangularReflectionMapping = 303;\nconst EquirectangularRefractionMapping = 304;\nconst CubeUVReflectionMapping = 306;\nconst RepeatWrapping = 1000;\nconst ClampToEdgeWrapping = 1001;\nconst MirroredRepeatWrapping = 1002;\nconst NearestFilter = 1003;\nconst NearestMipmapNearestFilter = 1004;\nconst NearestMipMapNearestFilter = 1004;\nconst NearestMipmapLinearFilter = 1005;\nconst NearestMipMapLinearFilter = 1005;\nconst LinearFilter = 1006;\nconst LinearMipmapNearestFilter = 1007;\nconst LinearMipMapNearestFilter = 1007;\nconst LinearMipmapLinearFilter = 1008;\nconst LinearMipMapLinearFilter = 1008;\nconst UnsignedByteType = 1009;\nconst ByteType = 1010;\nconst ShortType = 1011;\nconst UnsignedShortType = 1012;\nconst IntType = 1013;\nconst UnsignedIntType = 1014;\nconst FloatType = 1015;\nconst HalfFloatType = 1016;\nconst UnsignedShort4444Type = 1017;\nconst UnsignedShort5551Type = 1018;\nconst UnsignedInt248Type = 1020;\nconst AlphaFormat = 1021;\nconst RGBAFormat = 1023;\nconst LuminanceFormat = 1024;\nconst LuminanceAlphaFormat = 1025;\nconst DepthFormat = 1026;\nconst DepthStencilFormat = 1027;\nconst RedFormat = 1028;\nconst RedIntegerFormat = 1029;\nconst RGFormat = 1030;\nconst RGIntegerFormat = 1031;\nconst RGBAIntegerFormat = 1033;\n\nconst RGB_S3TC_DXT1_Format = 33776;\nconst RGBA_S3TC_DXT1_Format = 33777;\nconst RGBA_S3TC_DXT3_Format = 33778;\nconst RGBA_S3TC_DXT5_Format = 33779;\nconst RGB_PVRTC_4BPPV1_Format = 35840;\nconst RGB_PVRTC_2BPPV1_Format = 35841;\nconst RGBA_PVRTC_4BPPV1_Format = 35842;\nconst RGBA_PVRTC_2BPPV1_Format = 35843;\nconst RGB_ETC1_Format = 36196;\nconst RGB_ETC2_Format = 37492;\nconst RGBA_ETC2_EAC_Format = 37496;\nconst RGBA_ASTC_4x4_Format = 37808;\nconst RGBA_ASTC_5x4_Format = 37809;\nconst RGBA_ASTC_5x5_Format = 37810;\nconst RGBA_ASTC_6x5_Format = 37811;\nconst RGBA_ASTC_6x6_Format = 37812;\nconst RGBA_ASTC_8x5_Format = 37813;\nconst RGBA_ASTC_8x6_Format = 37814;\nconst RGBA_ASTC_8x8_Format = 37815;\nconst RGBA_ASTC_10x5_Format = 37816;\nconst RGBA_ASTC_10x6_Format = 37817;\nconst RGBA_ASTC_10x8_Format = 37818;\nconst RGBA_ASTC_10x10_Format = 37819;\nconst RGBA_ASTC_12x10_Format = 37820;\nconst RGBA_ASTC_12x12_Format = 37821;\nconst RGBA_BPTC_Format = 36492;\nconst RED_RGTC1_Format = 36283;\nconst SIGNED_RED_RGTC1_Format = 36284;\nconst RED_GREEN_RGTC2_Format = 36285;\nconst SIGNED_RED_GREEN_RGTC2_Format = 36286;\nconst LoopOnce = 2200;\nconst LoopRepeat = 2201;\nconst LoopPingPong = 2202;\nconst InterpolateDiscrete = 2300;\nconst InterpolateLinear = 2301;\nconst InterpolateSmooth = 2302;\nconst ZeroCurvatureEnding = 2400;\nconst ZeroSlopeEnding = 2401;\nconst WrapAroundEnding = 2402;\nconst NormalAnimationBlendMode = 2500;\nconst AdditiveAnimationBlendMode = 2501;\nconst TrianglesDrawMode = 0;\nconst TriangleStripDrawMode = 1;\nconst TriangleFanDrawMode = 2;\n/** @deprecated Use LinearSRGBColorSpace or NoColorSpace in three.js r152+. */\nconst LinearEncoding = 3000;\n/** @deprecated Use SRGBColorSpace in three.js r152+. */\nconst sRGBEncoding = 3001;\nconst BasicDepthPacking = 3200;\nconst RGBADepthPacking = 3201;\nconst TangentSpaceNormalMap = 0;\nconst ObjectSpaceNormalMap = 1;\n\n// Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.\nconst NoColorSpace = '';\nconst SRGBColorSpace = 'srgb';\nconst LinearSRGBColorSpace = 'srgb-linear';\nconst DisplayP3ColorSpace = 'display-p3';\n\nconst ZeroStencilOp = 0;\nconst KeepStencilOp = 7680;\nconst ReplaceStencilOp = 7681;\nconst IncrementStencilOp = 7682;\nconst DecrementStencilOp = 7683;\nconst IncrementWrapStencilOp = 34055;\nconst DecrementWrapStencilOp = 34056;\nconst InvertStencilOp = 5386;\n\nconst NeverStencilFunc = 512;\nconst LessStencilFunc = 513;\nconst EqualStencilFunc = 514;\nconst LessEqualStencilFunc = 515;\nconst GreaterStencilFunc = 516;\nconst NotEqualStencilFunc = 517;\nconst GreaterEqualStencilFunc = 518;\nconst AlwaysStencilFunc = 519;\n\nconst StaticDrawUsage = 35044;\nconst DynamicDrawUsage = 35048;\nconst StreamDrawUsage = 35040;\nconst StaticReadUsage = 35045;\nconst DynamicReadUsage = 35049;\nconst StreamReadUsage = 35041;\nconst StaticCopyUsage = 35046;\nconst DynamicCopyUsage = 35050;\nconst StreamCopyUsage = 35042;\n\nconst GLSL1 = '100';\nconst GLSL3 = '300 es';\n\nconst _SRGBAFormat = 1035; // fallback for WebGL 1\n\n/**\n * https://github.com/mrdoob/eventdispatcher.js/\n */\n\nclass EventDispatcher {\n\n\taddEventListener( type, listener ) {\n\n\t\tif ( this._listeners === undefined ) this._listeners = {};\n\n\t\tconst listeners = this._listeners;\n\n\t\tif ( listeners[ type ] === undefined ) {\n\n\t\t\tlisteners[ type ] = [];\n\n\t\t}\n\n\t\tif ( listeners[ type ].indexOf( listener ) === - 1 ) {\n\n\t\t\tlisteners[ type ].push( listener );\n\n\t\t}\n\n\t}\n\n\thasEventListener( type, listener ) {\n\n\t\tif ( this._listeners === undefined ) return false;\n\n\t\tconst listeners = this._listeners;\n\n\t\treturn listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;\n\n\t}\n\n\tremoveEventListener( type, listener ) {\n\n\t\tif ( this._listeners === undefined ) return;\n\n\t\tconst listeners = this._listeners;\n\t\tconst listenerArray = listeners[ type ];\n\n\t\tif ( listenerArray !== undefined ) {\n\n\t\t\tconst index = listenerArray.indexOf( listener );\n\n\t\t\tif ( index !== - 1 ) {\n\n\t\t\t\tlistenerArray.splice( index, 1 );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tdispatchEvent( event ) {\n\n\t\tif ( this._listeners === undefined ) return;\n\n\t\tconst listeners = this._listeners;\n\t\tconst listenerArray = listeners[ event.type ];\n\n\t\tif ( listenerArray !== undefined ) {\n\n\t\t\tevent.target = this;\n\n\t\t\t// Make a copy, in case listeners are removed while iterating.\n\t\t\tconst array = listenerArray.slice( 0 );\n\n\t\t\tfor ( let i = 0, l = array.length; i < l; i ++ ) {\n\n\t\t\t\tarray[ i ].call( this, event );\n\n\t\t\t}\n\n\t\t\tevent.target = null;\n\n\t\t}\n\n\t}\n\n}\n\nconst _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];\n\nlet _seed = 1234567;\n\n\nconst DEG2RAD = Math.PI / 180;\nconst RAD2DEG = 180 / Math.PI;\n\n// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136\nfunction generateUUID() {\n\n\tconst d0 = Math.random() * 0xffffffff | 0;\n\tconst d1 = Math.random() * 0xffffffff | 0;\n\tconst d2 = Math.random() * 0xffffffff | 0;\n\tconst d3 = Math.random() * 0xffffffff | 0;\n\tconst uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +\n\t\t\t_lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +\n\t\t\t_lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +\n\t\t\t_lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];\n\n\t// .toLowerCase() here flattens concatenated strings to save heap memory space.\n\treturn uuid.toLowerCase();\n\n}\n\nfunction clamp( value, min, max ) {\n\n\treturn Math.max( min, Math.min( max, value ) );\n\n}\n\n// compute euclidean modulo of m % n\n// https://en.wikipedia.org/wiki/Modulo_operation\nfunction euclideanModulo( n, m ) {\n\n\treturn ( ( n % m ) + m ) % m;\n\n}\n\n// Linear mapping from range to range \nfunction mapLinear( x, a1, a2, b1, b2 ) {\n\n\treturn b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );\n\n}\n\n// https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/\nfunction inverseLerp( x, y, value ) {\n\n\tif ( x !== y ) {\n\n\t\treturn ( value - x ) / ( y - x );\n\n\t} else {\n\n\t\treturn 0;\n\n\t}\n\n}\n\n// https://en.wikipedia.org/wiki/Linear_interpolation\nfunction lerp( x, y, t ) {\n\n\treturn ( 1 - t ) * x + t * y;\n\n}\n\n// http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/\nfunction damp( x, y, lambda, dt ) {\n\n\treturn lerp( x, y, 1 - Math.exp( - lambda * dt ) );\n\n}\n\n// https://www.desmos.com/calculator/vcsjnyz7x4\nfunction pingpong( x, length = 1 ) {\n\n\treturn length - Math.abs( euclideanModulo( x, length * 2 ) - length );\n\n}\n\n// http://en.wikipedia.org/wiki/Smoothstep\nfunction smoothstep( x, min, max ) {\n\n\tif ( x <= min ) return 0;\n\tif ( x >= max ) return 1;\n\n\tx = ( x - min ) / ( max - min );\n\n\treturn x * x * ( 3 - 2 * x );\n\n}\n\nfunction smootherstep( x, min, max ) {\n\n\tif ( x <= min ) return 0;\n\tif ( x >= max ) return 1;\n\n\tx = ( x - min ) / ( max - min );\n\n\treturn x * x * x * ( x * ( x * 6 - 15 ) + 10 );\n\n}\n\n// Random integer from interval\nfunction randInt( low, high ) {\n\n\treturn low + Math.floor( Math.random() * ( high - low + 1 ) );\n\n}\n\n// Random float from interval\nfunction randFloat( low, high ) {\n\n\treturn low + Math.random() * ( high - low );\n\n}\n\n// Random float from <-range/2, range/2> interval\nfunction randFloatSpread( range ) {\n\n\treturn range * ( 0.5 - Math.random() );\n\n}\n\n// Deterministic pseudo-random float in the interval [ 0, 1 ]\nfunction seededRandom( s ) {\n\n\tif ( s !== undefined ) _seed = s;\n\n\t// Mulberry32 generator\n\n\tlet t = _seed += 0x6D2B79F5;\n\n\tt = Math.imul( t ^ t >>> 15, t | 1 );\n\n\tt ^= t + Math.imul( t ^ t >>> 7, t | 61 );\n\n\treturn ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;\n\n}\n\nfunction degToRad( degrees ) {\n\n\treturn degrees * DEG2RAD;\n\n}\n\nfunction radToDeg( radians ) {\n\n\treturn radians * RAD2DEG;\n\n}\n\nfunction isPowerOfTwo( value ) {\n\n\treturn ( value & ( value - 1 ) ) === 0 && value !== 0;\n\n}\n\nfunction ceilPowerOfTwo( value ) {\n\n\treturn Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );\n\n}\n\nfunction floorPowerOfTwo( value ) {\n\n\treturn Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );\n\n}\n\nfunction setQuaternionFromProperEuler( q, a, b, c, order ) {\n\n\t// Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles\n\n\t// rotations are applied to the axes in the order specified by 'order'\n\t// rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'\n\t// angles are in radians\n\n\tconst cos = Math.cos;\n\tconst sin = Math.sin;\n\n\tconst c2 = cos( b / 2 );\n\tconst s2 = sin( b / 2 );\n\n\tconst c13 = cos( ( a + c ) / 2 );\n\tconst s13 = sin( ( a + c ) / 2 );\n\n\tconst c1_3 = cos( ( a - c ) / 2 );\n\tconst s1_3 = sin( ( a - c ) / 2 );\n\n\tconst c3_1 = cos( ( c - a ) / 2 );\n\tconst s3_1 = sin( ( c - a ) / 2 );\n\n\tswitch ( order ) {\n\n\t\tcase 'XYX':\n\t\t\tq.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );\n\t\t\tbreak;\n\n\t\tcase 'YZY':\n\t\t\tq.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );\n\t\t\tbreak;\n\n\t\tcase 'ZXZ':\n\t\t\tq.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );\n\t\t\tbreak;\n\n\t\tcase 'XZX':\n\t\t\tq.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );\n\t\t\tbreak;\n\n\t\tcase 'YXY':\n\t\t\tq.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );\n\t\t\tbreak;\n\n\t\tcase 'ZYZ':\n\t\t\tq.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tconsole.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );\n\n\t}\n\n}\n\nfunction denormalize( value, array ) {\n\n\tswitch ( array.constructor ) {\n\n\t\tcase Float32Array:\n\n\t\t\treturn value;\n\n\t\tcase Uint16Array:\n\n\t\t\treturn value / 65535.0;\n\n\t\tcase Uint8Array:\n\n\t\t\treturn value / 255.0;\n\n\t\tcase Int16Array:\n\n\t\t\treturn Math.max( value / 32767.0, - 1.0 );\n\n\t\tcase Int8Array:\n\n\t\t\treturn Math.max( value / 127.0, - 1.0 );\n\n\t\tdefault:\n\n\t\t\tthrow new Error( 'Invalid component type.' );\n\n\t}\n\n}\n\nfunction normalize( value, array ) {\n\n\tswitch ( array.constructor ) {\n\n\t\tcase Float32Array:\n\n\t\t\treturn value;\n\n\t\tcase Uint16Array:\n\n\t\t\treturn Math.round( value * 65535.0 );\n\n\t\tcase Uint8Array:\n\n\t\t\treturn Math.round( value * 255.0 );\n\n\t\tcase Int16Array:\n\n\t\t\treturn Math.round( value * 32767.0 );\n\n\t\tcase Int8Array:\n\n\t\t\treturn Math.round( value * 127.0 );\n\n\t\tdefault:\n\n\t\t\tthrow new Error( 'Invalid component type.' );\n\n\t}\n\n}\n\nconst MathUtils = {\n\tDEG2RAD: DEG2RAD,\n\tRAD2DEG: RAD2DEG,\n\tgenerateUUID: generateUUID,\n\tclamp: clamp,\n\teuclideanModulo: euclideanModulo,\n\tmapLinear: mapLinear,\n\tinverseLerp: inverseLerp,\n\tlerp: lerp,\n\tdamp: damp,\n\tpingpong: pingpong,\n\tsmoothstep: smoothstep,\n\tsmootherstep: smootherstep,\n\trandInt: randInt,\n\trandFloat: randFloat,\n\trandFloatSpread: randFloatSpread,\n\tseededRandom: seededRandom,\n\tdegToRad: degToRad,\n\tradToDeg: radToDeg,\n\tisPowerOfTwo: isPowerOfTwo,\n\tceilPowerOfTwo: ceilPowerOfTwo,\n\tfloorPowerOfTwo: floorPowerOfTwo,\n\tsetQuaternionFromProperEuler: setQuaternionFromProperEuler,\n\tnormalize: normalize,\n\tdenormalize: denormalize\n};\n\nclass Vector2 {\n\n\tconstructor( x = 0, y = 0 ) {\n\n\t\tVector2.prototype.isVector2 = true;\n\n\t\tthis.x = x;\n\t\tthis.y = y;\n\n\t}\n\n\tget width() {\n\n\t\treturn this.x;\n\n\t}\n\n\tset width( value ) {\n\n\t\tthis.x = value;\n\n\t}\n\n\tget height() {\n\n\t\treturn this.y;\n\n\t}\n\n\tset height( value ) {\n\n\t\tthis.y = value;\n\n\t}\n\n\tset( x, y ) {\n\n\t\tthis.x = x;\n\t\tthis.y = y;\n\n\t\treturn this;\n\n\t}\n\n\tsetScalar( scalar ) {\n\n\t\tthis.x = scalar;\n\t\tthis.y = scalar;\n\n\t\treturn this;\n\n\t}\n\n\tsetX( x ) {\n\n\t\tthis.x = x;\n\n\t\treturn this;\n\n\t}\n\n\tsetY( y ) {\n\n\t\tthis.y = y;\n\n\t\treturn this;\n\n\t}\n\n\tsetComponent( index, value ) {\n\n\t\tswitch ( index ) {\n\n\t\t\tcase 0: this.x = value; break;\n\t\t\tcase 1: this.y = value; break;\n\t\t\tdefault: throw new Error( 'index is out of range: ' + index );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tgetComponent( index ) {\n\n\t\tswitch ( index ) {\n\n\t\t\tcase 0: return this.x;\n\t\t\tcase 1: return this.y;\n\t\t\tdefault: throw new Error( 'index is out of range: ' + index );\n\n\t\t}\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor( this.x, this.y );\n\n\t}\n\n\tcopy( v ) {\n\n\t\tthis.x = v.x;\n\t\tthis.y = v.y;\n\n\t\treturn this;\n\n\t}\n\n\tadd( v ) {\n\n\t\tthis.x += v.x;\n\t\tthis.y += v.y;\n\n\t\treturn this;\n\n\t}\n\n\taddScalar( s ) {\n\n\t\tthis.x += s;\n\t\tthis.y += s;\n\n\t\treturn this;\n\n\t}\n\n\taddVectors( a, b ) {\n\n\t\tthis.x = a.x + b.x;\n\t\tthis.y = a.y + b.y;\n\n\t\treturn this;\n\n\t}\n\n\taddScaledVector( v, s ) {\n\n\t\tthis.x += v.x * s;\n\t\tthis.y += v.y * s;\n\n\t\treturn this;\n\n\t}\n\n\tsub( v ) {\n\n\t\tthis.x -= v.x;\n\t\tthis.y -= v.y;\n\n\t\treturn this;\n\n\t}\n\n\tsubScalar( s ) {\n\n\t\tthis.x -= s;\n\t\tthis.y -= s;\n\n\t\treturn this;\n\n\t}\n\n\tsubVectors( a, b ) {\n\n\t\tthis.x = a.x - b.x;\n\t\tthis.y = a.y - b.y;\n\n\t\treturn this;\n\n\t}\n\n\tmultiply( v ) {\n\n\t\tthis.x *= v.x;\n\t\tthis.y *= v.y;\n\n\t\treturn this;\n\n\t}\n\n\tmultiplyScalar( scalar ) {\n\n\t\tthis.x *= scalar;\n\t\tthis.y *= scalar;\n\n\t\treturn this;\n\n\t}\n\n\tdivide( v ) {\n\n\t\tthis.x /= v.x;\n\t\tthis.y /= v.y;\n\n\t\treturn this;\n\n\t}\n\n\tdivideScalar( scalar ) {\n\n\t\treturn this.multiplyScalar( 1 / scalar );\n\n\t}\n\n\tapplyMatrix3( m ) {\n\n\t\tconst x = this.x, y = this.y;\n\t\tconst e = m.elements;\n\n\t\tthis.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];\n\t\tthis.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];\n\n\t\treturn this;\n\n\t}\n\n\tmin( v ) {\n\n\t\tthis.x = Math.min( this.x, v.x );\n\t\tthis.y = Math.min( this.y, v.y );\n\n\t\treturn this;\n\n\t}\n\n\tmax( v ) {\n\n\t\tthis.x = Math.max( this.x, v.x );\n\t\tthis.y = Math.max( this.y, v.y );\n\n\t\treturn this;\n\n\t}\n\n\tclamp( min, max ) {\n\n\t\t// assumes min < max, componentwise\n\n\t\tthis.x = Math.max( min.x, Math.min( max.x, this.x ) );\n\t\tthis.y = Math.max( min.y, Math.min( max.y, this.y ) );\n\n\t\treturn this;\n\n\t}\n\n\tclampScalar( minVal, maxVal ) {\n\n\t\tthis.x = Math.max( minVal, Math.min( maxVal, this.x ) );\n\t\tthis.y = Math.max( minVal, Math.min( maxVal, this.y ) );\n\n\t\treturn this;\n\n\t}\n\n\tclampLength( min, max ) {\n\n\t\tconst length = this.length();\n\n\t\treturn this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );\n\n\t}\n\n\tfloor() {\n\n\t\tthis.x = Math.floor( this.x );\n\t\tthis.y = Math.floor( this.y );\n\n\t\treturn this;\n\n\t}\n\n\tceil() {\n\n\t\tthis.x = Math.ceil( this.x );\n\t\tthis.y = Math.ceil( this.y );\n\n\t\treturn this;\n\n\t}\n\n\tround() {\n\n\t\tthis.x = Math.round( this.x );\n\t\tthis.y = Math.round( this.y );\n\n\t\treturn this;\n\n\t}\n\n\troundToZero() {\n\n\t\tthis.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );\n\t\tthis.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );\n\n\t\treturn this;\n\n\t}\n\n\tnegate() {\n\n\t\tthis.x = - this.x;\n\t\tthis.y = - this.y;\n\n\t\treturn this;\n\n\t}\n\n\tdot( v ) {\n\n\t\treturn this.x * v.x + this.y * v.y;\n\n\t}\n\n\tcross( v ) {\n\n\t\treturn this.x * v.y - this.y * v.x;\n\n\t}\n\n\tlengthSq() {\n\n\t\treturn this.x * this.x + this.y * this.y;\n\n\t}\n\n\tlength() {\n\n\t\treturn Math.sqrt( this.x * this.x + this.y * this.y );\n\n\t}\n\n\tmanhattanLength() {\n\n\t\treturn Math.abs( this.x ) + Math.abs( this.y );\n\n\t}\n\n\tnormalize() {\n\n\t\treturn this.divideScalar( this.length() || 1 );\n\n\t}\n\n\tangle() {\n\n\t\t// computes the angle in radians with respect to the positive x-axis\n\n\t\tconst angle = Math.atan2( - this.y, - this.x ) + Math.PI;\n\n\t\treturn angle;\n\n\t}\n\n\tangleTo( v ) {\n\n\t\tconst denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );\n\n\t\tif ( denominator === 0 ) return Math.PI / 2;\n\n\t\tconst theta = this.dot( v ) / denominator;\n\n\t\t// clamp, to handle numerical problems\n\n\t\treturn Math.acos( clamp( theta, - 1, 1 ) );\n\n\t}\n\n\tdistanceTo( v ) {\n\n\t\treturn Math.sqrt( this.distanceToSquared( v ) );\n\n\t}\n\n\tdistanceToSquared( v ) {\n\n\t\tconst dx = this.x - v.x, dy = this.y - v.y;\n\t\treturn dx * dx + dy * dy;\n\n\t}\n\n\tmanhattanDistanceTo( v ) {\n\n\t\treturn Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );\n\n\t}\n\n\tsetLength( length ) {\n\n\t\treturn this.normalize().multiplyScalar( length );\n\n\t}\n\n\tlerp( v, alpha ) {\n\n\t\tthis.x += ( v.x - this.x ) * alpha;\n\t\tthis.y += ( v.y - this.y ) * alpha;\n\n\t\treturn this;\n\n\t}\n\n\tlerpVectors( v1, v2, alpha ) {\n\n\t\tthis.x = v1.x + ( v2.x - v1.x ) * alpha;\n\t\tthis.y = v1.y + ( v2.y - v1.y ) * alpha;\n\n\t\treturn this;\n\n\t}\n\n\tequals( v ) {\n\n\t\treturn ( ( v.x === this.x ) && ( v.y === this.y ) );\n\n\t}\n\n\tfromArray( array, offset = 0 ) {\n\n\t\tthis.x = array[ offset ];\n\t\tthis.y = array[ offset + 1 ];\n\n\t\treturn this;\n\n\t}\n\n\ttoArray( array = [], offset = 0 ) {\n\n\t\tarray[ offset ] = this.x;\n\t\tarray[ offset + 1 ] = this.y;\n\n\t\treturn array;\n\n\t}\n\n\tfromBufferAttribute( attribute, index ) {\n\n\t\tthis.x = attribute.getX( index );\n\t\tthis.y = attribute.getY( index );\n\n\t\treturn this;\n\n\t}\n\n\trotateAround( center, angle ) {\n\n\t\tconst c = Math.cos( angle ), s = Math.sin( angle );\n\n\t\tconst x = this.x - center.x;\n\t\tconst y = this.y - center.y;\n\n\t\tthis.x = x * c - y * s + center.x;\n\t\tthis.y = x * s + y * c + center.y;\n\n\t\treturn this;\n\n\t}\n\n\trandom() {\n\n\t\tthis.x = Math.random();\n\t\tthis.y = Math.random();\n\n\t\treturn this;\n\n\t}\n\n\t*[ Symbol.iterator ]() {\n\n\t\tyield this.x;\n\t\tyield this.y;\n\n\t}\n\n}\n\nclass Matrix3 {\n\n\tconstructor() {\n\n\t\tMatrix3.prototype.isMatrix3 = true;\n\n\t\tthis.elements = [\n\n\t\t\t1, 0, 0,\n\t\t\t0, 1, 0,\n\t\t\t0, 0, 1\n\n\t\t];\n\n\t}\n\n\tset( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {\n\n\t\tconst te = this.elements;\n\n\t\tte[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;\n\t\tte[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;\n\t\tte[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;\n\n\t\treturn this;\n\n\t}\n\n\tidentity() {\n\n\t\tthis.set(\n\n\t\t\t1, 0, 0,\n\t\t\t0, 1, 0,\n\t\t\t0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\tcopy( m ) {\n\n\t\tconst te = this.elements;\n\t\tconst me = m.elements;\n\n\t\tte[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];\n\t\tte[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];\n\t\tte[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];\n\n\t\treturn this;\n\n\t}\n\n\textractBasis( xAxis, yAxis, zAxis ) {\n\n\t\txAxis.setFromMatrix3Column( this, 0 );\n\t\tyAxis.setFromMatrix3Column( this, 1 );\n\t\tzAxis.setFromMatrix3Column( this, 2 );\n\n\t\treturn this;\n\n\t}\n\n\tsetFromMatrix4( m ) {\n\n\t\tconst me = m.elements;\n\n\t\tthis.set(\n\n\t\t\tme[ 0 ], me[ 4 ], me[ 8 ],\n\t\t\tme[ 1 ], me[ 5 ], me[ 9 ],\n\t\t\tme[ 2 ], me[ 6 ], me[ 10 ]\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\tmultiply( m ) {\n\n\t\treturn this.multiplyMatrices( this, m );\n\n\t}\n\n\tpremultiply( m ) {\n\n\t\treturn this.multiplyMatrices( m, this );\n\n\t}\n\n\tmultiplyMatrices( a, b ) {\n\n\t\tconst ae = a.elements;\n\t\tconst be = b.elements;\n\t\tconst te = this.elements;\n\n\t\tconst a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];\n\t\tconst a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];\n\t\tconst a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];\n\n\t\tconst b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];\n\t\tconst b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];\n\t\tconst b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];\n\n\t\tte[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;\n\t\tte[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;\n\t\tte[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;\n\n\t\tte[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;\n\t\tte[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;\n\t\tte[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;\n\n\t\tte[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;\n\t\tte[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;\n\t\tte[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;\n\n\t\treturn this;\n\n\t}\n\n\tmultiplyScalar( s ) {\n\n\t\tconst te = this.elements;\n\n\t\tte[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;\n\t\tte[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;\n\t\tte[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;\n\n\t\treturn this;\n\n\t}\n\n\tdeterminant() {\n\n\t\tconst te = this.elements;\n\n\t\tconst a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],\n\t\t\td = te[ 3 ], e = te[ 4 ], f = te[ 5 ],\n\t\t\tg = te[ 6 ], h = te[ 7 ], i = te[ 8 ];\n\n\t\treturn a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;\n\n\t}\n\n\tinvert() {\n\n\t\tconst te = this.elements,\n\n\t\t\tn11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],\n\t\t\tn12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],\n\t\t\tn13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],\n\n\t\t\tt11 = n33 * n22 - n32 * n23,\n\t\t\tt12 = n32 * n13 - n33 * n12,\n\t\t\tt13 = n23 * n12 - n22 * n13,\n\n\t\t\tdet = n11 * t11 + n21 * t12 + n31 * t13;\n\n\t\tif ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );\n\n\t\tconst detInv = 1 / det;\n\n\t\tte[ 0 ] = t11 * detInv;\n\t\tte[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;\n\t\tte[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;\n\n\t\tte[ 3 ] = t12 * detInv;\n\t\tte[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;\n\t\tte[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;\n\n\t\tte[ 6 ] = t13 * detInv;\n\t\tte[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;\n\t\tte[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;\n\n\t\treturn this;\n\n\t}\n\n\ttranspose() {\n\n\t\tlet tmp;\n\t\tconst m = this.elements;\n\n\t\ttmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;\n\t\ttmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;\n\t\ttmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;\n\n\t\treturn this;\n\n\t}\n\n\tgetNormalMatrix( matrix4 ) {\n\n\t\treturn this.setFromMatrix4( matrix4 ).invert().transpose();\n\n\t}\n\n\ttransposeIntoArray( r ) {\n\n\t\tconst m = this.elements;\n\n\t\tr[ 0 ] = m[ 0 ];\n\t\tr[ 1 ] = m[ 3 ];\n\t\tr[ 2 ] = m[ 6 ];\n\t\tr[ 3 ] = m[ 1 ];\n\t\tr[ 4 ] = m[ 4 ];\n\t\tr[ 5 ] = m[ 7 ];\n\t\tr[ 6 ] = m[ 2 ];\n\t\tr[ 7 ] = m[ 5 ];\n\t\tr[ 8 ] = m[ 8 ];\n\n\t\treturn this;\n\n\t}\n\n\tsetUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {\n\n\t\tconst c = Math.cos( rotation );\n\t\tconst s = Math.sin( rotation );\n\n\t\tthis.set(\n\t\t\tsx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,\n\t\t\t- sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,\n\t\t\t0, 0, 1\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\t//\n\n\tscale( sx, sy ) {\n\n\t\tthis.premultiply( _m3.makeScale( sx, sy ) );\n\n\t\treturn this;\n\n\t}\n\n\trotate( theta ) {\n\n\t\tthis.premultiply( _m3.makeRotation( - theta ) );\n\n\t\treturn this;\n\n\t}\n\n\ttranslate( tx, ty ) {\n\n\t\tthis.premultiply( _m3.makeTranslation( tx, ty ) );\n\n\t\treturn this;\n\n\t}\n\n\t// for 2D Transforms\n\n\tmakeTranslation( x, y ) {\n\n\t\tthis.set(\n\n\t\t\t1, 0, x,\n\t\t\t0, 1, y,\n\t\t\t0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\tmakeRotation( theta ) {\n\n\t\t// counterclockwise\n\n\t\tconst c = Math.cos( theta );\n\t\tconst s = Math.sin( theta );\n\n\t\tthis.set(\n\n\t\t\tc, - s, 0,\n\t\t\ts, c, 0,\n\t\t\t0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\tmakeScale( x, y ) {\n\n\t\tthis.set(\n\n\t\t\tx, 0, 0,\n\t\t\t0, y, 0,\n\t\t\t0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\t//\n\n\tequals( matrix ) {\n\n\t\tconst te = this.elements;\n\t\tconst me = matrix.elements;\n\n\t\tfor ( let i = 0; i < 9; i ++ ) {\n\n\t\t\tif ( te[ i ] !== me[ i ] ) return false;\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\tfromArray( array, offset = 0 ) {\n\n\t\tfor ( let i = 0; i < 9; i ++ ) {\n\n\t\t\tthis.elements[ i ] = array[ i + offset ];\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\ttoArray( array = [], offset = 0 ) {\n\n\t\tconst te = this.elements;\n\n\t\tarray[ offset ] = te[ 0 ];\n\t\tarray[ offset + 1 ] = te[ 1 ];\n\t\tarray[ offset + 2 ] = te[ 2 ];\n\n\t\tarray[ offset + 3 ] = te[ 3 ];\n\t\tarray[ offset + 4 ] = te[ 4 ];\n\t\tarray[ offset + 5 ] = te[ 5 ];\n\n\t\tarray[ offset + 6 ] = te[ 6 ];\n\t\tarray[ offset + 7 ] = te[ 7 ];\n\t\tarray[ offset + 8 ] = te[ 8 ];\n\n\t\treturn array;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().fromArray( this.elements );\n\n\t}\n\n}\n\nconst _m3 = /*@__PURE__*/ new Matrix3();\n\nfunction arrayNeedsUint32( array ) {\n\n\t// assumes larger values usually on last\n\n\tfor ( let i = array.length - 1; i >= 0; -- i ) {\n\n\t\tif ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565\n\n\t}\n\n\treturn false;\n\n}\n\nconst TYPED_ARRAYS = {\n\tInt8Array: Int8Array,\n\tUint8Array: Uint8Array,\n\tUint8ClampedArray: Uint8ClampedArray,\n\tInt16Array: Int16Array,\n\tUint16Array: Uint16Array,\n\tInt32Array: Int32Array,\n\tUint32Array: Uint32Array,\n\tFloat32Array: Float32Array,\n\tFloat64Array: Float64Array\n};\n\nfunction getTypedArray( type, buffer ) {\n\n\treturn new TYPED_ARRAYS[ type ]( buffer );\n\n}\n\nfunction createElementNS( name ) {\n\n\treturn document.createElementNS( 'http://www.w3.org/1999/xhtml', name );\n\n}\n\nconst _cache = {};\n\nfunction warnOnce( message ) {\n\n\tif ( message in _cache ) return;\n\n\t_cache[ message ] = true;\n\n\tconsole.warn( message );\n\n}\n\nfunction SRGBToLinear( c ) {\n\n\treturn ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );\n\n}\n\nfunction LinearToSRGB( c ) {\n\n\treturn ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;\n\n}\n\n/**\n * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping\n * or clipping. Based on W3C specifications for sRGB and Display P3,\n * and ICC specifications for the D50 connection space. Values in/out\n * are _linear_ sRGB and _linear_ Display P3.\n *\n * Note that both sRGB and Display P3 use the sRGB transfer functions.\n *\n * Reference:\n * - http://www.russellcottrell.com/photo/matrixCalculator.htm\n */\n\nconst LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().fromArray( [\n\t0.8224621, 0.0331941, 0.0170827,\n\t0.1775380, 0.9668058, 0.0723974,\n\t- 0.0000001, 0.0000001, 0.9105199\n] );\n\nconst LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().fromArray( [\n\t1.2249401, - 0.0420569, - 0.0196376,\n\t- 0.2249404, 1.0420571, - 0.0786361,\n\t0.0000001, 0.0000000, 1.0982735\n] );\n\nfunction DisplayP3ToLinearSRGB( color ) {\n\n\t// Display P3 uses the sRGB transfer functions\n\treturn color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB );\n\n}\n\nfunction LinearSRGBToDisplayP3( color ) {\n\n\t// Display P3 uses the sRGB transfer functions\n\treturn color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB();\n\n}\n\n// Conversions from to Linear-sRGB reference space.\nconst TO_LINEAR = {\n\t[ LinearSRGBColorSpace ]: ( color ) => color,\n\t[ SRGBColorSpace ]: ( color ) => color.convertSRGBToLinear(),\n\t[ DisplayP3ColorSpace ]: DisplayP3ToLinearSRGB,\n};\n\n// Conversions to from Linear-sRGB reference space.\nconst FROM_LINEAR = {\n\t[ LinearSRGBColorSpace ]: ( color ) => color,\n\t[ SRGBColorSpace ]: ( color ) => color.convertLinearToSRGB(),\n\t[ DisplayP3ColorSpace ]: LinearSRGBToDisplayP3,\n};\n\nconst ColorManagement = {\n\n\tenabled: true,\n\n\tget legacyMode() {\n\n\t\tconsole.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );\n\n\t\treturn ! this.enabled;\n\n\t},\n\n\tset legacyMode( legacyMode ) {\n\n\t\tconsole.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );\n\n\t\tthis.enabled = ! legacyMode;\n\n\t},\n\n\tget workingColorSpace() {\n\n\t\treturn LinearSRGBColorSpace;\n\n\t},\n\n\tset workingColorSpace( colorSpace ) {\n\n\t\tconsole.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );\n\n\t},\n\n\tconvert: function ( color, sourceColorSpace, targetColorSpace ) {\n\n\t\tif ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {\n\n\t\t\treturn color;\n\n\t\t}\n\n\t\tconst sourceToLinear = TO_LINEAR[ sourceColorSpace ];\n\t\tconst targetFromLinear = FROM_LINEAR[ targetColorSpace ];\n\n\t\tif ( sourceToLinear === undefined || targetFromLinear === undefined ) {\n\n\t\t\tthrow new Error( `Unsupported color space conversion, \"${ sourceColorSpace }\" to \"${ targetColorSpace }\".` );\n\n\t\t}\n\n\t\treturn targetFromLinear( sourceToLinear( color ) );\n\n\t},\n\n\tfromWorkingColorSpace: function ( color, targetColorSpace ) {\n\n\t\treturn this.convert( color, this.workingColorSpace, targetColorSpace );\n\n\t},\n\n\ttoWorkingColorSpace: function ( color, sourceColorSpace ) {\n\n\t\treturn this.convert( color, sourceColorSpace, this.workingColorSpace );\n\n\t},\n\n};\n\nlet _canvas;\n\nclass ImageUtils {\n\n\tstatic getDataURL( image ) {\n\n\t\tif ( /^data:/i.test( image.src ) ) {\n\n\t\t\treturn image.src;\n\n\t\t}\n\n\t\tif ( typeof HTMLCanvasElement === 'undefined' ) {\n\n\t\t\treturn image.src;\n\n\t\t}\n\n\t\tlet canvas;\n\n\t\tif ( image instanceof HTMLCanvasElement ) {\n\n\t\t\tcanvas = image;\n\n\t\t} else {\n\n\t\t\tif ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );\n\n\t\t\t_canvas.width = image.width;\n\t\t\t_canvas.height = image.height;\n\n\t\t\tconst context = _canvas.getContext( '2d' );\n\n\t\t\tif ( image instanceof ImageData ) {\n\n\t\t\t\tcontext.putImageData( image, 0, 0 );\n\n\t\t\t} else {\n\n\t\t\t\tcontext.drawImage( image, 0, 0, image.width, image.height );\n\n\t\t\t}\n\n\t\t\tcanvas = _canvas;\n\n\t\t}\n\n\t\tif ( canvas.width > 2048 || canvas.height > 2048 ) {\n\n\t\t\tconsole.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );\n\n\t\t\treturn canvas.toDataURL( 'image/jpeg', 0.6 );\n\n\t\t} else {\n\n\t\t\treturn canvas.toDataURL( 'image/png' );\n\n\t\t}\n\n\t}\n\n\tstatic sRGBToLinear( image ) {\n\n\t\tif ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||\n\t\t\t( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||\n\t\t\t( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {\n\n\t\t\tconst canvas = createElementNS( 'canvas' );\n\n\t\t\tcanvas.width = image.width;\n\t\t\tcanvas.height = image.height;\n\n\t\t\tconst context = canvas.getContext( '2d' );\n\t\t\tcontext.drawImage( image, 0, 0, image.width, image.height );\n\n\t\t\tconst imageData = context.getImageData( 0, 0, image.width, image.height );\n\t\t\tconst data = imageData.data;\n\n\t\t\tfor ( let i = 0; i < data.length; i ++ ) {\n\n\t\t\t\tdata[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;\n\n\t\t\t}\n\n\t\t\tcontext.putImageData( imageData, 0, 0 );\n\n\t\t\treturn canvas;\n\n\t\t} else if ( image.data ) {\n\n\t\t\tconst data = image.data.slice( 0 );\n\n\t\t\tfor ( let i = 0; i < data.length; i ++ ) {\n\n\t\t\t\tif ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {\n\n\t\t\t\t\tdata[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// assuming float\n\n\t\t\t\t\tdata[ i ] = SRGBToLinear( data[ i ] );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tdata: data,\n\t\t\t\twidth: image.width,\n\t\t\t\theight: image.height\n\t\t\t};\n\n\t\t} else {\n\n\t\t\tconsole.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );\n\t\t\treturn image;\n\n\t\t}\n\n\t}\n\n}\n\nclass Source {\n\n\tconstructor( data = null ) {\n\n\t\tthis.isSource = true;\n\n\t\tthis.uuid = generateUUID();\n\n\t\tthis.data = data;\n\n\t\tthis.version = 0;\n\n\t}\n\n\tset needsUpdate( value ) {\n\n\t\tif ( value === true ) this.version ++;\n\n\t}\n\n\ttoJSON( meta ) {\n\n\t\tconst isRootObject = ( meta === undefined || typeof meta === 'string' );\n\n\t\tif ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {\n\n\t\t\treturn meta.images[ this.uuid ];\n\n\t\t}\n\n\t\tconst output = {\n\t\t\tuuid: this.uuid,\n\t\t\turl: ''\n\t\t};\n\n\t\tconst data = this.data;\n\n\t\tif ( data !== null ) {\n\n\t\t\tlet url;\n\n\t\t\tif ( Array.isArray( data ) ) {\n\n\t\t\t\t// cube texture\n\n\t\t\t\turl = [];\n\n\t\t\t\tfor ( let i = 0, l = data.length; i < l; i ++ ) {\n\n\t\t\t\t\tif ( data[ i ].isDataTexture ) {\n\n\t\t\t\t\t\turl.push( serializeImage( data[ i ].image ) );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\turl.push( serializeImage( data[ i ] ) );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\t// texture\n\n\t\t\t\turl = serializeImage( data );\n\n\t\t\t}\n\n\t\t\toutput.url = url;\n\n\t\t}\n\n\t\tif ( ! isRootObject ) {\n\n\t\t\tmeta.images[ this.uuid ] = output;\n\n\t\t}\n\n\t\treturn output;\n\n\t}\n\n}\n\nfunction serializeImage( image ) {\n\n\tif ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||\n\t\t( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||\n\t\t( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {\n\n\t\t// default images\n\n\t\treturn ImageUtils.getDataURL( image );\n\n\t} else {\n\n\t\tif ( image.data ) {\n\n\t\t\t// images of DataTexture\n\n\t\t\treturn {\n\t\t\t\tdata: Array.from( image.data ),\n\t\t\t\twidth: image.width,\n\t\t\t\theight: image.height,\n\t\t\t\ttype: image.data.constructor.name\n\t\t\t};\n\n\t\t} else {\n\n\t\t\tconsole.warn( 'THREE.Texture: Unable to serialize Texture.' );\n\t\t\treturn {};\n\n\t\t}\n\n\t}\n\n}\n\nlet textureId = 0;\n\nclass Texture extends EventDispatcher {\n\n\tconstructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {\n\n\t\tsuper();\n\n\t\tthis.isTexture = true;\n\n\t\tObject.defineProperty( this, 'id', { value: textureId ++ } );\n\n\t\tthis.uuid = generateUUID();\n\n\t\tthis.name = '';\n\n\t\tthis.source = new Source( image );\n\t\tthis.mipmaps = [];\n\n\t\tthis.mapping = mapping;\n\t\tthis.channel = 0;\n\n\t\tthis.wrapS = wrapS;\n\t\tthis.wrapT = wrapT;\n\n\t\tthis.magFilter = magFilter;\n\t\tthis.minFilter = minFilter;\n\n\t\tthis.anisotropy = anisotropy;\n\n\t\tthis.format = format;\n\t\tthis.internalFormat = null;\n\t\tthis.type = type;\n\n\t\tthis.offset = new Vector2( 0, 0 );\n\t\tthis.repeat = new Vector2( 1, 1 );\n\t\tthis.center = new Vector2( 0, 0 );\n\t\tthis.rotation = 0;\n\n\t\tthis.matrixAutoUpdate = true;\n\t\tthis.matrix = new Matrix3();\n\n\t\tthis.generateMipmaps = true;\n\t\tthis.premultiplyAlpha = false;\n\t\tthis.flipY = true;\n\t\tthis.unpackAlignment = 4;\t// valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)\n\n\t\tif ( typeof colorSpace === 'string' ) {\n\n\t\t\tthis.colorSpace = colorSpace;\n\n\t\t} else { // @deprecated, r152\n\n\t\t\twarnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );\n\t\t\tthis.colorSpace = colorSpace === sRGBEncoding ? SRGBColorSpace : NoColorSpace;\n\n\t\t}\n\n\n\t\tthis.userData = {};\n\n\t\tthis.version = 0;\n\t\tthis.onUpdate = null;\n\n\t\tthis.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not\n\t\tthis.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)\n\n\t}\n\n\tget image() {\n\n\t\treturn this.source.data;\n\n\t}\n\n\tset image( value = null ) {\n\n\t\tthis.source.data = value;\n\n\t}\n\n\tupdateMatrix() {\n\n\t\tthis.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tthis.name = source.name;\n\n\t\tthis.source = source.source;\n\t\tthis.mipmaps = source.mipmaps.slice( 0 );\n\n\t\tthis.mapping = source.mapping;\n\t\tthis.channel = source.channel;\n\n\t\tthis.wrapS = source.wrapS;\n\t\tthis.wrapT = source.wrapT;\n\n\t\tthis.magFilter = source.magFilter;\n\t\tthis.minFilter = source.minFilter;\n\n\t\tthis.anisotropy = source.anisotropy;\n\n\t\tthis.format = source.format;\n\t\tthis.internalFormat = source.internalFormat;\n\t\tthis.type = source.type;\n\n\t\tthis.offset.copy( source.offset );\n\t\tthis.repeat.copy( source.repeat );\n\t\tthis.center.copy( source.center );\n\t\tthis.rotation = source.rotation;\n\n\t\tthis.matrixAutoUpdate = source.matrixAutoUpdate;\n\t\tthis.matrix.copy( source.matrix );\n\n\t\tthis.generateMipmaps = source.generateMipmaps;\n\t\tthis.premultiplyAlpha = source.premultiplyAlpha;\n\t\tthis.flipY = source.flipY;\n\t\tthis.unpackAlignment = source.unpackAlignment;\n\t\tthis.colorSpace = source.colorSpace;\n\n\t\tthis.userData = JSON.parse( JSON.stringify( source.userData ) );\n\n\t\tthis.needsUpdate = true;\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON( meta ) {\n\n\t\tconst isRootObject = ( meta === undefined || typeof meta === 'string' );\n\n\t\tif ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {\n\n\t\t\treturn meta.textures[ this.uuid ];\n\n\t\t}\n\n\t\tconst output = {\n\n\t\t\tmetadata: {\n\t\t\t\tversion: 4.5,\n\t\t\t\ttype: 'Texture',\n\t\t\t\tgenerator: 'Texture.toJSON'\n\t\t\t},\n\n\t\t\tuuid: this.uuid,\n\t\t\tname: this.name,\n\n\t\t\timage: this.source.toJSON( meta ).uuid,\n\n\t\t\tmapping: this.mapping,\n\t\t\tchannel: this.channel,\n\n\t\t\trepeat: [ this.repeat.x, this.repeat.y ],\n\t\t\toffset: [ this.offset.x, this.offset.y ],\n\t\t\tcenter: [ this.center.x, this.center.y ],\n\t\t\trotation: this.rotation,\n\n\t\t\twrap: [ this.wrapS, this.wrapT ],\n\n\t\t\tformat: this.format,\n\t\t\tinternalFormat: this.internalFormat,\n\t\t\ttype: this.type,\n\t\t\tcolorSpace: this.colorSpace,\n\n\t\t\tminFilter: this.minFilter,\n\t\t\tmagFilter: this.magFilter,\n\t\t\tanisotropy: this.anisotropy,\n\n\t\t\tflipY: this.flipY,\n\n\t\t\tgenerateMipmaps: this.generateMipmaps,\n\t\t\tpremultiplyAlpha: this.premultiplyAlpha,\n\t\t\tunpackAlignment: this.unpackAlignment\n\n\t\t};\n\n\t\tif ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;\n\n\t\tif ( ! isRootObject ) {\n\n\t\t\tmeta.textures[ this.uuid ] = output;\n\n\t\t}\n\n\t\treturn output;\n\n\t}\n\n\tdispose() {\n\n\t\tthis.dispatchEvent( { type: 'dispose' } );\n\n\t}\n\n\ttransformUv( uv ) {\n\n\t\tif ( this.mapping !== UVMapping ) return uv;\n\n\t\tuv.applyMatrix3( this.matrix );\n\n\t\tif ( uv.x < 0 || uv.x > 1 ) {\n\n\t\t\tswitch ( this.wrapS ) {\n\n\t\t\t\tcase RepeatWrapping:\n\n\t\t\t\t\tuv.x = uv.x - Math.floor( uv.x );\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase ClampToEdgeWrapping:\n\n\t\t\t\t\tuv.x = uv.x < 0 ? 0 : 1;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MirroredRepeatWrapping:\n\n\t\t\t\t\tif ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {\n\n\t\t\t\t\t\tuv.x = Math.ceil( uv.x ) - uv.x;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tuv.x = uv.x - Math.floor( uv.x );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( uv.y < 0 || uv.y > 1 ) {\n\n\t\t\tswitch ( this.wrapT ) {\n\n\t\t\t\tcase RepeatWrapping:\n\n\t\t\t\t\tuv.y = uv.y - Math.floor( uv.y );\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase ClampToEdgeWrapping:\n\n\t\t\t\t\tuv.y = uv.y < 0 ? 0 : 1;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MirroredRepeatWrapping:\n\n\t\t\t\t\tif ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {\n\n\t\t\t\t\t\tuv.y = Math.ceil( uv.y ) - uv.y;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tuv.y = uv.y - Math.floor( uv.y );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( this.flipY ) {\n\n\t\t\tuv.y = 1 - uv.y;\n\n\t\t}\n\n\t\treturn uv;\n\n\t}\n\n\tset needsUpdate( value ) {\n\n\t\tif ( value === true ) {\n\n\t\t\tthis.version ++;\n\t\t\tthis.source.needsUpdate = true;\n\n\t\t}\n\n\t}\n\n\tget encoding() { // @deprecated, r152\n\n\t\twarnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );\n\t\treturn this.colorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding;\n\n\t}\n\n\tset encoding( encoding ) { // @deprecated, r152\n\n\t\twarnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );\n\t\tthis.colorSpace = encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;\n\n\t}\n\n}\n\nTexture.DEFAULT_IMAGE = null;\nTexture.DEFAULT_MAPPING = UVMapping;\nTexture.DEFAULT_ANISOTROPY = 1;\n\nclass Vector4 {\n\n\tconstructor( x = 0, y = 0, z = 0, w = 1 ) {\n\n\t\tVector4.prototype.isVector4 = true;\n\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.z = z;\n\t\tthis.w = w;\n\n\t}\n\n\tget width() {\n\n\t\treturn this.z;\n\n\t}\n\n\tset width( value ) {\n\n\t\tthis.z = value;\n\n\t}\n\n\tget height() {\n\n\t\treturn this.w;\n\n\t}\n\n\tset height( value ) {\n\n\t\tthis.w = value;\n\n\t}\n\n\tset( x, y, z, w ) {\n\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.z = z;\n\t\tthis.w = w;\n\n\t\treturn this;\n\n\t}\n\n\tsetScalar( scalar ) {\n\n\t\tthis.x = scalar;\n\t\tthis.y = scalar;\n\t\tthis.z = scalar;\n\t\tthis.w = scalar;\n\n\t\treturn this;\n\n\t}\n\n\tsetX( x ) {\n\n\t\tthis.x = x;\n\n\t\treturn this;\n\n\t}\n\n\tsetY( y ) {\n\n\t\tthis.y = y;\n\n\t\treturn this;\n\n\t}\n\n\tsetZ( z ) {\n\n\t\tthis.z = z;\n\n\t\treturn this;\n\n\t}\n\n\tsetW( w ) {\n\n\t\tthis.w = w;\n\n\t\treturn this;\n\n\t}\n\n\tsetComponent( index, value ) {\n\n\t\tswitch ( index ) {\n\n\t\t\tcase 0: this.x = value; break;\n\t\t\tcase 1: this.y = value; break;\n\t\t\tcase 2: this.z = value; break;\n\t\t\tcase 3: this.w = value; break;\n\t\t\tdefault: throw new Error( 'index is out of range: ' + index );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tgetComponent( index ) {\n\n\t\tswitch ( index ) {\n\n\t\t\tcase 0: return this.x;\n\t\t\tcase 1: return this.y;\n\t\t\tcase 2: return this.z;\n\t\t\tcase 3: return this.w;\n\t\t\tdefault: throw new Error( 'index is out of range: ' + index );\n\n\t\t}\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor( this.x, this.y, this.z, this.w );\n\n\t}\n\n\tcopy( v ) {\n\n\t\tthis.x = v.x;\n\t\tthis.y = v.y;\n\t\tthis.z = v.z;\n\t\tthis.w = ( v.w !== undefined ) ? v.w : 1;\n\n\t\treturn this;\n\n\t}\n\n\tadd( v ) {\n\n\t\tthis.x += v.x;\n\t\tthis.y += v.y;\n\t\tthis.z += v.z;\n\t\tthis.w += v.w;\n\n\t\treturn this;\n\n\t}\n\n\taddScalar( s ) {\n\n\t\tthis.x += s;\n\t\tthis.y += s;\n\t\tthis.z += s;\n\t\tthis.w += s;\n\n\t\treturn this;\n\n\t}\n\n\taddVectors( a, b ) {\n\n\t\tthis.x = a.x + b.x;\n\t\tthis.y = a.y + b.y;\n\t\tthis.z = a.z + b.z;\n\t\tthis.w = a.w + b.w;\n\n\t\treturn this;\n\n\t}\n\n\taddScaledVector( v, s ) {\n\n\t\tthis.x += v.x * s;\n\t\tthis.y += v.y * s;\n\t\tthis.z += v.z * s;\n\t\tthis.w += v.w * s;\n\n\t\treturn this;\n\n\t}\n\n\tsub( v ) {\n\n\t\tthis.x -= v.x;\n\t\tthis.y -= v.y;\n\t\tthis.z -= v.z;\n\t\tthis.w -= v.w;\n\n\t\treturn this;\n\n\t}\n\n\tsubScalar( s ) {\n\n\t\tthis.x -= s;\n\t\tthis.y -= s;\n\t\tthis.z -= s;\n\t\tthis.w -= s;\n\n\t\treturn this;\n\n\t}\n\n\tsubVectors( a, b ) {\n\n\t\tthis.x = a.x - b.x;\n\t\tthis.y = a.y - b.y;\n\t\tthis.z = a.z - b.z;\n\t\tthis.w = a.w - b.w;\n\n\t\treturn this;\n\n\t}\n\n\tmultiply( v ) {\n\n\t\tthis.x *= v.x;\n\t\tthis.y *= v.y;\n\t\tthis.z *= v.z;\n\t\tthis.w *= v.w;\n\n\t\treturn this;\n\n\t}\n\n\tmultiplyScalar( scalar ) {\n\n\t\tthis.x *= scalar;\n\t\tthis.y *= scalar;\n\t\tthis.z *= scalar;\n\t\tthis.w *= scalar;\n\n\t\treturn this;\n\n\t}\n\n\tapplyMatrix4( m ) {\n\n\t\tconst x = this.x, y = this.y, z = this.z, w = this.w;\n\t\tconst e = m.elements;\n\n\t\tthis.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;\n\t\tthis.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;\n\t\tthis.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;\n\t\tthis.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;\n\n\t\treturn this;\n\n\t}\n\n\tdivideScalar( scalar ) {\n\n\t\treturn this.multiplyScalar( 1 / scalar );\n\n\t}\n\n\tsetAxisAngleFromQuaternion( q ) {\n\n\t\t// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm\n\n\t\t// q is assumed to be normalized\n\n\t\tthis.w = 2 * Math.acos( q.w );\n\n\t\tconst s = Math.sqrt( 1 - q.w * q.w );\n\n\t\tif ( s < 0.0001 ) {\n\n\t\t\tthis.x = 1;\n\t\t\tthis.y = 0;\n\t\t\tthis.z = 0;\n\n\t\t} else {\n\n\t\t\tthis.x = q.x / s;\n\t\t\tthis.y = q.y / s;\n\t\t\tthis.z = q.z / s;\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tsetAxisAngleFromRotationMatrix( m ) {\n\n\t\t// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm\n\n\t\t// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)\n\n\t\tlet angle, x, y, z; // variables for result\n\t\tconst epsilon = 0.01,\t\t// margin to allow for rounding errors\n\t\t\tepsilon2 = 0.1,\t\t// margin to distinguish between 0 and 180 degrees\n\n\t\t\tte = m.elements,\n\n\t\t\tm11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],\n\t\t\tm21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],\n\t\t\tm31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];\n\n\t\tif ( ( Math.abs( m12 - m21 ) < epsilon ) &&\n\t\t ( Math.abs( m13 - m31 ) < epsilon ) &&\n\t\t ( Math.abs( m23 - m32 ) < epsilon ) ) {\n\n\t\t\t// singularity found\n\t\t\t// first check for identity matrix which must have +1 for all terms\n\t\t\t// in leading diagonal and zero in other terms\n\n\t\t\tif ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&\n\t\t\t ( Math.abs( m13 + m31 ) < epsilon2 ) &&\n\t\t\t ( Math.abs( m23 + m32 ) < epsilon2 ) &&\n\t\t\t ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {\n\n\t\t\t\t// this singularity is identity matrix so angle = 0\n\n\t\t\t\tthis.set( 1, 0, 0, 0 );\n\n\t\t\t\treturn this; // zero angle, arbitrary axis\n\n\t\t\t}\n\n\t\t\t// otherwise this singularity is angle = 180\n\n\t\t\tangle = Math.PI;\n\n\t\t\tconst xx = ( m11 + 1 ) / 2;\n\t\t\tconst yy = ( m22 + 1 ) / 2;\n\t\t\tconst zz = ( m33 + 1 ) / 2;\n\t\t\tconst xy = ( m12 + m21 ) / 4;\n\t\t\tconst xz = ( m13 + m31 ) / 4;\n\t\t\tconst yz = ( m23 + m32 ) / 4;\n\n\t\t\tif ( ( xx > yy ) && ( xx > zz ) ) {\n\n\t\t\t\t// m11 is the largest diagonal term\n\n\t\t\t\tif ( xx < epsilon ) {\n\n\t\t\t\t\tx = 0;\n\t\t\t\t\ty = 0.707106781;\n\t\t\t\t\tz = 0.707106781;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tx = Math.sqrt( xx );\n\t\t\t\t\ty = xy / x;\n\t\t\t\t\tz = xz / x;\n\n\t\t\t\t}\n\n\t\t\t} else if ( yy > zz ) {\n\n\t\t\t\t// m22 is the largest diagonal term\n\n\t\t\t\tif ( yy < epsilon ) {\n\n\t\t\t\t\tx = 0.707106781;\n\t\t\t\t\ty = 0;\n\t\t\t\t\tz = 0.707106781;\n\n\t\t\t\t} else {\n\n\t\t\t\t\ty = Math.sqrt( yy );\n\t\t\t\t\tx = xy / y;\n\t\t\t\t\tz = yz / y;\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\t// m33 is the largest diagonal term so base result on this\n\n\t\t\t\tif ( zz < epsilon ) {\n\n\t\t\t\t\tx = 0.707106781;\n\t\t\t\t\ty = 0.707106781;\n\t\t\t\t\tz = 0;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tz = Math.sqrt( zz );\n\t\t\t\t\tx = xz / z;\n\t\t\t\t\ty = yz / z;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tthis.set( x, y, z, angle );\n\n\t\t\treturn this; // return 180 deg rotation\n\n\t\t}\n\n\t\t// as we have reached here there are no singularities so we can handle normally\n\n\t\tlet s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +\n\t\t\t( m13 - m31 ) * ( m13 - m31 ) +\n\t\t\t( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize\n\n\t\tif ( Math.abs( s ) < 0.001 ) s = 1;\n\n\t\t// prevent divide by zero, should not happen if matrix is orthogonal and should be\n\t\t// caught by singularity test above, but I've left it in just in case\n\n\t\tthis.x = ( m32 - m23 ) / s;\n\t\tthis.y = ( m13 - m31 ) / s;\n\t\tthis.z = ( m21 - m12 ) / s;\n\t\tthis.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );\n\n\t\treturn this;\n\n\t}\n\n\tmin( v ) {\n\n\t\tthis.x = Math.min( this.x, v.x );\n\t\tthis.y = Math.min( this.y, v.y );\n\t\tthis.z = Math.min( this.z, v.z );\n\t\tthis.w = Math.min( this.w, v.w );\n\n\t\treturn this;\n\n\t}\n\n\tmax( v ) {\n\n\t\tthis.x = Math.max( this.x, v.x );\n\t\tthis.y = Math.max( this.y, v.y );\n\t\tthis.z = Math.max( this.z, v.z );\n\t\tthis.w = Math.max( this.w, v.w );\n\n\t\treturn this;\n\n\t}\n\n\tclamp( min, max ) {\n\n\t\t// assumes min < max, componentwise\n\n\t\tthis.x = Math.max( min.x, Math.min( max.x, this.x ) );\n\t\tthis.y = Math.max( min.y, Math.min( max.y, this.y ) );\n\t\tthis.z = Math.max( min.z, Math.min( max.z, this.z ) );\n\t\tthis.w = Math.max( min.w, Math.min( max.w, this.w ) );\n\n\t\treturn this;\n\n\t}\n\n\tclampScalar( minVal, maxVal ) {\n\n\t\tthis.x = Math.max( minVal, Math.min( maxVal, this.x ) );\n\t\tthis.y = Math.max( minVal, Math.min( maxVal, this.y ) );\n\t\tthis.z = Math.max( minVal, Math.min( maxVal, this.z ) );\n\t\tthis.w = Math.max( minVal, Math.min( maxVal, this.w ) );\n\n\t\treturn this;\n\n\t}\n\n\tclampLength( min, max ) {\n\n\t\tconst length = this.length();\n\n\t\treturn this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );\n\n\t}\n\n\tfloor() {\n\n\t\tthis.x = Math.floor( this.x );\n\t\tthis.y = Math.floor( this.y );\n\t\tthis.z = Math.floor( this.z );\n\t\tthis.w = Math.floor( this.w );\n\n\t\treturn this;\n\n\t}\n\n\tceil() {\n\n\t\tthis.x = Math.ceil( this.x );\n\t\tthis.y = Math.ceil( this.y );\n\t\tthis.z = Math.ceil( this.z );\n\t\tthis.w = Math.ceil( this.w );\n\n\t\treturn this;\n\n\t}\n\n\tround() {\n\n\t\tthis.x = Math.round( this.x );\n\t\tthis.y = Math.round( this.y );\n\t\tthis.z = Math.round( this.z );\n\t\tthis.w = Math.round( this.w );\n\n\t\treturn this;\n\n\t}\n\n\troundToZero() {\n\n\t\tthis.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );\n\t\tthis.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );\n\t\tthis.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );\n\t\tthis.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );\n\n\t\treturn this;\n\n\t}\n\n\tnegate() {\n\n\t\tthis.x = - this.x;\n\t\tthis.y = - this.y;\n\t\tthis.z = - this.z;\n\t\tthis.w = - this.w;\n\n\t\treturn this;\n\n\t}\n\n\tdot( v ) {\n\n\t\treturn this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;\n\n\t}\n\n\tlengthSq() {\n\n\t\treturn this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;\n\n\t}\n\n\tlength() {\n\n\t\treturn Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );\n\n\t}\n\n\tmanhattanLength() {\n\n\t\treturn Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );\n\n\t}\n\n\tnormalize() {\n\n\t\treturn this.divideScalar( this.length() || 1 );\n\n\t}\n\n\tsetLength( length ) {\n\n\t\treturn this.normalize().multiplyScalar( length );\n\n\t}\n\n\tlerp( v, alpha ) {\n\n\t\tthis.x += ( v.x - this.x ) * alpha;\n\t\tthis.y += ( v.y - this.y ) * alpha;\n\t\tthis.z += ( v.z - this.z ) * alpha;\n\t\tthis.w += ( v.w - this.w ) * alpha;\n\n\t\treturn this;\n\n\t}\n\n\tlerpVectors( v1, v2, alpha ) {\n\n\t\tthis.x = v1.x + ( v2.x - v1.x ) * alpha;\n\t\tthis.y = v1.y + ( v2.y - v1.y ) * alpha;\n\t\tthis.z = v1.z + ( v2.z - v1.z ) * alpha;\n\t\tthis.w = v1.w + ( v2.w - v1.w ) * alpha;\n\n\t\treturn this;\n\n\t}\n\n\tequals( v ) {\n\n\t\treturn ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );\n\n\t}\n\n\tfromArray( array, offset = 0 ) {\n\n\t\tthis.x = array[ offset ];\n\t\tthis.y = array[ offset + 1 ];\n\t\tthis.z = array[ offset + 2 ];\n\t\tthis.w = array[ offset + 3 ];\n\n\t\treturn this;\n\n\t}\n\n\ttoArray( array = [], offset = 0 ) {\n\n\t\tarray[ offset ] = this.x;\n\t\tarray[ offset + 1 ] = this.y;\n\t\tarray[ offset + 2 ] = this.z;\n\t\tarray[ offset + 3 ] = this.w;\n\n\t\treturn array;\n\n\t}\n\n\tfromBufferAttribute( attribute, index ) {\n\n\t\tthis.x = attribute.getX( index );\n\t\tthis.y = attribute.getY( index );\n\t\tthis.z = attribute.getZ( index );\n\t\tthis.w = attribute.getW( index );\n\n\t\treturn this;\n\n\t}\n\n\trandom() {\n\n\t\tthis.x = Math.random();\n\t\tthis.y = Math.random();\n\t\tthis.z = Math.random();\n\t\tthis.w = Math.random();\n\n\t\treturn this;\n\n\t}\n\n\t*[ Symbol.iterator ]() {\n\n\t\tyield this.x;\n\t\tyield this.y;\n\t\tyield this.z;\n\t\tyield this.w;\n\n\t}\n\n}\n\n/*\n In options, we can specify:\n * Texture parameters for an auto-generated target texture\n * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers\n*/\nclass WebGLRenderTarget extends EventDispatcher {\n\n\tconstructor( width = 1, height = 1, options = {} ) {\n\n\t\tsuper();\n\n\t\tthis.isWebGLRenderTarget = true;\n\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.depth = 1;\n\n\t\tthis.scissor = new Vector4( 0, 0, width, height );\n\t\tthis.scissorTest = false;\n\n\t\tthis.viewport = new Vector4( 0, 0, width, height );\n\n\t\tconst image = { width: width, height: height, depth: 1 };\n\n\t\tif ( options.encoding !== undefined ) {\n\n\t\t\t// @deprecated, r152\n\t\t\twarnOnce( 'THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace.' );\n\t\t\toptions.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;\n\n\t\t}\n\n\t\tthis.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );\n\t\tthis.texture.isRenderTargetTexture = true;\n\n\t\tthis.texture.flipY = false;\n\t\tthis.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;\n\t\tthis.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;\n\t\tthis.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;\n\n\t\tthis.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;\n\t\tthis.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;\n\n\t\tthis.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;\n\n\t\tthis.samples = options.samples !== undefined ? options.samples : 0;\n\n\t}\n\n\tsetSize( width, height, depth = 1 ) {\n\n\t\tif ( this.width !== width || this.height !== height || this.depth !== depth ) {\n\n\t\t\tthis.width = width;\n\t\t\tthis.height = height;\n\t\t\tthis.depth = depth;\n\n\t\t\tthis.texture.image.width = width;\n\t\t\tthis.texture.image.height = height;\n\t\t\tthis.texture.image.depth = depth;\n\n\t\t\tthis.dispose();\n\n\t\t}\n\n\t\tthis.viewport.set( 0, 0, width, height );\n\t\tthis.scissor.set( 0, 0, width, height );\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tthis.width = source.width;\n\t\tthis.height = source.height;\n\t\tthis.depth = source.depth;\n\n\t\tthis.scissor.copy( source.scissor );\n\t\tthis.scissorTest = source.scissorTest;\n\n\t\tthis.viewport.copy( source.viewport );\n\n\t\tthis.texture = source.texture.clone();\n\t\tthis.texture.isRenderTargetTexture = true;\n\n\t\t// ensure image object is not shared, see #20328\n\n\t\tconst image = Object.assign( {}, source.texture.image );\n\t\tthis.texture.source = new Source( image );\n\n\t\tthis.depthBuffer = source.depthBuffer;\n\t\tthis.stencilBuffer = source.stencilBuffer;\n\n\t\tif ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();\n\n\t\tthis.samples = source.samples;\n\n\t\treturn this;\n\n\t}\n\n\tdispose() {\n\n\t\tthis.dispatchEvent( { type: 'dispose' } );\n\n\t}\n\n}\n\nclass DataArrayTexture extends Texture {\n\n\tconstructor( data = null, width = 1, height = 1, depth = 1 ) {\n\n\t\tsuper( null );\n\n\t\tthis.isDataArrayTexture = true;\n\n\t\tthis.image = { data, width, height, depth };\n\n\t\tthis.magFilter = NearestFilter;\n\t\tthis.minFilter = NearestFilter;\n\n\t\tthis.wrapR = ClampToEdgeWrapping;\n\n\t\tthis.generateMipmaps = false;\n\t\tthis.flipY = false;\n\t\tthis.unpackAlignment = 1;\n\n\t}\n\n}\n\nclass WebGLArrayRenderTarget extends WebGLRenderTarget {\n\n\tconstructor( width = 1, height = 1, depth = 1 ) {\n\n\t\tsuper( width, height );\n\n\t\tthis.isWebGLArrayRenderTarget = true;\n\n\t\tthis.depth = depth;\n\n\t\tthis.texture = new DataArrayTexture( null, width, height, depth );\n\n\t\tthis.texture.isRenderTargetTexture = true;\n\n\t}\n\n}\n\nclass Data3DTexture extends Texture {\n\n\tconstructor( data = null, width = 1, height = 1, depth = 1 ) {\n\n\t\t// We're going to add .setXXX() methods for setting properties later.\n\t\t// Users can still set in DataTexture3D directly.\n\t\t//\n\t\t//\tconst texture = new THREE.DataTexture3D( data, width, height, depth );\n\t\t// \ttexture.anisotropy = 16;\n\t\t//\n\t\t// See #14839\n\n\t\tsuper( null );\n\n\t\tthis.isData3DTexture = true;\n\n\t\tthis.image = { data, width, height, depth };\n\n\t\tthis.magFilter = NearestFilter;\n\t\tthis.minFilter = NearestFilter;\n\n\t\tthis.wrapR = ClampToEdgeWrapping;\n\n\t\tthis.generateMipmaps = false;\n\t\tthis.flipY = false;\n\t\tthis.unpackAlignment = 1;\n\n\t}\n\n}\n\nclass WebGL3DRenderTarget extends WebGLRenderTarget {\n\n\tconstructor( width = 1, height = 1, depth = 1 ) {\n\n\t\tsuper( width, height );\n\n\t\tthis.isWebGL3DRenderTarget = true;\n\n\t\tthis.depth = depth;\n\n\t\tthis.texture = new Data3DTexture( null, width, height, depth );\n\n\t\tthis.texture.isRenderTargetTexture = true;\n\n\t}\n\n}\n\nclass WebGLMultipleRenderTargets extends WebGLRenderTarget {\n\n\tconstructor( width = 1, height = 1, count = 1, options = {} ) {\n\n\t\tsuper( width, height, options );\n\n\t\tthis.isWebGLMultipleRenderTargets = true;\n\n\t\tconst texture = this.texture;\n\n\t\tthis.texture = [];\n\n\t\tfor ( let i = 0; i < count; i ++ ) {\n\n\t\t\tthis.texture[ i ] = texture.clone();\n\t\t\tthis.texture[ i ].isRenderTargetTexture = true;\n\n\t\t}\n\n\t}\n\n\tsetSize( width, height, depth = 1 ) {\n\n\t\tif ( this.width !== width || this.height !== height || this.depth !== depth ) {\n\n\t\t\tthis.width = width;\n\t\t\tthis.height = height;\n\t\t\tthis.depth = depth;\n\n\t\t\tfor ( let i = 0, il = this.texture.length; i < il; i ++ ) {\n\n\t\t\t\tthis.texture[ i ].image.width = width;\n\t\t\t\tthis.texture[ i ].image.height = height;\n\t\t\t\tthis.texture[ i ].image.depth = depth;\n\n\t\t\t}\n\n\t\t\tthis.dispose();\n\n\t\t}\n\n\t\tthis.viewport.set( 0, 0, width, height );\n\t\tthis.scissor.set( 0, 0, width, height );\n\n\t\treturn this;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tthis.dispose();\n\n\t\tthis.width = source.width;\n\t\tthis.height = source.height;\n\t\tthis.depth = source.depth;\n\n\t\tthis.scissor.copy( source.scissor );\n\t\tthis.scissorTest = source.scissorTest;\n\n\t\tthis.viewport.copy( source.viewport );\n\n\t\tthis.depthBuffer = source.depthBuffer;\n\t\tthis.stencilBuffer = source.stencilBuffer;\n\n\t\tif ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();\n\n\t\tthis.texture.length = 0;\n\n\t\tfor ( let i = 0, il = source.texture.length; i < il; i ++ ) {\n\n\t\t\tthis.texture[ i ] = source.texture[ i ].clone();\n\t\t\tthis.texture[ i ].isRenderTargetTexture = true;\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass Quaternion {\n\n\tconstructor( x = 0, y = 0, z = 0, w = 1 ) {\n\n\t\tthis.isQuaternion = true;\n\n\t\tthis._x = x;\n\t\tthis._y = y;\n\t\tthis._z = z;\n\t\tthis._w = w;\n\n\t}\n\n\tstatic slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {\n\n\t\t// fuzz-free, array-based Quaternion SLERP operation\n\n\t\tlet x0 = src0[ srcOffset0 + 0 ],\n\t\t\ty0 = src0[ srcOffset0 + 1 ],\n\t\t\tz0 = src0[ srcOffset0 + 2 ],\n\t\t\tw0 = src0[ srcOffset0 + 3 ];\n\n\t\tconst x1 = src1[ srcOffset1 + 0 ],\n\t\t\ty1 = src1[ srcOffset1 + 1 ],\n\t\t\tz1 = src1[ srcOffset1 + 2 ],\n\t\t\tw1 = src1[ srcOffset1 + 3 ];\n\n\t\tif ( t === 0 ) {\n\n\t\t\tdst[ dstOffset + 0 ] = x0;\n\t\t\tdst[ dstOffset + 1 ] = y0;\n\t\t\tdst[ dstOffset + 2 ] = z0;\n\t\t\tdst[ dstOffset + 3 ] = w0;\n\t\t\treturn;\n\n\t\t}\n\n\t\tif ( t === 1 ) {\n\n\t\t\tdst[ dstOffset + 0 ] = x1;\n\t\t\tdst[ dstOffset + 1 ] = y1;\n\t\t\tdst[ dstOffset + 2 ] = z1;\n\t\t\tdst[ dstOffset + 3 ] = w1;\n\t\t\treturn;\n\n\t\t}\n\n\t\tif ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {\n\n\t\t\tlet s = 1 - t;\n\t\t\tconst cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,\n\t\t\t\tdir = ( cos >= 0 ? 1 : - 1 ),\n\t\t\t\tsqrSin = 1 - cos * cos;\n\n\t\t\t// Skip the Slerp for tiny steps to avoid numeric problems:\n\t\t\tif ( sqrSin > Number.EPSILON ) {\n\n\t\t\t\tconst sin = Math.sqrt( sqrSin ),\n\t\t\t\t\tlen = Math.atan2( sin, cos * dir );\n\n\t\t\t\ts = Math.sin( s * len ) / sin;\n\t\t\t\tt = Math.sin( t * len ) / sin;\n\n\t\t\t}\n\n\t\t\tconst tDir = t * dir;\n\n\t\t\tx0 = x0 * s + x1 * tDir;\n\t\t\ty0 = y0 * s + y1 * tDir;\n\t\t\tz0 = z0 * s + z1 * tDir;\n\t\t\tw0 = w0 * s + w1 * tDir;\n\n\t\t\t// Normalize in case we just did a lerp:\n\t\t\tif ( s === 1 - t ) {\n\n\t\t\t\tconst f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );\n\n\t\t\t\tx0 *= f;\n\t\t\t\ty0 *= f;\n\t\t\t\tz0 *= f;\n\t\t\t\tw0 *= f;\n\n\t\t\t}\n\n\t\t}\n\n\t\tdst[ dstOffset ] = x0;\n\t\tdst[ dstOffset + 1 ] = y0;\n\t\tdst[ dstOffset + 2 ] = z0;\n\t\tdst[ dstOffset + 3 ] = w0;\n\n\t}\n\n\tstatic multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {\n\n\t\tconst x0 = src0[ srcOffset0 ];\n\t\tconst y0 = src0[ srcOffset0 + 1 ];\n\t\tconst z0 = src0[ srcOffset0 + 2 ];\n\t\tconst w0 = src0[ srcOffset0 + 3 ];\n\n\t\tconst x1 = src1[ srcOffset1 ];\n\t\tconst y1 = src1[ srcOffset1 + 1 ];\n\t\tconst z1 = src1[ srcOffset1 + 2 ];\n\t\tconst w1 = src1[ srcOffset1 + 3 ];\n\n\t\tdst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;\n\t\tdst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;\n\t\tdst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;\n\t\tdst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;\n\n\t\treturn dst;\n\n\t}\n\n\tget x() {\n\n\t\treturn this._x;\n\n\t}\n\n\tset x( value ) {\n\n\t\tthis._x = value;\n\t\tthis._onChangeCallback();\n\n\t}\n\n\tget y() {\n\n\t\treturn this._y;\n\n\t}\n\n\tset y( value ) {\n\n\t\tthis._y = value;\n\t\tthis._onChangeCallback();\n\n\t}\n\n\tget z() {\n\n\t\treturn this._z;\n\n\t}\n\n\tset z( value ) {\n\n\t\tthis._z = value;\n\t\tthis._onChangeCallback();\n\n\t}\n\n\tget w() {\n\n\t\treturn this._w;\n\n\t}\n\n\tset w( value ) {\n\n\t\tthis._w = value;\n\t\tthis._onChangeCallback();\n\n\t}\n\n\tset( x, y, z, w ) {\n\n\t\tthis._x = x;\n\t\tthis._y = y;\n\t\tthis._z = z;\n\t\tthis._w = w;\n\n\t\tthis._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor( this._x, this._y, this._z, this._w );\n\n\t}\n\n\tcopy( quaternion ) {\n\n\t\tthis._x = quaternion.x;\n\t\tthis._y = quaternion.y;\n\t\tthis._z = quaternion.z;\n\t\tthis._w = quaternion.w;\n\n\t\tthis._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\tsetFromEuler( euler, update ) {\n\n\t\tconst x = euler._x, y = euler._y, z = euler._z, order = euler._order;\n\n\t\t// http://www.mathworks.com/matlabcentral/fileexchange/\n\t\t// \t20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/\n\t\t//\tcontent/SpinCalc.m\n\n\t\tconst cos = Math.cos;\n\t\tconst sin = Math.sin;\n\n\t\tconst c1 = cos( x / 2 );\n\t\tconst c2 = cos( y / 2 );\n\t\tconst c3 = cos( z / 2 );\n\n\t\tconst s1 = sin( x / 2 );\n\t\tconst s2 = sin( y / 2 );\n\t\tconst s3 = sin( z / 2 );\n\n\t\tswitch ( order ) {\n\n\t\t\tcase 'XYZ':\n\t\t\t\tthis._x = s1 * c2 * c3 + c1 * s2 * s3;\n\t\t\t\tthis._y = c1 * s2 * c3 - s1 * c2 * s3;\n\t\t\t\tthis._z = c1 * c2 * s3 + s1 * s2 * c3;\n\t\t\t\tthis._w = c1 * c2 * c3 - s1 * s2 * s3;\n\t\t\t\tbreak;\n\n\t\t\tcase 'YXZ':\n\t\t\t\tthis._x = s1 * c2 * c3 + c1 * s2 * s3;\n\t\t\t\tthis._y = c1 * s2 * c3 - s1 * c2 * s3;\n\t\t\t\tthis._z = c1 * c2 * s3 - s1 * s2 * c3;\n\t\t\t\tthis._w = c1 * c2 * c3 + s1 * s2 * s3;\n\t\t\t\tbreak;\n\n\t\t\tcase 'ZXY':\n\t\t\t\tthis._x = s1 * c2 * c3 - c1 * s2 * s3;\n\t\t\t\tthis._y = c1 * s2 * c3 + s1 * c2 * s3;\n\t\t\t\tthis._z = c1 * c2 * s3 + s1 * s2 * c3;\n\t\t\t\tthis._w = c1 * c2 * c3 - s1 * s2 * s3;\n\t\t\t\tbreak;\n\n\t\t\tcase 'ZYX':\n\t\t\t\tthis._x = s1 * c2 * c3 - c1 * s2 * s3;\n\t\t\t\tthis._y = c1 * s2 * c3 + s1 * c2 * s3;\n\t\t\t\tthis._z = c1 * c2 * s3 - s1 * s2 * c3;\n\t\t\t\tthis._w = c1 * c2 * c3 + s1 * s2 * s3;\n\t\t\t\tbreak;\n\n\t\t\tcase 'YZX':\n\t\t\t\tthis._x = s1 * c2 * c3 + c1 * s2 * s3;\n\t\t\t\tthis._y = c1 * s2 * c3 + s1 * c2 * s3;\n\t\t\t\tthis._z = c1 * c2 * s3 - s1 * s2 * c3;\n\t\t\t\tthis._w = c1 * c2 * c3 - s1 * s2 * s3;\n\t\t\t\tbreak;\n\n\t\t\tcase 'XZY':\n\t\t\t\tthis._x = s1 * c2 * c3 - c1 * s2 * s3;\n\t\t\t\tthis._y = c1 * s2 * c3 - s1 * c2 * s3;\n\t\t\t\tthis._z = c1 * c2 * s3 + s1 * s2 * c3;\n\t\t\t\tthis._w = c1 * c2 * c3 + s1 * s2 * s3;\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tconsole.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );\n\n\t\t}\n\n\t\tif ( update !== false ) this._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\tsetFromAxisAngle( axis, angle ) {\n\n\t\t// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm\n\n\t\t// assumes axis is normalized\n\n\t\tconst halfAngle = angle / 2, s = Math.sin( halfAngle );\n\n\t\tthis._x = axis.x * s;\n\t\tthis._y = axis.y * s;\n\t\tthis._z = axis.z * s;\n\t\tthis._w = Math.cos( halfAngle );\n\n\t\tthis._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\tsetFromRotationMatrix( m ) {\n\n\t\t// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm\n\n\t\t// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)\n\n\t\tconst te = m.elements,\n\n\t\t\tm11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],\n\t\t\tm21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],\n\t\t\tm31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],\n\n\t\t\ttrace = m11 + m22 + m33;\n\n\t\tif ( trace > 0 ) {\n\n\t\t\tconst s = 0.5 / Math.sqrt( trace + 1.0 );\n\n\t\t\tthis._w = 0.25 / s;\n\t\t\tthis._x = ( m32 - m23 ) * s;\n\t\t\tthis._y = ( m13 - m31 ) * s;\n\t\t\tthis._z = ( m21 - m12 ) * s;\n\n\t\t} else if ( m11 > m22 && m11 > m33 ) {\n\n\t\t\tconst s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );\n\n\t\t\tthis._w = ( m32 - m23 ) / s;\n\t\t\tthis._x = 0.25 * s;\n\t\t\tthis._y = ( m12 + m21 ) / s;\n\t\t\tthis._z = ( m13 + m31 ) / s;\n\n\t\t} else if ( m22 > m33 ) {\n\n\t\t\tconst s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );\n\n\t\t\tthis._w = ( m13 - m31 ) / s;\n\t\t\tthis._x = ( m12 + m21 ) / s;\n\t\t\tthis._y = 0.25 * s;\n\t\t\tthis._z = ( m23 + m32 ) / s;\n\n\t\t} else {\n\n\t\t\tconst s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );\n\n\t\t\tthis._w = ( m21 - m12 ) / s;\n\t\t\tthis._x = ( m13 + m31 ) / s;\n\t\t\tthis._y = ( m23 + m32 ) / s;\n\t\t\tthis._z = 0.25 * s;\n\n\t\t}\n\n\t\tthis._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\tsetFromUnitVectors( vFrom, vTo ) {\n\n\t\t// assumes direction vectors vFrom and vTo are normalized\n\n\t\tlet r = vFrom.dot( vTo ) + 1;\n\n\t\tif ( r < Number.EPSILON ) {\n\n\t\t\t// vFrom and vTo point in opposite directions\n\n\t\t\tr = 0;\n\n\t\t\tif ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {\n\n\t\t\t\tthis._x = - vFrom.y;\n\t\t\t\tthis._y = vFrom.x;\n\t\t\t\tthis._z = 0;\n\t\t\t\tthis._w = r;\n\n\t\t\t} else {\n\n\t\t\t\tthis._x = 0;\n\t\t\t\tthis._y = - vFrom.z;\n\t\t\t\tthis._z = vFrom.y;\n\t\t\t\tthis._w = r;\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\t// crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3\n\n\t\t\tthis._x = vFrom.y * vTo.z - vFrom.z * vTo.y;\n\t\t\tthis._y = vFrom.z * vTo.x - vFrom.x * vTo.z;\n\t\t\tthis._z = vFrom.x * vTo.y - vFrom.y * vTo.x;\n\t\t\tthis._w = r;\n\n\t\t}\n\n\t\treturn this.normalize();\n\n\t}\n\n\tangleTo( q ) {\n\n\t\treturn 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );\n\n\t}\n\n\trotateTowards( q, step ) {\n\n\t\tconst angle = this.angleTo( q );\n\n\t\tif ( angle === 0 ) return this;\n\n\t\tconst t = Math.min( 1, step / angle );\n\n\t\tthis.slerp( q, t );\n\n\t\treturn this;\n\n\t}\n\n\tidentity() {\n\n\t\treturn this.set( 0, 0, 0, 1 );\n\n\t}\n\n\tinvert() {\n\n\t\t// quaternion is assumed to have unit length\n\n\t\treturn this.conjugate();\n\n\t}\n\n\tconjugate() {\n\n\t\tthis._x *= - 1;\n\t\tthis._y *= - 1;\n\t\tthis._z *= - 1;\n\n\t\tthis._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\tdot( v ) {\n\n\t\treturn this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;\n\n\t}\n\n\tlengthSq() {\n\n\t\treturn this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;\n\n\t}\n\n\tlength() {\n\n\t\treturn Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );\n\n\t}\n\n\tnormalize() {\n\n\t\tlet l = this.length();\n\n\t\tif ( l === 0 ) {\n\n\t\t\tthis._x = 0;\n\t\t\tthis._y = 0;\n\t\t\tthis._z = 0;\n\t\t\tthis._w = 1;\n\n\t\t} else {\n\n\t\t\tl = 1 / l;\n\n\t\t\tthis._x = this._x * l;\n\t\t\tthis._y = this._y * l;\n\t\t\tthis._z = this._z * l;\n\t\t\tthis._w = this._w * l;\n\n\t\t}\n\n\t\tthis._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\tmultiply( q ) {\n\n\t\treturn this.multiplyQuaternions( this, q );\n\n\t}\n\n\tpremultiply( q ) {\n\n\t\treturn this.multiplyQuaternions( q, this );\n\n\t}\n\n\tmultiplyQuaternions( a, b ) {\n\n\t\t// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm\n\n\t\tconst qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;\n\t\tconst qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;\n\n\t\tthis._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;\n\t\tthis._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;\n\t\tthis._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;\n\t\tthis._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;\n\n\t\tthis._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\tslerp( qb, t ) {\n\n\t\tif ( t === 0 ) return this;\n\t\tif ( t === 1 ) return this.copy( qb );\n\n\t\tconst x = this._x, y = this._y, z = this._z, w = this._w;\n\n\t\t// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/\n\n\t\tlet cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;\n\n\t\tif ( cosHalfTheta < 0 ) {\n\n\t\t\tthis._w = - qb._w;\n\t\t\tthis._x = - qb._x;\n\t\t\tthis._y = - qb._y;\n\t\t\tthis._z = - qb._z;\n\n\t\t\tcosHalfTheta = - cosHalfTheta;\n\n\t\t} else {\n\n\t\t\tthis.copy( qb );\n\n\t\t}\n\n\t\tif ( cosHalfTheta >= 1.0 ) {\n\n\t\t\tthis._w = w;\n\t\t\tthis._x = x;\n\t\t\tthis._y = y;\n\t\t\tthis._z = z;\n\n\t\t\treturn this;\n\n\t\t}\n\n\t\tconst sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;\n\n\t\tif ( sqrSinHalfTheta <= Number.EPSILON ) {\n\n\t\t\tconst s = 1 - t;\n\t\t\tthis._w = s * w + t * this._w;\n\t\t\tthis._x = s * x + t * this._x;\n\t\t\tthis._y = s * y + t * this._y;\n\t\t\tthis._z = s * z + t * this._z;\n\n\t\t\tthis.normalize();\n\t\t\tthis._onChangeCallback();\n\n\t\t\treturn this;\n\n\t\t}\n\n\t\tconst sinHalfTheta = Math.sqrt( sqrSinHalfTheta );\n\t\tconst halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );\n\t\tconst ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,\n\t\t\tratioB = Math.sin( t * halfTheta ) / sinHalfTheta;\n\n\t\tthis._w = ( w * ratioA + this._w * ratioB );\n\t\tthis._x = ( x * ratioA + this._x * ratioB );\n\t\tthis._y = ( y * ratioA + this._y * ratioB );\n\t\tthis._z = ( z * ratioA + this._z * ratioB );\n\n\t\tthis._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\tslerpQuaternions( qa, qb, t ) {\n\n\t\treturn this.copy( qa ).slerp( qb, t );\n\n\t}\n\n\trandom() {\n\n\t\t// Derived from http://planning.cs.uiuc.edu/node198.html\n\t\t// Note, this source uses w, x, y, z ordering,\n\t\t// so we swap the order below.\n\n\t\tconst u1 = Math.random();\n\t\tconst sqrt1u1 = Math.sqrt( 1 - u1 );\n\t\tconst sqrtu1 = Math.sqrt( u1 );\n\n\t\tconst u2 = 2 * Math.PI * Math.random();\n\n\t\tconst u3 = 2 * Math.PI * Math.random();\n\n\t\treturn this.set(\n\t\t\tsqrt1u1 * Math.cos( u2 ),\n\t\t\tsqrtu1 * Math.sin( u3 ),\n\t\t\tsqrtu1 * Math.cos( u3 ),\n\t\t\tsqrt1u1 * Math.sin( u2 ),\n\t\t);\n\n\t}\n\n\tequals( quaternion ) {\n\n\t\treturn ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );\n\n\t}\n\n\tfromArray( array, offset = 0 ) {\n\n\t\tthis._x = array[ offset ];\n\t\tthis._y = array[ offset + 1 ];\n\t\tthis._z = array[ offset + 2 ];\n\t\tthis._w = array[ offset + 3 ];\n\n\t\tthis._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\ttoArray( array = [], offset = 0 ) {\n\n\t\tarray[ offset ] = this._x;\n\t\tarray[ offset + 1 ] = this._y;\n\t\tarray[ offset + 2 ] = this._z;\n\t\tarray[ offset + 3 ] = this._w;\n\n\t\treturn array;\n\n\t}\n\n\tfromBufferAttribute( attribute, index ) {\n\n\t\tthis._x = attribute.getX( index );\n\t\tthis._y = attribute.getY( index );\n\t\tthis._z = attribute.getZ( index );\n\t\tthis._w = attribute.getW( index );\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\treturn this.toArray();\n\n\t}\n\n\t_onChange( callback ) {\n\n\t\tthis._onChangeCallback = callback;\n\n\t\treturn this;\n\n\t}\n\n\t_onChangeCallback() {}\n\n\t*[ Symbol.iterator ]() {\n\n\t\tyield this._x;\n\t\tyield this._y;\n\t\tyield this._z;\n\t\tyield this._w;\n\n\t}\n\n}\n\nclass Vector3 {\n\n\tconstructor( x = 0, y = 0, z = 0 ) {\n\n\t\tVector3.prototype.isVector3 = true;\n\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.z = z;\n\n\t}\n\n\tset( x, y, z ) {\n\n\t\tif ( z === undefined ) z = this.z; // sprite.scale.set(x,y)\n\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.z = z;\n\n\t\treturn this;\n\n\t}\n\n\tsetScalar( scalar ) {\n\n\t\tthis.x = scalar;\n\t\tthis.y = scalar;\n\t\tthis.z = scalar;\n\n\t\treturn this;\n\n\t}\n\n\tsetX( x ) {\n\n\t\tthis.x = x;\n\n\t\treturn this;\n\n\t}\n\n\tsetY( y ) {\n\n\t\tthis.y = y;\n\n\t\treturn this;\n\n\t}\n\n\tsetZ( z ) {\n\n\t\tthis.z = z;\n\n\t\treturn this;\n\n\t}\n\n\tsetComponent( index, value ) {\n\n\t\tswitch ( index ) {\n\n\t\t\tcase 0: this.x = value; break;\n\t\t\tcase 1: this.y = value; break;\n\t\t\tcase 2: this.z = value; break;\n\t\t\tdefault: throw new Error( 'index is out of range: ' + index );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tgetComponent( index ) {\n\n\t\tswitch ( index ) {\n\n\t\t\tcase 0: return this.x;\n\t\t\tcase 1: return this.y;\n\t\t\tcase 2: return this.z;\n\t\t\tdefault: throw new Error( 'index is out of range: ' + index );\n\n\t\t}\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor( this.x, this.y, this.z );\n\n\t}\n\n\tcopy( v ) {\n\n\t\tthis.x = v.x;\n\t\tthis.y = v.y;\n\t\tthis.z = v.z;\n\n\t\treturn this;\n\n\t}\n\n\tadd( v ) {\n\n\t\tthis.x += v.x;\n\t\tthis.y += v.y;\n\t\tthis.z += v.z;\n\n\t\treturn this;\n\n\t}\n\n\taddScalar( s ) {\n\n\t\tthis.x += s;\n\t\tthis.y += s;\n\t\tthis.z += s;\n\n\t\treturn this;\n\n\t}\n\n\taddVectors( a, b ) {\n\n\t\tthis.x = a.x + b.x;\n\t\tthis.y = a.y + b.y;\n\t\tthis.z = a.z + b.z;\n\n\t\treturn this;\n\n\t}\n\n\taddScaledVector( v, s ) {\n\n\t\tthis.x += v.x * s;\n\t\tthis.y += v.y * s;\n\t\tthis.z += v.z * s;\n\n\t\treturn this;\n\n\t}\n\n\tsub( v ) {\n\n\t\tthis.x -= v.x;\n\t\tthis.y -= v.y;\n\t\tthis.z -= v.z;\n\n\t\treturn this;\n\n\t}\n\n\tsubScalar( s ) {\n\n\t\tthis.x -= s;\n\t\tthis.y -= s;\n\t\tthis.z -= s;\n\n\t\treturn this;\n\n\t}\n\n\tsubVectors( a, b ) {\n\n\t\tthis.x = a.x - b.x;\n\t\tthis.y = a.y - b.y;\n\t\tthis.z = a.z - b.z;\n\n\t\treturn this;\n\n\t}\n\n\tmultiply( v ) {\n\n\t\tthis.x *= v.x;\n\t\tthis.y *= v.y;\n\t\tthis.z *= v.z;\n\n\t\treturn this;\n\n\t}\n\n\tmultiplyScalar( scalar ) {\n\n\t\tthis.x *= scalar;\n\t\tthis.y *= scalar;\n\t\tthis.z *= scalar;\n\n\t\treturn this;\n\n\t}\n\n\tmultiplyVectors( a, b ) {\n\n\t\tthis.x = a.x * b.x;\n\t\tthis.y = a.y * b.y;\n\t\tthis.z = a.z * b.z;\n\n\t\treturn this;\n\n\t}\n\n\tapplyEuler( euler ) {\n\n\t\treturn this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );\n\n\t}\n\n\tapplyAxisAngle( axis, angle ) {\n\n\t\treturn this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );\n\n\t}\n\n\tapplyMatrix3( m ) {\n\n\t\tconst x = this.x, y = this.y, z = this.z;\n\t\tconst e = m.elements;\n\n\t\tthis.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;\n\t\tthis.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;\n\t\tthis.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;\n\n\t\treturn this;\n\n\t}\n\n\tapplyNormalMatrix( m ) {\n\n\t\treturn this.applyMatrix3( m ).normalize();\n\n\t}\n\n\tapplyMatrix4( m ) {\n\n\t\tconst x = this.x, y = this.y, z = this.z;\n\t\tconst e = m.elements;\n\n\t\tconst w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );\n\n\t\tthis.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;\n\t\tthis.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;\n\t\tthis.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;\n\n\t\treturn this;\n\n\t}\n\n\tapplyQuaternion( q ) {\n\n\t\tconst x = this.x, y = this.y, z = this.z;\n\t\tconst qx = q.x, qy = q.y, qz = q.z, qw = q.w;\n\n\t\t// calculate quat * vector\n\n\t\tconst ix = qw * x + qy * z - qz * y;\n\t\tconst iy = qw * y + qz * x - qx * z;\n\t\tconst iz = qw * z + qx * y - qy * x;\n\t\tconst iw = - qx * x - qy * y - qz * z;\n\n\t\t// calculate result * inverse quat\n\n\t\tthis.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;\n\t\tthis.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;\n\t\tthis.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;\n\n\t\treturn this;\n\n\t}\n\n\tproject( camera ) {\n\n\t\treturn this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );\n\n\t}\n\n\tunproject( camera ) {\n\n\t\treturn this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );\n\n\t}\n\n\ttransformDirection( m ) {\n\n\t\t// input: THREE.Matrix4 affine matrix\n\t\t// vector interpreted as a direction\n\n\t\tconst x = this.x, y = this.y, z = this.z;\n\t\tconst e = m.elements;\n\n\t\tthis.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;\n\t\tthis.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;\n\t\tthis.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;\n\n\t\treturn this.normalize();\n\n\t}\n\n\tdivide( v ) {\n\n\t\tthis.x /= v.x;\n\t\tthis.y /= v.y;\n\t\tthis.z /= v.z;\n\n\t\treturn this;\n\n\t}\n\n\tdivideScalar( scalar ) {\n\n\t\treturn this.multiplyScalar( 1 / scalar );\n\n\t}\n\n\tmin( v ) {\n\n\t\tthis.x = Math.min( this.x, v.x );\n\t\tthis.y = Math.min( this.y, v.y );\n\t\tthis.z = Math.min( this.z, v.z );\n\n\t\treturn this;\n\n\t}\n\n\tmax( v ) {\n\n\t\tthis.x = Math.max( this.x, v.x );\n\t\tthis.y = Math.max( this.y, v.y );\n\t\tthis.z = Math.max( this.z, v.z );\n\n\t\treturn this;\n\n\t}\n\n\tclamp( min, max ) {\n\n\t\t// assumes min < max, componentwise\n\n\t\tthis.x = Math.max( min.x, Math.min( max.x, this.x ) );\n\t\tthis.y = Math.max( min.y, Math.min( max.y, this.y ) );\n\t\tthis.z = Math.max( min.z, Math.min( max.z, this.z ) );\n\n\t\treturn this;\n\n\t}\n\n\tclampScalar( minVal, maxVal ) {\n\n\t\tthis.x = Math.max( minVal, Math.min( maxVal, this.x ) );\n\t\tthis.y = Math.max( minVal, Math.min( maxVal, this.y ) );\n\t\tthis.z = Math.max( minVal, Math.min( maxVal, this.z ) );\n\n\t\treturn this;\n\n\t}\n\n\tclampLength( min, max ) {\n\n\t\tconst length = this.length();\n\n\t\treturn this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );\n\n\t}\n\n\tfloor() {\n\n\t\tthis.x = Math.floor( this.x );\n\t\tthis.y = Math.floor( this.y );\n\t\tthis.z = Math.floor( this.z );\n\n\t\treturn this;\n\n\t}\n\n\tceil() {\n\n\t\tthis.x = Math.ceil( this.x );\n\t\tthis.y = Math.ceil( this.y );\n\t\tthis.z = Math.ceil( this.z );\n\n\t\treturn this;\n\n\t}\n\n\tround() {\n\n\t\tthis.x = Math.round( this.x );\n\t\tthis.y = Math.round( this.y );\n\t\tthis.z = Math.round( this.z );\n\n\t\treturn this;\n\n\t}\n\n\troundToZero() {\n\n\t\tthis.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );\n\t\tthis.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );\n\t\tthis.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );\n\n\t\treturn this;\n\n\t}\n\n\tnegate() {\n\n\t\tthis.x = - this.x;\n\t\tthis.y = - this.y;\n\t\tthis.z = - this.z;\n\n\t\treturn this;\n\n\t}\n\n\tdot( v ) {\n\n\t\treturn this.x * v.x + this.y * v.y + this.z * v.z;\n\n\t}\n\n\t// TODO lengthSquared?\n\n\tlengthSq() {\n\n\t\treturn this.x * this.x + this.y * this.y + this.z * this.z;\n\n\t}\n\n\tlength() {\n\n\t\treturn Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );\n\n\t}\n\n\tmanhattanLength() {\n\n\t\treturn Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );\n\n\t}\n\n\tnormalize() {\n\n\t\treturn this.divideScalar( this.length() || 1 );\n\n\t}\n\n\tsetLength( length ) {\n\n\t\treturn this.normalize().multiplyScalar( length );\n\n\t}\n\n\tlerp( v, alpha ) {\n\n\t\tthis.x += ( v.x - this.x ) * alpha;\n\t\tthis.y += ( v.y - this.y ) * alpha;\n\t\tthis.z += ( v.z - this.z ) * alpha;\n\n\t\treturn this;\n\n\t}\n\n\tlerpVectors( v1, v2, alpha ) {\n\n\t\tthis.x = v1.x + ( v2.x - v1.x ) * alpha;\n\t\tthis.y = v1.y + ( v2.y - v1.y ) * alpha;\n\t\tthis.z = v1.z + ( v2.z - v1.z ) * alpha;\n\n\t\treturn this;\n\n\t}\n\n\tcross( v ) {\n\n\t\treturn this.crossVectors( this, v );\n\n\t}\n\n\tcrossVectors( a, b ) {\n\n\t\tconst ax = a.x, ay = a.y, az = a.z;\n\t\tconst bx = b.x, by = b.y, bz = b.z;\n\n\t\tthis.x = ay * bz - az * by;\n\t\tthis.y = az * bx - ax * bz;\n\t\tthis.z = ax * by - ay * bx;\n\n\t\treturn this;\n\n\t}\n\n\tprojectOnVector( v ) {\n\n\t\tconst denominator = v.lengthSq();\n\n\t\tif ( denominator === 0 ) return this.set( 0, 0, 0 );\n\n\t\tconst scalar = v.dot( this ) / denominator;\n\n\t\treturn this.copy( v ).multiplyScalar( scalar );\n\n\t}\n\n\tprojectOnPlane( planeNormal ) {\n\n\t\t_vector$b.copy( this ).projectOnVector( planeNormal );\n\n\t\treturn this.sub( _vector$b );\n\n\t}\n\n\treflect( normal ) {\n\n\t\t// reflect incident vector off plane orthogonal to normal\n\t\t// normal is assumed to have unit length\n\n\t\treturn this.sub( _vector$b.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );\n\n\t}\n\n\tangleTo( v ) {\n\n\t\tconst denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );\n\n\t\tif ( denominator === 0 ) return Math.PI / 2;\n\n\t\tconst theta = this.dot( v ) / denominator;\n\n\t\t// clamp, to handle numerical problems\n\n\t\treturn Math.acos( clamp( theta, - 1, 1 ) );\n\n\t}\n\n\tdistanceTo( v ) {\n\n\t\treturn Math.sqrt( this.distanceToSquared( v ) );\n\n\t}\n\n\tdistanceToSquared( v ) {\n\n\t\tconst dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;\n\n\t\treturn dx * dx + dy * dy + dz * dz;\n\n\t}\n\n\tmanhattanDistanceTo( v ) {\n\n\t\treturn Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );\n\n\t}\n\n\tsetFromSpherical( s ) {\n\n\t\treturn this.setFromSphericalCoords( s.radius, s.phi, s.theta );\n\n\t}\n\n\tsetFromSphericalCoords( radius, phi, theta ) {\n\n\t\tconst sinPhiRadius = Math.sin( phi ) * radius;\n\n\t\tthis.x = sinPhiRadius * Math.sin( theta );\n\t\tthis.y = Math.cos( phi ) * radius;\n\t\tthis.z = sinPhiRadius * Math.cos( theta );\n\n\t\treturn this;\n\n\t}\n\n\tsetFromCylindrical( c ) {\n\n\t\treturn this.setFromCylindricalCoords( c.radius, c.theta, c.y );\n\n\t}\n\n\tsetFromCylindricalCoords( radius, theta, y ) {\n\n\t\tthis.x = radius * Math.sin( theta );\n\t\tthis.y = y;\n\t\tthis.z = radius * Math.cos( theta );\n\n\t\treturn this;\n\n\t}\n\n\tsetFromMatrixPosition( m ) {\n\n\t\tconst e = m.elements;\n\n\t\tthis.x = e[ 12 ];\n\t\tthis.y = e[ 13 ];\n\t\tthis.z = e[ 14 ];\n\n\t\treturn this;\n\n\t}\n\n\tsetFromMatrixScale( m ) {\n\n\t\tconst sx = this.setFromMatrixColumn( m, 0 ).length();\n\t\tconst sy = this.setFromMatrixColumn( m, 1 ).length();\n\t\tconst sz = this.setFromMatrixColumn( m, 2 ).length();\n\n\t\tthis.x = sx;\n\t\tthis.y = sy;\n\t\tthis.z = sz;\n\n\t\treturn this;\n\n\t}\n\n\tsetFromMatrixColumn( m, index ) {\n\n\t\treturn this.fromArray( m.elements, index * 4 );\n\n\t}\n\n\tsetFromMatrix3Column( m, index ) {\n\n\t\treturn this.fromArray( m.elements, index * 3 );\n\n\t}\n\n\tsetFromEuler( e ) {\n\n\t\tthis.x = e._x;\n\t\tthis.y = e._y;\n\t\tthis.z = e._z;\n\n\t\treturn this;\n\n\t}\n\n\tsetFromColor( c ) {\n\n\t\tthis.x = c.r;\n\t\tthis.y = c.g;\n\t\tthis.z = c.b;\n\n\t\treturn this;\n\n\t}\n\n\tequals( v ) {\n\n\t\treturn ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );\n\n\t}\n\n\tfromArray( array, offset = 0 ) {\n\n\t\tthis.x = array[ offset ];\n\t\tthis.y = array[ offset + 1 ];\n\t\tthis.z = array[ offset + 2 ];\n\n\t\treturn this;\n\n\t}\n\n\ttoArray( array = [], offset = 0 ) {\n\n\t\tarray[ offset ] = this.x;\n\t\tarray[ offset + 1 ] = this.y;\n\t\tarray[ offset + 2 ] = this.z;\n\n\t\treturn array;\n\n\t}\n\n\tfromBufferAttribute( attribute, index ) {\n\n\t\tthis.x = attribute.getX( index );\n\t\tthis.y = attribute.getY( index );\n\t\tthis.z = attribute.getZ( index );\n\n\t\treturn this;\n\n\t}\n\n\trandom() {\n\n\t\tthis.x = Math.random();\n\t\tthis.y = Math.random();\n\t\tthis.z = Math.random();\n\n\t\treturn this;\n\n\t}\n\n\trandomDirection() {\n\n\t\t// Derived from https://mathworld.wolfram.com/SpherePointPicking.html\n\n\t\tconst u = ( Math.random() - 0.5 ) * 2;\n\t\tconst t = Math.random() * Math.PI * 2;\n\t\tconst f = Math.sqrt( 1 - u ** 2 );\n\n\t\tthis.x = f * Math.cos( t );\n\t\tthis.y = f * Math.sin( t );\n\t\tthis.z = u;\n\n\t\treturn this;\n\n\t}\n\n\t*[ Symbol.iterator ]() {\n\n\t\tyield this.x;\n\t\tyield this.y;\n\t\tyield this.z;\n\n\t}\n\n}\n\nconst _vector$b = /*@__PURE__*/ new Vector3();\nconst _quaternion$4 = /*@__PURE__*/ new Quaternion();\n\nclass Box3 {\n\n\tconstructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {\n\n\t\tthis.isBox3 = true;\n\n\t\tthis.min = min;\n\t\tthis.max = max;\n\n\t}\n\n\tset( min, max ) {\n\n\t\tthis.min.copy( min );\n\t\tthis.max.copy( max );\n\n\t\treturn this;\n\n\t}\n\n\tsetFromArray( array ) {\n\n\t\tthis.makeEmpty();\n\n\t\tfor ( let i = 0, il = array.length; i < il; i += 3 ) {\n\n\t\t\tthis.expandByPoint( _vector$a.fromArray( array, i ) );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tsetFromBufferAttribute( attribute ) {\n\n\t\tthis.makeEmpty();\n\n\t\tfor ( let i = 0, il = attribute.count; i < il; i ++ ) {\n\n\t\t\tthis.expandByPoint( _vector$a.fromBufferAttribute( attribute, i ) );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tsetFromPoints( points ) {\n\n\t\tthis.makeEmpty();\n\n\t\tfor ( let i = 0, il = points.length; i < il; i ++ ) {\n\n\t\t\tthis.expandByPoint( points[ i ] );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tsetFromCenterAndSize( center, size ) {\n\n\t\tconst halfSize = _vector$a.copy( size ).multiplyScalar( 0.5 );\n\n\t\tthis.min.copy( center ).sub( halfSize );\n\t\tthis.max.copy( center ).add( halfSize );\n\n\t\treturn this;\n\n\t}\n\n\tsetFromObject( object, precise = false ) {\n\n\t\tthis.makeEmpty();\n\n\t\treturn this.expandByObject( object, precise );\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n\tcopy( box ) {\n\n\t\tthis.min.copy( box.min );\n\t\tthis.max.copy( box.max );\n\n\t\treturn this;\n\n\t}\n\n\tmakeEmpty() {\n\n\t\tthis.min.x = this.min.y = this.min.z = + Infinity;\n\t\tthis.max.x = this.max.y = this.max.z = - Infinity;\n\n\t\treturn this;\n\n\t}\n\n\tisEmpty() {\n\n\t\t// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes\n\n\t\treturn ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );\n\n\t}\n\n\tgetCenter( target ) {\n\n\t\treturn this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );\n\n\t}\n\n\tgetSize( target ) {\n\n\t\treturn this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );\n\n\t}\n\n\texpandByPoint( point ) {\n\n\t\tthis.min.min( point );\n\t\tthis.max.max( point );\n\n\t\treturn this;\n\n\t}\n\n\texpandByVector( vector ) {\n\n\t\tthis.min.sub( vector );\n\t\tthis.max.add( vector );\n\n\t\treturn this;\n\n\t}\n\n\texpandByScalar( scalar ) {\n\n\t\tthis.min.addScalar( - scalar );\n\t\tthis.max.addScalar( scalar );\n\n\t\treturn this;\n\n\t}\n\n\texpandByObject( object, precise = false ) {\n\n\t\t// Computes the world-axis-aligned bounding box of an object (including its children),\n\t\t// accounting for both the object's, and children's, world transforms\n\n\t\tobject.updateWorldMatrix( false, false );\n\n\t\tif ( object.boundingBox !== undefined ) {\n\n\t\t\tif ( object.boundingBox === null ) {\n\n\t\t\t\tobject.computeBoundingBox();\n\n\t\t\t}\n\n\t\t\t_box$3.copy( object.boundingBox );\n\t\t\t_box$3.applyMatrix4( object.matrixWorld );\n\n\t\t\tthis.union( _box$3 );\n\n\t\t} else {\n\n\t\t\tconst geometry = object.geometry;\n\n\t\t\tif ( geometry !== undefined ) {\n\n\t\t\t\tif ( precise && geometry.attributes !== undefined && geometry.attributes.position !== undefined ) {\n\n\t\t\t\t\tconst position = geometry.attributes.position;\n\t\t\t\t\tfor ( let i = 0, l = position.count; i < l; i ++ ) {\n\n\t\t\t\t\t\t_vector$a.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );\n\t\t\t\t\t\tthis.expandByPoint( _vector$a );\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\tif ( geometry.boundingBox === null ) {\n\n\t\t\t\t\t\tgeometry.computeBoundingBox();\n\n\t\t\t\t\t}\n\n\t\t\t\t\t_box$3.copy( geometry.boundingBox );\n\t\t\t\t\t_box$3.applyMatrix4( object.matrixWorld );\n\n\t\t\t\t\tthis.union( _box$3 );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst children = object.children;\n\n\t\tfor ( let i = 0, l = children.length; i < l; i ++ ) {\n\n\t\t\tthis.expandByObject( children[ i ], precise );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tcontainsPoint( point ) {\n\n\t\treturn point.x < this.min.x || point.x > this.max.x ||\n\t\t\tpoint.y < this.min.y || point.y > this.max.y ||\n\t\t\tpoint.z < this.min.z || point.z > this.max.z ? false : true;\n\n\t}\n\n\tcontainsBox( box ) {\n\n\t\treturn this.min.x <= box.min.x && box.max.x <= this.max.x &&\n\t\t\tthis.min.y <= box.min.y && box.max.y <= this.max.y &&\n\t\t\tthis.min.z <= box.min.z && box.max.z <= this.max.z;\n\n\t}\n\n\tgetParameter( point, target ) {\n\n\t\t// This can potentially have a divide by zero if the box\n\t\t// has a size dimension of 0.\n\n\t\treturn target.set(\n\t\t\t( point.x - this.min.x ) / ( this.max.x - this.min.x ),\n\t\t\t( point.y - this.min.y ) / ( this.max.y - this.min.y ),\n\t\t\t( point.z - this.min.z ) / ( this.max.z - this.min.z )\n\t\t);\n\n\t}\n\n\tintersectsBox( box ) {\n\n\t\t// using 6 splitting planes to rule out intersections.\n\t\treturn box.max.x < this.min.x || box.min.x > this.max.x ||\n\t\t\tbox.max.y < this.min.y || box.min.y > this.max.y ||\n\t\t\tbox.max.z < this.min.z || box.min.z > this.max.z ? false : true;\n\n\t}\n\n\tintersectsSphere( sphere ) {\n\n\t\t// Find the point on the AABB closest to the sphere center.\n\t\tthis.clampPoint( sphere.center, _vector$a );\n\n\t\t// If that point is inside the sphere, the AABB and sphere intersect.\n\t\treturn _vector$a.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );\n\n\t}\n\n\tintersectsPlane( plane ) {\n\n\t\t// We compute the minimum and maximum dot product values. If those values\n\t\t// are on the same side (back or front) of the plane, then there is no intersection.\n\n\t\tlet min, max;\n\n\t\tif ( plane.normal.x > 0 ) {\n\n\t\t\tmin = plane.normal.x * this.min.x;\n\t\t\tmax = plane.normal.x * this.max.x;\n\n\t\t} else {\n\n\t\t\tmin = plane.normal.x * this.max.x;\n\t\t\tmax = plane.normal.x * this.min.x;\n\n\t\t}\n\n\t\tif ( plane.normal.y > 0 ) {\n\n\t\t\tmin += plane.normal.y * this.min.y;\n\t\t\tmax += plane.normal.y * this.max.y;\n\n\t\t} else {\n\n\t\t\tmin += plane.normal.y * this.max.y;\n\t\t\tmax += plane.normal.y * this.min.y;\n\n\t\t}\n\n\t\tif ( plane.normal.z > 0 ) {\n\n\t\t\tmin += plane.normal.z * this.min.z;\n\t\t\tmax += plane.normal.z * this.max.z;\n\n\t\t} else {\n\n\t\t\tmin += plane.normal.z * this.max.z;\n\t\t\tmax += plane.normal.z * this.min.z;\n\n\t\t}\n\n\t\treturn ( min <= - plane.constant && max >= - plane.constant );\n\n\t}\n\n\tintersectsTriangle( triangle ) {\n\n\t\tif ( this.isEmpty() ) {\n\n\t\t\treturn false;\n\n\t\t}\n\n\t\t// compute box center and extents\n\t\tthis.getCenter( _center );\n\t\t_extents.subVectors( this.max, _center );\n\n\t\t// translate triangle to aabb origin\n\t\t_v0$2.subVectors( triangle.a, _center );\n\t\t_v1$7.subVectors( triangle.b, _center );\n\t\t_v2$4.subVectors( triangle.c, _center );\n\n\t\t// compute edge vectors for triangle\n\t\t_f0.subVectors( _v1$7, _v0$2 );\n\t\t_f1.subVectors( _v2$4, _v1$7 );\n\t\t_f2.subVectors( _v0$2, _v2$4 );\n\n\t\t// test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb\n\t\t// make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation\n\t\t// axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)\n\t\tlet axes = [\n\t\t\t0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,\n\t\t\t_f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,\n\t\t\t- _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0\n\t\t];\n\t\tif ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {\n\n\t\t\treturn false;\n\n\t\t}\n\n\t\t// test 3 face normals from the aabb\n\t\taxes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];\n\t\tif ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {\n\n\t\t\treturn false;\n\n\t\t}\n\n\t\t// finally testing the face normal of the triangle\n\t\t// use already existing triangle edge vectors here\n\t\t_triangleNormal.crossVectors( _f0, _f1 );\n\t\taxes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];\n\n\t\treturn satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );\n\n\t}\n\n\tclampPoint( point, target ) {\n\n\t\treturn target.copy( point ).clamp( this.min, this.max );\n\n\t}\n\n\tdistanceToPoint( point ) {\n\n\t\treturn this.clampPoint( point, _vector$a ).distanceTo( point );\n\n\t}\n\n\tgetBoundingSphere( target ) {\n\n\t\tif ( this.isEmpty() ) {\n\n\t\t\ttarget.makeEmpty();\n\n\t\t} else {\n\n\t\t\tthis.getCenter( target.center );\n\n\t\t\ttarget.radius = this.getSize( _vector$a ).length() * 0.5;\n\n\t\t}\n\n\t\treturn target;\n\n\t}\n\n\tintersect( box ) {\n\n\t\tthis.min.max( box.min );\n\t\tthis.max.min( box.max );\n\n\t\t// ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.\n\t\tif ( this.isEmpty() ) this.makeEmpty();\n\n\t\treturn this;\n\n\t}\n\n\tunion( box ) {\n\n\t\tthis.min.min( box.min );\n\t\tthis.max.max( box.max );\n\n\t\treturn this;\n\n\t}\n\n\tapplyMatrix4( matrix ) {\n\n\t\t// transform of empty box is an empty box.\n\t\tif ( this.isEmpty() ) return this;\n\n\t\t// NOTE: I am using a binary pattern to specify all 2^3 combinations below\n\t\t_points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000\n\t\t_points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001\n\t\t_points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010\n\t\t_points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011\n\t\t_points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100\n\t\t_points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101\n\t\t_points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110\n\t\t_points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111\n\n\t\tthis.setFromPoints( _points );\n\n\t\treturn this;\n\n\t}\n\n\ttranslate( offset ) {\n\n\t\tthis.min.add( offset );\n\t\tthis.max.add( offset );\n\n\t\treturn this;\n\n\t}\n\n\tequals( box ) {\n\n\t\treturn box.min.equals( this.min ) && box.max.equals( this.max );\n\n\t}\n\n}\n\nconst _points = [\n\t/*@__PURE__*/ new Vector3(),\n\t/*@__PURE__*/ new Vector3(),\n\t/*@__PURE__*/ new Vector3(),\n\t/*@__PURE__*/ new Vector3(),\n\t/*@__PURE__*/ new Vector3(),\n\t/*@__PURE__*/ new Vector3(),\n\t/*@__PURE__*/ new Vector3(),\n\t/*@__PURE__*/ new Vector3()\n];\n\nconst _vector$a = /*@__PURE__*/ new Vector3();\n\nconst _box$3 = /*@__PURE__*/ new Box3();\n\n// triangle centered vertices\n\nconst _v0$2 = /*@__PURE__*/ new Vector3();\nconst _v1$7 = /*@__PURE__*/ new Vector3();\nconst _v2$4 = /*@__PURE__*/ new Vector3();\n\n// triangle edge vectors\n\nconst _f0 = /*@__PURE__*/ new Vector3();\nconst _f1 = /*@__PURE__*/ new Vector3();\nconst _f2 = /*@__PURE__*/ new Vector3();\n\nconst _center = /*@__PURE__*/ new Vector3();\nconst _extents = /*@__PURE__*/ new Vector3();\nconst _triangleNormal = /*@__PURE__*/ new Vector3();\nconst _testAxis = /*@__PURE__*/ new Vector3();\n\nfunction satForAxes( axes, v0, v1, v2, extents ) {\n\n\tfor ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {\n\n\t\t_testAxis.fromArray( axes, i );\n\t\t// project the aabb onto the separating axis\n\t\tconst r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );\n\t\t// project all 3 vertices of the triangle onto the separating axis\n\t\tconst p0 = v0.dot( _testAxis );\n\t\tconst p1 = v1.dot( _testAxis );\n\t\tconst p2 = v2.dot( _testAxis );\n\t\t// actual test, basically see if either of the most extreme of the triangle points intersects r\n\t\tif ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {\n\n\t\t\t// points of the projected triangle are outside the projected half-length of the aabb\n\t\t\t// the axis is separating and we can exit\n\t\t\treturn false;\n\n\t\t}\n\n\t}\n\n\treturn true;\n\n}\n\nconst _box$2 = /*@__PURE__*/ new Box3();\nconst _v1$6 = /*@__PURE__*/ new Vector3();\nconst _v2$3 = /*@__PURE__*/ new Vector3();\n\nclass Sphere {\n\n\tconstructor( center = new Vector3(), radius = - 1 ) {\n\n\t\tthis.center = center;\n\t\tthis.radius = radius;\n\n\t}\n\n\tset( center, radius ) {\n\n\t\tthis.center.copy( center );\n\t\tthis.radius = radius;\n\n\t\treturn this;\n\n\t}\n\n\tsetFromPoints( points, optionalCenter ) {\n\n\t\tconst center = this.center;\n\n\t\tif ( optionalCenter !== undefined ) {\n\n\t\t\tcenter.copy( optionalCenter );\n\n\t\t} else {\n\n\t\t\t_box$2.setFromPoints( points ).getCenter( center );\n\n\t\t}\n\n\t\tlet maxRadiusSq = 0;\n\n\t\tfor ( let i = 0, il = points.length; i < il; i ++ ) {\n\n\t\t\tmaxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );\n\n\t\t}\n\n\t\tthis.radius = Math.sqrt( maxRadiusSq );\n\n\t\treturn this;\n\n\t}\n\n\tcopy( sphere ) {\n\n\t\tthis.center.copy( sphere.center );\n\t\tthis.radius = sphere.radius;\n\n\t\treturn this;\n\n\t}\n\n\tisEmpty() {\n\n\t\treturn ( this.radius < 0 );\n\n\t}\n\n\tmakeEmpty() {\n\n\t\tthis.center.set( 0, 0, 0 );\n\t\tthis.radius = - 1;\n\n\t\treturn this;\n\n\t}\n\n\tcontainsPoint( point ) {\n\n\t\treturn ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );\n\n\t}\n\n\tdistanceToPoint( point ) {\n\n\t\treturn ( point.distanceTo( this.center ) - this.radius );\n\n\t}\n\n\tintersectsSphere( sphere ) {\n\n\t\tconst radiusSum = this.radius + sphere.radius;\n\n\t\treturn sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );\n\n\t}\n\n\tintersectsBox( box ) {\n\n\t\treturn box.intersectsSphere( this );\n\n\t}\n\n\tintersectsPlane( plane ) {\n\n\t\treturn Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;\n\n\t}\n\n\tclampPoint( point, target ) {\n\n\t\tconst deltaLengthSq = this.center.distanceToSquared( point );\n\n\t\ttarget.copy( point );\n\n\t\tif ( deltaLengthSq > ( this.radius * this.radius ) ) {\n\n\t\t\ttarget.sub( this.center ).normalize();\n\t\t\ttarget.multiplyScalar( this.radius ).add( this.center );\n\n\t\t}\n\n\t\treturn target;\n\n\t}\n\n\tgetBoundingBox( target ) {\n\n\t\tif ( this.isEmpty() ) {\n\n\t\t\t// Empty sphere produces empty bounding box\n\t\t\ttarget.makeEmpty();\n\t\t\treturn target;\n\n\t\t}\n\n\t\ttarget.set( this.center, this.center );\n\t\ttarget.expandByScalar( this.radius );\n\n\t\treturn target;\n\n\t}\n\n\tapplyMatrix4( matrix ) {\n\n\t\tthis.center.applyMatrix4( matrix );\n\t\tthis.radius = this.radius * matrix.getMaxScaleOnAxis();\n\n\t\treturn this;\n\n\t}\n\n\ttranslate( offset ) {\n\n\t\tthis.center.add( offset );\n\n\t\treturn this;\n\n\t}\n\n\texpandByPoint( point ) {\n\n\t\tif ( this.isEmpty() ) {\n\n\t\t\tthis.center.copy( point );\n\n\t\t\tthis.radius = 0;\n\n\t\t\treturn this;\n\n\t\t}\n\n\t\t_v1$6.subVectors( point, this.center );\n\n\t\tconst lengthSq = _v1$6.lengthSq();\n\n\t\tif ( lengthSq > ( this.radius * this.radius ) ) {\n\n\t\t\t// calculate the minimal sphere\n\n\t\t\tconst length = Math.sqrt( lengthSq );\n\n\t\t\tconst delta = ( length - this.radius ) * 0.5;\n\n\t\t\tthis.center.addScaledVector( _v1$6, delta / length );\n\n\t\t\tthis.radius += delta;\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tunion( sphere ) {\n\n\t\tif ( sphere.isEmpty() ) {\n\n\t\t\treturn this;\n\n\t\t}\n\n\t\tif ( this.isEmpty() ) {\n\n\t\t\tthis.copy( sphere );\n\n\t\t\treturn this;\n\n\t\t}\n\n\t\tif ( this.center.equals( sphere.center ) === true ) {\n\n\t\t\t this.radius = Math.max( this.radius, sphere.radius );\n\n\t\t} else {\n\n\t\t\t_v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );\n\n\t\t\tthis.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );\n\n\t\t\tthis.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tequals( sphere ) {\n\n\t\treturn sphere.center.equals( this.center ) && ( sphere.radius === this.radius );\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n}\n\nconst _vector$9 = /*@__PURE__*/ new Vector3();\nconst _segCenter = /*@__PURE__*/ new Vector3();\nconst _segDir = /*@__PURE__*/ new Vector3();\nconst _diff = /*@__PURE__*/ new Vector3();\n\nconst _edge1 = /*@__PURE__*/ new Vector3();\nconst _edge2 = /*@__PURE__*/ new Vector3();\nconst _normal$1 = /*@__PURE__*/ new Vector3();\n\nclass Ray {\n\n\tconstructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {\n\n\t\tthis.origin = origin;\n\t\tthis.direction = direction;\n\n\t}\n\n\tset( origin, direction ) {\n\n\t\tthis.origin.copy( origin );\n\t\tthis.direction.copy( direction );\n\n\t\treturn this;\n\n\t}\n\n\tcopy( ray ) {\n\n\t\tthis.origin.copy( ray.origin );\n\t\tthis.direction.copy( ray.direction );\n\n\t\treturn this;\n\n\t}\n\n\tat( t, target ) {\n\n\t\treturn target.copy( this.origin ).addScaledVector( this.direction, t );\n\n\t}\n\n\tlookAt( v ) {\n\n\t\tthis.direction.copy( v ).sub( this.origin ).normalize();\n\n\t\treturn this;\n\n\t}\n\n\trecast( t ) {\n\n\t\tthis.origin.copy( this.at( t, _vector$9 ) );\n\n\t\treturn this;\n\n\t}\n\n\tclosestPointToPoint( point, target ) {\n\n\t\ttarget.subVectors( point, this.origin );\n\n\t\tconst directionDistance = target.dot( this.direction );\n\n\t\tif ( directionDistance < 0 ) {\n\n\t\t\treturn target.copy( this.origin );\n\n\t\t}\n\n\t\treturn target.copy( this.origin ).addScaledVector( this.direction, directionDistance );\n\n\t}\n\n\tdistanceToPoint( point ) {\n\n\t\treturn Math.sqrt( this.distanceSqToPoint( point ) );\n\n\t}\n\n\tdistanceSqToPoint( point ) {\n\n\t\tconst directionDistance = _vector$9.subVectors( point, this.origin ).dot( this.direction );\n\n\t\t// point behind the ray\n\n\t\tif ( directionDistance < 0 ) {\n\n\t\t\treturn this.origin.distanceToSquared( point );\n\n\t\t}\n\n\t\t_vector$9.copy( this.origin ).addScaledVector( this.direction, directionDistance );\n\n\t\treturn _vector$9.distanceToSquared( point );\n\n\t}\n\n\tdistanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {\n\n\t\t// from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h\n\t\t// It returns the min distance between the ray and the segment\n\t\t// defined by v0 and v1\n\t\t// It can also set two optional targets :\n\t\t// - The closest point on the ray\n\t\t// - The closest point on the segment\n\n\t\t_segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );\n\t\t_segDir.copy( v1 ).sub( v0 ).normalize();\n\t\t_diff.copy( this.origin ).sub( _segCenter );\n\n\t\tconst segExtent = v0.distanceTo( v1 ) * 0.5;\n\t\tconst a01 = - this.direction.dot( _segDir );\n\t\tconst b0 = _diff.dot( this.direction );\n\t\tconst b1 = - _diff.dot( _segDir );\n\t\tconst c = _diff.lengthSq();\n\t\tconst det = Math.abs( 1 - a01 * a01 );\n\t\tlet s0, s1, sqrDist, extDet;\n\n\t\tif ( det > 0 ) {\n\n\t\t\t// The ray and segment are not parallel.\n\n\t\t\ts0 = a01 * b1 - b0;\n\t\t\ts1 = a01 * b0 - b1;\n\t\t\textDet = segExtent * det;\n\n\t\t\tif ( s0 >= 0 ) {\n\n\t\t\t\tif ( s1 >= - extDet ) {\n\n\t\t\t\t\tif ( s1 <= extDet ) {\n\n\t\t\t\t\t\t// region 0\n\t\t\t\t\t\t// Minimum at interior points of ray and segment.\n\n\t\t\t\t\t\tconst invDet = 1 / det;\n\t\t\t\t\t\ts0 *= invDet;\n\t\t\t\t\t\ts1 *= invDet;\n\t\t\t\t\t\tsqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t// region 1\n\n\t\t\t\t\t\ts1 = segExtent;\n\t\t\t\t\t\ts0 = Math.max( 0, - ( a01 * s1 + b0 ) );\n\t\t\t\t\t\tsqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// region 5\n\n\t\t\t\t\ts1 = - segExtent;\n\t\t\t\t\ts0 = Math.max( 0, - ( a01 * s1 + b0 ) );\n\t\t\t\t\tsqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tif ( s1 <= - extDet ) {\n\n\t\t\t\t\t// region 4\n\n\t\t\t\t\ts0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );\n\t\t\t\t\ts1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );\n\t\t\t\t\tsqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;\n\n\t\t\t\t} else if ( s1 <= extDet ) {\n\n\t\t\t\t\t// region 3\n\n\t\t\t\t\ts0 = 0;\n\t\t\t\t\ts1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );\n\t\t\t\t\tsqrDist = s1 * ( s1 + 2 * b1 ) + c;\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// region 2\n\n\t\t\t\t\ts0 = Math.max( 0, - ( a01 * segExtent + b0 ) );\n\t\t\t\t\ts1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );\n\t\t\t\t\tsqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\t// Ray and segment are parallel.\n\n\t\t\ts1 = ( a01 > 0 ) ? - segExtent : segExtent;\n\t\t\ts0 = Math.max( 0, - ( a01 * s1 + b0 ) );\n\t\t\tsqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;\n\n\t\t}\n\n\t\tif ( optionalPointOnRay ) {\n\n\t\t\toptionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );\n\n\t\t}\n\n\t\tif ( optionalPointOnSegment ) {\n\n\t\t\toptionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );\n\n\t\t}\n\n\t\treturn sqrDist;\n\n\t}\n\n\tintersectSphere( sphere, target ) {\n\n\t\t_vector$9.subVectors( sphere.center, this.origin );\n\t\tconst tca = _vector$9.dot( this.direction );\n\t\tconst d2 = _vector$9.dot( _vector$9 ) - tca * tca;\n\t\tconst radius2 = sphere.radius * sphere.radius;\n\n\t\tif ( d2 > radius2 ) return null;\n\n\t\tconst thc = Math.sqrt( radius2 - d2 );\n\n\t\t// t0 = first intersect point - entrance on front of sphere\n\t\tconst t0 = tca - thc;\n\n\t\t// t1 = second intersect point - exit point on back of sphere\n\t\tconst t1 = tca + thc;\n\n\t\t// test to see if t1 is behind the ray - if so, return null\n\t\tif ( t1 < 0 ) return null;\n\n\t\t// test to see if t0 is behind the ray:\n\t\t// if it is, the ray is inside the sphere, so return the second exit point scaled by t1,\n\t\t// in order to always return an intersect point that is in front of the ray.\n\t\tif ( t0 < 0 ) return this.at( t1, target );\n\n\t\t// else t0 is in front of the ray, so return the first collision point scaled by t0\n\t\treturn this.at( t0, target );\n\n\t}\n\n\tintersectsSphere( sphere ) {\n\n\t\treturn this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );\n\n\t}\n\n\tdistanceToPlane( plane ) {\n\n\t\tconst denominator = plane.normal.dot( this.direction );\n\n\t\tif ( denominator === 0 ) {\n\n\t\t\t// line is coplanar, return origin\n\t\t\tif ( plane.distanceToPoint( this.origin ) === 0 ) {\n\n\t\t\t\treturn 0;\n\n\t\t\t}\n\n\t\t\t// Null is preferable to undefined since undefined means.... it is undefined\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\tconst t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;\n\n\t\t// Return if the ray never intersects the plane\n\n\t\treturn t >= 0 ? t : null;\n\n\t}\n\n\tintersectPlane( plane, target ) {\n\n\t\tconst t = this.distanceToPlane( plane );\n\n\t\tif ( t === null ) {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\treturn this.at( t, target );\n\n\t}\n\n\tintersectsPlane( plane ) {\n\n\t\t// check if the ray lies on the plane first\n\n\t\tconst distToPoint = plane.distanceToPoint( this.origin );\n\n\t\tif ( distToPoint === 0 ) {\n\n\t\t\treturn true;\n\n\t\t}\n\n\t\tconst denominator = plane.normal.dot( this.direction );\n\n\t\tif ( denominator * distToPoint < 0 ) {\n\n\t\t\treturn true;\n\n\t\t}\n\n\t\t// ray origin is behind the plane (and is pointing behind it)\n\n\t\treturn false;\n\n\t}\n\n\tintersectBox( box, target ) {\n\n\t\tlet tmin, tmax, tymin, tymax, tzmin, tzmax;\n\n\t\tconst invdirx = 1 / this.direction.x,\n\t\t\tinvdiry = 1 / this.direction.y,\n\t\t\tinvdirz = 1 / this.direction.z;\n\n\t\tconst origin = this.origin;\n\n\t\tif ( invdirx >= 0 ) {\n\n\t\t\ttmin = ( box.min.x - origin.x ) * invdirx;\n\t\t\ttmax = ( box.max.x - origin.x ) * invdirx;\n\n\t\t} else {\n\n\t\t\ttmin = ( box.max.x - origin.x ) * invdirx;\n\t\t\ttmax = ( box.min.x - origin.x ) * invdirx;\n\n\t\t}\n\n\t\tif ( invdiry >= 0 ) {\n\n\t\t\ttymin = ( box.min.y - origin.y ) * invdiry;\n\t\t\ttymax = ( box.max.y - origin.y ) * invdiry;\n\n\t\t} else {\n\n\t\t\ttymin = ( box.max.y - origin.y ) * invdiry;\n\t\t\ttymax = ( box.min.y - origin.y ) * invdiry;\n\n\t\t}\n\n\t\tif ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;\n\n\t\tif ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;\n\n\t\tif ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;\n\n\t\tif ( invdirz >= 0 ) {\n\n\t\t\ttzmin = ( box.min.z - origin.z ) * invdirz;\n\t\t\ttzmax = ( box.max.z - origin.z ) * invdirz;\n\n\t\t} else {\n\n\t\t\ttzmin = ( box.max.z - origin.z ) * invdirz;\n\t\t\ttzmax = ( box.min.z - origin.z ) * invdirz;\n\n\t\t}\n\n\t\tif ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;\n\n\t\tif ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;\n\n\t\tif ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;\n\n\t\t//return point closest to the ray (positive side)\n\n\t\tif ( tmax < 0 ) return null;\n\n\t\treturn this.at( tmin >= 0 ? tmin : tmax, target );\n\n\t}\n\n\tintersectsBox( box ) {\n\n\t\treturn this.intersectBox( box, _vector$9 ) !== null;\n\n\t}\n\n\tintersectTriangle( a, b, c, backfaceCulling, target ) {\n\n\t\t// Compute the offset origin, edges, and normal.\n\n\t\t// from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h\n\n\t\t_edge1.subVectors( b, a );\n\t\t_edge2.subVectors( c, a );\n\t\t_normal$1.crossVectors( _edge1, _edge2 );\n\n\t\t// Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,\n\t\t// E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by\n\t\t// |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))\n\t\t// |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))\n\t\t// |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)\n\t\tlet DdN = this.direction.dot( _normal$1 );\n\t\tlet sign;\n\n\t\tif ( DdN > 0 ) {\n\n\t\t\tif ( backfaceCulling ) return null;\n\t\t\tsign = 1;\n\n\t\t} else if ( DdN < 0 ) {\n\n\t\t\tsign = - 1;\n\t\t\tDdN = - DdN;\n\n\t\t} else {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\t_diff.subVectors( this.origin, a );\n\t\tconst DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );\n\n\t\t// b1 < 0, no intersection\n\t\tif ( DdQxE2 < 0 ) {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\tconst DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );\n\n\t\t// b2 < 0, no intersection\n\t\tif ( DdE1xQ < 0 ) {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\t// b1+b2 > 1, no intersection\n\t\tif ( DdQxE2 + DdE1xQ > DdN ) {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\t// Line intersects triangle, check if ray does.\n\t\tconst QdN = - sign * _diff.dot( _normal$1 );\n\n\t\t// t < 0, no intersection\n\t\tif ( QdN < 0 ) {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\t// Ray intersects triangle.\n\t\treturn this.at( QdN / DdN, target );\n\n\t}\n\n\tapplyMatrix4( matrix4 ) {\n\n\t\tthis.origin.applyMatrix4( matrix4 );\n\t\tthis.direction.transformDirection( matrix4 );\n\n\t\treturn this;\n\n\t}\n\n\tequals( ray ) {\n\n\t\treturn ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n}\n\nclass Matrix4 {\n\n\tconstructor() {\n\n\t\tMatrix4.prototype.isMatrix4 = true;\n\n\t\tthis.elements = [\n\n\t\t\t1, 0, 0, 0,\n\t\t\t0, 1, 0, 0,\n\t\t\t0, 0, 1, 0,\n\t\t\t0, 0, 0, 1\n\n\t\t];\n\n\t}\n\n\tset( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {\n\n\t\tconst te = this.elements;\n\n\t\tte[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;\n\t\tte[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;\n\t\tte[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;\n\t\tte[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;\n\n\t\treturn this;\n\n\t}\n\n\tidentity() {\n\n\t\tthis.set(\n\n\t\t\t1, 0, 0, 0,\n\t\t\t0, 1, 0, 0,\n\t\t\t0, 0, 1, 0,\n\t\t\t0, 0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\treturn new Matrix4().fromArray( this.elements );\n\n\t}\n\n\tcopy( m ) {\n\n\t\tconst te = this.elements;\n\t\tconst me = m.elements;\n\n\t\tte[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];\n\t\tte[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];\n\t\tte[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];\n\t\tte[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];\n\n\t\treturn this;\n\n\t}\n\n\tcopyPosition( m ) {\n\n\t\tconst te = this.elements, me = m.elements;\n\n\t\tte[ 12 ] = me[ 12 ];\n\t\tte[ 13 ] = me[ 13 ];\n\t\tte[ 14 ] = me[ 14 ];\n\n\t\treturn this;\n\n\t}\n\n\tsetFromMatrix3( m ) {\n\n\t\tconst me = m.elements;\n\n\t\tthis.set(\n\n\t\t\tme[ 0 ], me[ 3 ], me[ 6 ], 0,\n\t\t\tme[ 1 ], me[ 4 ], me[ 7 ], 0,\n\t\t\tme[ 2 ], me[ 5 ], me[ 8 ], 0,\n\t\t\t0, 0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\textractBasis( xAxis, yAxis, zAxis ) {\n\n\t\txAxis.setFromMatrixColumn( this, 0 );\n\t\tyAxis.setFromMatrixColumn( this, 1 );\n\t\tzAxis.setFromMatrixColumn( this, 2 );\n\n\t\treturn this;\n\n\t}\n\n\tmakeBasis( xAxis, yAxis, zAxis ) {\n\n\t\tthis.set(\n\t\t\txAxis.x, yAxis.x, zAxis.x, 0,\n\t\t\txAxis.y, yAxis.y, zAxis.y, 0,\n\t\t\txAxis.z, yAxis.z, zAxis.z, 0,\n\t\t\t0, 0, 0, 1\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\textractRotation( m ) {\n\n\t\t// this method does not support reflection matrices\n\n\t\tconst te = this.elements;\n\t\tconst me = m.elements;\n\n\t\tconst scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();\n\t\tconst scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();\n\t\tconst scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();\n\n\t\tte[ 0 ] = me[ 0 ] * scaleX;\n\t\tte[ 1 ] = me[ 1 ] * scaleX;\n\t\tte[ 2 ] = me[ 2 ] * scaleX;\n\t\tte[ 3 ] = 0;\n\n\t\tte[ 4 ] = me[ 4 ] * scaleY;\n\t\tte[ 5 ] = me[ 5 ] * scaleY;\n\t\tte[ 6 ] = me[ 6 ] * scaleY;\n\t\tte[ 7 ] = 0;\n\n\t\tte[ 8 ] = me[ 8 ] * scaleZ;\n\t\tte[ 9 ] = me[ 9 ] * scaleZ;\n\t\tte[ 10 ] = me[ 10 ] * scaleZ;\n\t\tte[ 11 ] = 0;\n\n\t\tte[ 12 ] = 0;\n\t\tte[ 13 ] = 0;\n\t\tte[ 14 ] = 0;\n\t\tte[ 15 ] = 1;\n\n\t\treturn this;\n\n\t}\n\n\tmakeRotationFromEuler( euler ) {\n\n\t\tconst te = this.elements;\n\n\t\tconst x = euler.x, y = euler.y, z = euler.z;\n\t\tconst a = Math.cos( x ), b = Math.sin( x );\n\t\tconst c = Math.cos( y ), d = Math.sin( y );\n\t\tconst e = Math.cos( z ), f = Math.sin( z );\n\n\t\tif ( euler.order === 'XYZ' ) {\n\n\t\t\tconst ae = a * e, af = a * f, be = b * e, bf = b * f;\n\n\t\t\tte[ 0 ] = c * e;\n\t\t\tte[ 4 ] = - c * f;\n\t\t\tte[ 8 ] = d;\n\n\t\t\tte[ 1 ] = af + be * d;\n\t\t\tte[ 5 ] = ae - bf * d;\n\t\t\tte[ 9 ] = - b * c;\n\n\t\t\tte[ 2 ] = bf - ae * d;\n\t\t\tte[ 6 ] = be + af * d;\n\t\t\tte[ 10 ] = a * c;\n\n\t\t} else if ( euler.order === 'YXZ' ) {\n\n\t\t\tconst ce = c * e, cf = c * f, de = d * e, df = d * f;\n\n\t\t\tte[ 0 ] = ce + df * b;\n\t\t\tte[ 4 ] = de * b - cf;\n\t\t\tte[ 8 ] = a * d;\n\n\t\t\tte[ 1 ] = a * f;\n\t\t\tte[ 5 ] = a * e;\n\t\t\tte[ 9 ] = - b;\n\n\t\t\tte[ 2 ] = cf * b - de;\n\t\t\tte[ 6 ] = df + ce * b;\n\t\t\tte[ 10 ] = a * c;\n\n\t\t} else if ( euler.order === 'ZXY' ) {\n\n\t\t\tconst ce = c * e, cf = c * f, de = d * e, df = d * f;\n\n\t\t\tte[ 0 ] = ce - df * b;\n\t\t\tte[ 4 ] = - a * f;\n\t\t\tte[ 8 ] = de + cf * b;\n\n\t\t\tte[ 1 ] = cf + de * b;\n\t\t\tte[ 5 ] = a * e;\n\t\t\tte[ 9 ] = df - ce * b;\n\n\t\t\tte[ 2 ] = - a * d;\n\t\t\tte[ 6 ] = b;\n\t\t\tte[ 10 ] = a * c;\n\n\t\t} else if ( euler.order === 'ZYX' ) {\n\n\t\t\tconst ae = a * e, af = a * f, be = b * e, bf = b * f;\n\n\t\t\tte[ 0 ] = c * e;\n\t\t\tte[ 4 ] = be * d - af;\n\t\t\tte[ 8 ] = ae * d + bf;\n\n\t\t\tte[ 1 ] = c * f;\n\t\t\tte[ 5 ] = bf * d + ae;\n\t\t\tte[ 9 ] = af * d - be;\n\n\t\t\tte[ 2 ] = - d;\n\t\t\tte[ 6 ] = b * c;\n\t\t\tte[ 10 ] = a * c;\n\n\t\t} else if ( euler.order === 'YZX' ) {\n\n\t\t\tconst ac = a * c, ad = a * d, bc = b * c, bd = b * d;\n\n\t\t\tte[ 0 ] = c * e;\n\t\t\tte[ 4 ] = bd - ac * f;\n\t\t\tte[ 8 ] = bc * f + ad;\n\n\t\t\tte[ 1 ] = f;\n\t\t\tte[ 5 ] = a * e;\n\t\t\tte[ 9 ] = - b * e;\n\n\t\t\tte[ 2 ] = - d * e;\n\t\t\tte[ 6 ] = ad * f + bc;\n\t\t\tte[ 10 ] = ac - bd * f;\n\n\t\t} else if ( euler.order === 'XZY' ) {\n\n\t\t\tconst ac = a * c, ad = a * d, bc = b * c, bd = b * d;\n\n\t\t\tte[ 0 ] = c * e;\n\t\t\tte[ 4 ] = - f;\n\t\t\tte[ 8 ] = d * e;\n\n\t\t\tte[ 1 ] = ac * f + bd;\n\t\t\tte[ 5 ] = a * e;\n\t\t\tte[ 9 ] = ad * f - bc;\n\n\t\t\tte[ 2 ] = bc * f - ad;\n\t\t\tte[ 6 ] = b * e;\n\t\t\tte[ 10 ] = bd * f + ac;\n\n\t\t}\n\n\t\t// bottom row\n\t\tte[ 3 ] = 0;\n\t\tte[ 7 ] = 0;\n\t\tte[ 11 ] = 0;\n\n\t\t// last column\n\t\tte[ 12 ] = 0;\n\t\tte[ 13 ] = 0;\n\t\tte[ 14 ] = 0;\n\t\tte[ 15 ] = 1;\n\n\t\treturn this;\n\n\t}\n\n\tmakeRotationFromQuaternion( q ) {\n\n\t\treturn this.compose( _zero, q, _one );\n\n\t}\n\n\tlookAt( eye, target, up ) {\n\n\t\tconst te = this.elements;\n\n\t\t_z.subVectors( eye, target );\n\n\t\tif ( _z.lengthSq() === 0 ) {\n\n\t\t\t// eye and target are in the same position\n\n\t\t\t_z.z = 1;\n\n\t\t}\n\n\t\t_z.normalize();\n\t\t_x.crossVectors( up, _z );\n\n\t\tif ( _x.lengthSq() === 0 ) {\n\n\t\t\t// up and z are parallel\n\n\t\t\tif ( Math.abs( up.z ) === 1 ) {\n\n\t\t\t\t_z.x += 0.0001;\n\n\t\t\t} else {\n\n\t\t\t\t_z.z += 0.0001;\n\n\t\t\t}\n\n\t\t\t_z.normalize();\n\t\t\t_x.crossVectors( up, _z );\n\n\t\t}\n\n\t\t_x.normalize();\n\t\t_y.crossVectors( _z, _x );\n\n\t\tte[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;\n\t\tte[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;\n\t\tte[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;\n\n\t\treturn this;\n\n\t}\n\n\tmultiply( m ) {\n\n\t\treturn this.multiplyMatrices( this, m );\n\n\t}\n\n\tpremultiply( m ) {\n\n\t\treturn this.multiplyMatrices( m, this );\n\n\t}\n\n\tmultiplyMatrices( a, b ) {\n\n\t\tconst ae = a.elements;\n\t\tconst be = b.elements;\n\t\tconst te = this.elements;\n\n\t\tconst a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];\n\t\tconst a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];\n\t\tconst a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];\n\t\tconst a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];\n\n\t\tconst b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];\n\t\tconst b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];\n\t\tconst b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];\n\t\tconst b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];\n\n\t\tte[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;\n\t\tte[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;\n\t\tte[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;\n\t\tte[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;\n\n\t\tte[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;\n\t\tte[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;\n\t\tte[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;\n\t\tte[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;\n\n\t\tte[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;\n\t\tte[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;\n\t\tte[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;\n\t\tte[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;\n\n\t\tte[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;\n\t\tte[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;\n\t\tte[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;\n\t\tte[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;\n\n\t\treturn this;\n\n\t}\n\n\tmultiplyScalar( s ) {\n\n\t\tconst te = this.elements;\n\n\t\tte[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;\n\t\tte[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;\n\t\tte[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;\n\t\tte[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;\n\n\t\treturn this;\n\n\t}\n\n\tdeterminant() {\n\n\t\tconst te = this.elements;\n\n\t\tconst n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];\n\t\tconst n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];\n\t\tconst n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];\n\t\tconst n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];\n\n\t\t//TODO: make this more efficient\n\t\t//( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )\n\n\t\treturn (\n\t\t\tn41 * (\n\t\t\t\t+ n14 * n23 * n32\n\t\t\t\t - n13 * n24 * n32\n\t\t\t\t - n14 * n22 * n33\n\t\t\t\t + n12 * n24 * n33\n\t\t\t\t + n13 * n22 * n34\n\t\t\t\t - n12 * n23 * n34\n\t\t\t) +\n\t\t\tn42 * (\n\t\t\t\t+ n11 * n23 * n34\n\t\t\t\t - n11 * n24 * n33\n\t\t\t\t + n14 * n21 * n33\n\t\t\t\t - n13 * n21 * n34\n\t\t\t\t + n13 * n24 * n31\n\t\t\t\t - n14 * n23 * n31\n\t\t\t) +\n\t\t\tn43 * (\n\t\t\t\t+ n11 * n24 * n32\n\t\t\t\t - n11 * n22 * n34\n\t\t\t\t - n14 * n21 * n32\n\t\t\t\t + n12 * n21 * n34\n\t\t\t\t + n14 * n22 * n31\n\t\t\t\t - n12 * n24 * n31\n\t\t\t) +\n\t\t\tn44 * (\n\t\t\t\t- n13 * n22 * n31\n\t\t\t\t - n11 * n23 * n32\n\t\t\t\t + n11 * n22 * n33\n\t\t\t\t + n13 * n21 * n32\n\t\t\t\t - n12 * n21 * n33\n\t\t\t\t + n12 * n23 * n31\n\t\t\t)\n\n\t\t);\n\n\t}\n\n\ttranspose() {\n\n\t\tconst te = this.elements;\n\t\tlet tmp;\n\n\t\ttmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;\n\t\ttmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;\n\t\ttmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;\n\n\t\ttmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;\n\t\ttmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;\n\t\ttmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;\n\n\t\treturn this;\n\n\t}\n\n\tsetPosition( x, y, z ) {\n\n\t\tconst te = this.elements;\n\n\t\tif ( x.isVector3 ) {\n\n\t\t\tte[ 12 ] = x.x;\n\t\t\tte[ 13 ] = x.y;\n\t\t\tte[ 14 ] = x.z;\n\n\t\t} else {\n\n\t\t\tte[ 12 ] = x;\n\t\t\tte[ 13 ] = y;\n\t\t\tte[ 14 ] = z;\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tinvert() {\n\n\t\t// based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm\n\t\tconst te = this.elements,\n\n\t\t\tn11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],\n\t\t\tn12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],\n\t\t\tn13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],\n\t\t\tn14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],\n\n\t\t\tt11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,\n\t\t\tt12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,\n\t\t\tt13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,\n\t\t\tt14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;\n\n\t\tconst det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;\n\n\t\tif ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );\n\n\t\tconst detInv = 1 / det;\n\n\t\tte[ 0 ] = t11 * detInv;\n\t\tte[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;\n\t\tte[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;\n\t\tte[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;\n\n\t\tte[ 4 ] = t12 * detInv;\n\t\tte[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;\n\t\tte[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;\n\t\tte[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;\n\n\t\tte[ 8 ] = t13 * detInv;\n\t\tte[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;\n\t\tte[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;\n\t\tte[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;\n\n\t\tte[ 12 ] = t14 * detInv;\n\t\tte[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;\n\t\tte[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;\n\t\tte[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;\n\n\t\treturn this;\n\n\t}\n\n\tscale( v ) {\n\n\t\tconst te = this.elements;\n\t\tconst x = v.x, y = v.y, z = v.z;\n\n\t\tte[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;\n\t\tte[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;\n\t\tte[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;\n\t\tte[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;\n\n\t\treturn this;\n\n\t}\n\n\tgetMaxScaleOnAxis() {\n\n\t\tconst te = this.elements;\n\n\t\tconst scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];\n\t\tconst scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];\n\t\tconst scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];\n\n\t\treturn Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );\n\n\t}\n\n\tmakeTranslation( x, y, z ) {\n\n\t\tthis.set(\n\n\t\t\t1, 0, 0, x,\n\t\t\t0, 1, 0, y,\n\t\t\t0, 0, 1, z,\n\t\t\t0, 0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\tmakeRotationX( theta ) {\n\n\t\tconst c = Math.cos( theta ), s = Math.sin( theta );\n\n\t\tthis.set(\n\n\t\t\t1, 0, 0, 0,\n\t\t\t0, c, - s, 0,\n\t\t\t0, s, c, 0,\n\t\t\t0, 0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\tmakeRotationY( theta ) {\n\n\t\tconst c = Math.cos( theta ), s = Math.sin( theta );\n\n\t\tthis.set(\n\n\t\t\t c, 0, s, 0,\n\t\t\t 0, 1, 0, 0,\n\t\t\t- s, 0, c, 0,\n\t\t\t 0, 0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\tmakeRotationZ( theta ) {\n\n\t\tconst c = Math.cos( theta ), s = Math.sin( theta );\n\n\t\tthis.set(\n\n\t\t\tc, - s, 0, 0,\n\t\t\ts, c, 0, 0,\n\t\t\t0, 0, 1, 0,\n\t\t\t0, 0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\tmakeRotationAxis( axis, angle ) {\n\n\t\t// Based on http://www.gamedev.net/reference/articles/article1199.asp\n\n\t\tconst c = Math.cos( angle );\n\t\tconst s = Math.sin( angle );\n\t\tconst t = 1 - c;\n\t\tconst x = axis.x, y = axis.y, z = axis.z;\n\t\tconst tx = t * x, ty = t * y;\n\n\t\tthis.set(\n\n\t\t\ttx * x + c, tx * y - s * z, tx * z + s * y, 0,\n\t\t\ttx * y + s * z, ty * y + c, ty * z - s * x, 0,\n\t\t\ttx * z - s * y, ty * z + s * x, t * z * z + c, 0,\n\t\t\t0, 0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\tmakeScale( x, y, z ) {\n\n\t\tthis.set(\n\n\t\t\tx, 0, 0, 0,\n\t\t\t0, y, 0, 0,\n\t\t\t0, 0, z, 0,\n\t\t\t0, 0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\tmakeShear( xy, xz, yx, yz, zx, zy ) {\n\n\t\tthis.set(\n\n\t\t\t1, yx, zx, 0,\n\t\t\txy, 1, zy, 0,\n\t\t\txz, yz, 1, 0,\n\t\t\t0, 0, 0, 1\n\n\t\t);\n\n\t\treturn this;\n\n\t}\n\n\tcompose( position, quaternion, scale ) {\n\n\t\tconst te = this.elements;\n\n\t\tconst x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;\n\t\tconst x2 = x + x,\ty2 = y + y, z2 = z + z;\n\t\tconst xx = x * x2, xy = x * y2, xz = x * z2;\n\t\tconst yy = y * y2, yz = y * z2, zz = z * z2;\n\t\tconst wx = w * x2, wy = w * y2, wz = w * z2;\n\n\t\tconst sx = scale.x, sy = scale.y, sz = scale.z;\n\n\t\tte[ 0 ] = ( 1 - ( yy + zz ) ) * sx;\n\t\tte[ 1 ] = ( xy + wz ) * sx;\n\t\tte[ 2 ] = ( xz - wy ) * sx;\n\t\tte[ 3 ] = 0;\n\n\t\tte[ 4 ] = ( xy - wz ) * sy;\n\t\tte[ 5 ] = ( 1 - ( xx + zz ) ) * sy;\n\t\tte[ 6 ] = ( yz + wx ) * sy;\n\t\tte[ 7 ] = 0;\n\n\t\tte[ 8 ] = ( xz + wy ) * sz;\n\t\tte[ 9 ] = ( yz - wx ) * sz;\n\t\tte[ 10 ] = ( 1 - ( xx + yy ) ) * sz;\n\t\tte[ 11 ] = 0;\n\n\t\tte[ 12 ] = position.x;\n\t\tte[ 13 ] = position.y;\n\t\tte[ 14 ] = position.z;\n\t\tte[ 15 ] = 1;\n\n\t\treturn this;\n\n\t}\n\n\tdecompose( position, quaternion, scale ) {\n\n\t\tconst te = this.elements;\n\n\t\tlet sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();\n\t\tconst sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();\n\t\tconst sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();\n\n\t\t// if determine is negative, we need to invert one scale\n\t\tconst det = this.determinant();\n\t\tif ( det < 0 ) sx = - sx;\n\n\t\tposition.x = te[ 12 ];\n\t\tposition.y = te[ 13 ];\n\t\tposition.z = te[ 14 ];\n\n\t\t// scale the rotation part\n\t\t_m1$2.copy( this );\n\n\t\tconst invSX = 1 / sx;\n\t\tconst invSY = 1 / sy;\n\t\tconst invSZ = 1 / sz;\n\n\t\t_m1$2.elements[ 0 ] *= invSX;\n\t\t_m1$2.elements[ 1 ] *= invSX;\n\t\t_m1$2.elements[ 2 ] *= invSX;\n\n\t\t_m1$2.elements[ 4 ] *= invSY;\n\t\t_m1$2.elements[ 5 ] *= invSY;\n\t\t_m1$2.elements[ 6 ] *= invSY;\n\n\t\t_m1$2.elements[ 8 ] *= invSZ;\n\t\t_m1$2.elements[ 9 ] *= invSZ;\n\t\t_m1$2.elements[ 10 ] *= invSZ;\n\n\t\tquaternion.setFromRotationMatrix( _m1$2 );\n\n\t\tscale.x = sx;\n\t\tscale.y = sy;\n\t\tscale.z = sz;\n\n\t\treturn this;\n\n\t}\n\n\tmakePerspective( left, right, top, bottom, near, far ) {\n\n\t\tconst te = this.elements;\n\t\tconst x = 2 * near / ( right - left );\n\t\tconst y = 2 * near / ( top - bottom );\n\n\t\tconst a = ( right + left ) / ( right - left );\n\t\tconst b = ( top + bottom ) / ( top - bottom );\n\t\tconst c = - ( far + near ) / ( far - near );\n\t\tconst d = - 2 * far * near / ( far - near );\n\n\t\tte[ 0 ] = x;\tte[ 4 ] = 0;\tte[ 8 ] = a;\tte[ 12 ] = 0;\n\t\tte[ 1 ] = 0;\tte[ 5 ] = y;\tte[ 9 ] = b;\tte[ 13 ] = 0;\n\t\tte[ 2 ] = 0;\tte[ 6 ] = 0;\tte[ 10 ] = c;\tte[ 14 ] = d;\n\t\tte[ 3 ] = 0;\tte[ 7 ] = 0;\tte[ 11 ] = - 1;\tte[ 15 ] = 0;\n\n\t\treturn this;\n\n\t}\n\n\tmakeOrthographic( left, right, top, bottom, near, far ) {\n\n\t\tconst te = this.elements;\n\t\tconst w = 1.0 / ( right - left );\n\t\tconst h = 1.0 / ( top - bottom );\n\t\tconst p = 1.0 / ( far - near );\n\n\t\tconst x = ( right + left ) * w;\n\t\tconst y = ( top + bottom ) * h;\n\t\tconst z = ( far + near ) * p;\n\n\t\tte[ 0 ] = 2 * w;\tte[ 4 ] = 0;\tte[ 8 ] = 0;\tte[ 12 ] = - x;\n\t\tte[ 1 ] = 0;\tte[ 5 ] = 2 * h;\tte[ 9 ] = 0;\tte[ 13 ] = - y;\n\t\tte[ 2 ] = 0;\tte[ 6 ] = 0;\tte[ 10 ] = - 2 * p;\tte[ 14 ] = - z;\n\t\tte[ 3 ] = 0;\tte[ 7 ] = 0;\tte[ 11 ] = 0;\tte[ 15 ] = 1;\n\n\t\treturn this;\n\n\t}\n\n\tequals( matrix ) {\n\n\t\tconst te = this.elements;\n\t\tconst me = matrix.elements;\n\n\t\tfor ( let i = 0; i < 16; i ++ ) {\n\n\t\t\tif ( te[ i ] !== me[ i ] ) return false;\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\tfromArray( array, offset = 0 ) {\n\n\t\tfor ( let i = 0; i < 16; i ++ ) {\n\n\t\t\tthis.elements[ i ] = array[ i + offset ];\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\ttoArray( array = [], offset = 0 ) {\n\n\t\tconst te = this.elements;\n\n\t\tarray[ offset ] = te[ 0 ];\n\t\tarray[ offset + 1 ] = te[ 1 ];\n\t\tarray[ offset + 2 ] = te[ 2 ];\n\t\tarray[ offset + 3 ] = te[ 3 ];\n\n\t\tarray[ offset + 4 ] = te[ 4 ];\n\t\tarray[ offset + 5 ] = te[ 5 ];\n\t\tarray[ offset + 6 ] = te[ 6 ];\n\t\tarray[ offset + 7 ] = te[ 7 ];\n\n\t\tarray[ offset + 8 ] = te[ 8 ];\n\t\tarray[ offset + 9 ] = te[ 9 ];\n\t\tarray[ offset + 10 ] = te[ 10 ];\n\t\tarray[ offset + 11 ] = te[ 11 ];\n\n\t\tarray[ offset + 12 ] = te[ 12 ];\n\t\tarray[ offset + 13 ] = te[ 13 ];\n\t\tarray[ offset + 14 ] = te[ 14 ];\n\t\tarray[ offset + 15 ] = te[ 15 ];\n\n\t\treturn array;\n\n\t}\n\n}\n\nconst _v1$5 = /*@__PURE__*/ new Vector3();\nconst _m1$2 = /*@__PURE__*/ new Matrix4();\nconst _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );\nconst _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );\nconst _x = /*@__PURE__*/ new Vector3();\nconst _y = /*@__PURE__*/ new Vector3();\nconst _z = /*@__PURE__*/ new Vector3();\n\nconst _matrix = /*@__PURE__*/ new Matrix4();\nconst _quaternion$3 = /*@__PURE__*/ new Quaternion();\n\nclass Euler {\n\n\tconstructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {\n\n\t\tthis.isEuler = true;\n\n\t\tthis._x = x;\n\t\tthis._y = y;\n\t\tthis._z = z;\n\t\tthis._order = order;\n\n\t}\n\n\tget x() {\n\n\t\treturn this._x;\n\n\t}\n\n\tset x( value ) {\n\n\t\tthis._x = value;\n\t\tthis._onChangeCallback();\n\n\t}\n\n\tget y() {\n\n\t\treturn this._y;\n\n\t}\n\n\tset y( value ) {\n\n\t\tthis._y = value;\n\t\tthis._onChangeCallback();\n\n\t}\n\n\tget z() {\n\n\t\treturn this._z;\n\n\t}\n\n\tset z( value ) {\n\n\t\tthis._z = value;\n\t\tthis._onChangeCallback();\n\n\t}\n\n\tget order() {\n\n\t\treturn this._order;\n\n\t}\n\n\tset order( value ) {\n\n\t\tthis._order = value;\n\t\tthis._onChangeCallback();\n\n\t}\n\n\tset( x, y, z, order = this._order ) {\n\n\t\tthis._x = x;\n\t\tthis._y = y;\n\t\tthis._z = z;\n\t\tthis._order = order;\n\n\t\tthis._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor( this._x, this._y, this._z, this._order );\n\n\t}\n\n\tcopy( euler ) {\n\n\t\tthis._x = euler._x;\n\t\tthis._y = euler._y;\n\t\tthis._z = euler._z;\n\t\tthis._order = euler._order;\n\n\t\tthis._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\tsetFromRotationMatrix( m, order = this._order, update = true ) {\n\n\t\t// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)\n\n\t\tconst te = m.elements;\n\t\tconst m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];\n\t\tconst m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];\n\t\tconst m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];\n\n\t\tswitch ( order ) {\n\n\t\t\tcase 'XYZ':\n\n\t\t\t\tthis._y = Math.asin( clamp( m13, - 1, 1 ) );\n\n\t\t\t\tif ( Math.abs( m13 ) < 0.9999999 ) {\n\n\t\t\t\t\tthis._x = Math.atan2( - m23, m33 );\n\t\t\t\t\tthis._z = Math.atan2( - m12, m11 );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tthis._x = Math.atan2( m32, m22 );\n\t\t\t\t\tthis._z = 0;\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'YXZ':\n\n\t\t\t\tthis._x = Math.asin( - clamp( m23, - 1, 1 ) );\n\n\t\t\t\tif ( Math.abs( m23 ) < 0.9999999 ) {\n\n\t\t\t\t\tthis._y = Math.atan2( m13, m33 );\n\t\t\t\t\tthis._z = Math.atan2( m21, m22 );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tthis._y = Math.atan2( - m31, m11 );\n\t\t\t\t\tthis._z = 0;\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'ZXY':\n\n\t\t\t\tthis._x = Math.asin( clamp( m32, - 1, 1 ) );\n\n\t\t\t\tif ( Math.abs( m32 ) < 0.9999999 ) {\n\n\t\t\t\t\tthis._y = Math.atan2( - m31, m33 );\n\t\t\t\t\tthis._z = Math.atan2( - m12, m22 );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tthis._y = 0;\n\t\t\t\t\tthis._z = Math.atan2( m21, m11 );\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'ZYX':\n\n\t\t\t\tthis._y = Math.asin( - clamp( m31, - 1, 1 ) );\n\n\t\t\t\tif ( Math.abs( m31 ) < 0.9999999 ) {\n\n\t\t\t\t\tthis._x = Math.atan2( m32, m33 );\n\t\t\t\t\tthis._z = Math.atan2( m21, m11 );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tthis._x = 0;\n\t\t\t\t\tthis._z = Math.atan2( - m12, m22 );\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'YZX':\n\n\t\t\t\tthis._z = Math.asin( clamp( m21, - 1, 1 ) );\n\n\t\t\t\tif ( Math.abs( m21 ) < 0.9999999 ) {\n\n\t\t\t\t\tthis._x = Math.atan2( - m23, m22 );\n\t\t\t\t\tthis._y = Math.atan2( - m31, m11 );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tthis._x = 0;\n\t\t\t\t\tthis._y = Math.atan2( m13, m33 );\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'XZY':\n\n\t\t\t\tthis._z = Math.asin( - clamp( m12, - 1, 1 ) );\n\n\t\t\t\tif ( Math.abs( m12 ) < 0.9999999 ) {\n\n\t\t\t\t\tthis._x = Math.atan2( m32, m22 );\n\t\t\t\t\tthis._y = Math.atan2( m13, m11 );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tthis._x = Math.atan2( - m23, m33 );\n\t\t\t\t\tthis._y = 0;\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\n\t\t\t\tconsole.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );\n\n\t\t}\n\n\t\tthis._order = order;\n\n\t\tif ( update === true ) this._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\tsetFromQuaternion( q, order, update ) {\n\n\t\t_matrix.makeRotationFromQuaternion( q );\n\n\t\treturn this.setFromRotationMatrix( _matrix, order, update );\n\n\t}\n\n\tsetFromVector3( v, order = this._order ) {\n\n\t\treturn this.set( v.x, v.y, v.z, order );\n\n\t}\n\n\treorder( newOrder ) {\n\n\t\t// WARNING: this discards revolution information -bhouston\n\n\t\t_quaternion$3.setFromEuler( this );\n\n\t\treturn this.setFromQuaternion( _quaternion$3, newOrder );\n\n\t}\n\n\tequals( euler ) {\n\n\t\treturn ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );\n\n\t}\n\n\tfromArray( array ) {\n\n\t\tthis._x = array[ 0 ];\n\t\tthis._y = array[ 1 ];\n\t\tthis._z = array[ 2 ];\n\t\tif ( array[ 3 ] !== undefined ) this._order = array[ 3 ];\n\n\t\tthis._onChangeCallback();\n\n\t\treturn this;\n\n\t}\n\n\ttoArray( array = [], offset = 0 ) {\n\n\t\tarray[ offset ] = this._x;\n\t\tarray[ offset + 1 ] = this._y;\n\t\tarray[ offset + 2 ] = this._z;\n\t\tarray[ offset + 3 ] = this._order;\n\n\t\treturn array;\n\n\t}\n\n\t_onChange( callback ) {\n\n\t\tthis._onChangeCallback = callback;\n\n\t\treturn this;\n\n\t}\n\n\t_onChangeCallback() {}\n\n\t*[ Symbol.iterator ]() {\n\n\t\tyield this._x;\n\t\tyield this._y;\n\t\tyield this._z;\n\t\tyield this._order;\n\n\t}\n\n}\n\nEuler.DEFAULT_ORDER = 'XYZ';\n\nclass Layers {\n\n\tconstructor() {\n\n\t\tthis.mask = 1 | 0;\n\n\t}\n\n\tset( channel ) {\n\n\t\tthis.mask = ( 1 << channel | 0 ) >>> 0;\n\n\t}\n\n\tenable( channel ) {\n\n\t\tthis.mask |= 1 << channel | 0;\n\n\t}\n\n\tenableAll() {\n\n\t\tthis.mask = 0xffffffff | 0;\n\n\t}\n\n\ttoggle( channel ) {\n\n\t\tthis.mask ^= 1 << channel | 0;\n\n\t}\n\n\tdisable( channel ) {\n\n\t\tthis.mask &= ~ ( 1 << channel | 0 );\n\n\t}\n\n\tdisableAll() {\n\n\t\tthis.mask = 0;\n\n\t}\n\n\ttest( layers ) {\n\n\t\treturn ( this.mask & layers.mask ) !== 0;\n\n\t}\n\n\tisEnabled( channel ) {\n\n\t\treturn ( this.mask & ( 1 << channel | 0 ) ) !== 0;\n\n\t}\n\n}\n\nlet _object3DId = 0;\n\nconst _v1$4 = /*@__PURE__*/ new Vector3();\nconst _q1 = /*@__PURE__*/ new Quaternion();\nconst _m1$1 = /*@__PURE__*/ new Matrix4();\nconst _target = /*@__PURE__*/ new Vector3();\n\nconst _position$3 = /*@__PURE__*/ new Vector3();\nconst _scale$2 = /*@__PURE__*/ new Vector3();\nconst _quaternion$2 = /*@__PURE__*/ new Quaternion();\n\nconst _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );\nconst _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );\nconst _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );\n\nconst _addedEvent = { type: 'added' };\nconst _removedEvent = { type: 'removed' };\n\nclass Object3D extends EventDispatcher {\n\n\tconstructor() {\n\n\t\tsuper();\n\n\t\tthis.isObject3D = true;\n\n\t\tObject.defineProperty( this, 'id', { value: _object3DId ++ } );\n\n\t\tthis.uuid = generateUUID();\n\n\t\tthis.name = '';\n\t\tthis.type = 'Object3D';\n\n\t\tthis.parent = null;\n\t\tthis.children = [];\n\n\t\tthis.up = Object3D.DEFAULT_UP.clone();\n\n\t\tconst position = new Vector3();\n\t\tconst rotation = new Euler();\n\t\tconst quaternion = new Quaternion();\n\t\tconst scale = new Vector3( 1, 1, 1 );\n\n\t\tfunction onRotationChange() {\n\n\t\t\tquaternion.setFromEuler( rotation, false );\n\n\t\t}\n\n\t\tfunction onQuaternionChange() {\n\n\t\t\trotation.setFromQuaternion( quaternion, undefined, false );\n\n\t\t}\n\n\t\trotation._onChange( onRotationChange );\n\t\tquaternion._onChange( onQuaternionChange );\n\n\t\tObject.defineProperties( this, {\n\t\t\tposition: {\n\t\t\t\tconfigurable: true,\n\t\t\t\tenumerable: true,\n\t\t\t\tvalue: position\n\t\t\t},\n\t\t\trotation: {\n\t\t\t\tconfigurable: true,\n\t\t\t\tenumerable: true,\n\t\t\t\tvalue: rotation\n\t\t\t},\n\t\t\tquaternion: {\n\t\t\t\tconfigurable: true,\n\t\t\t\tenumerable: true,\n\t\t\t\tvalue: quaternion\n\t\t\t},\n\t\t\tscale: {\n\t\t\t\tconfigurable: true,\n\t\t\t\tenumerable: true,\n\t\t\t\tvalue: scale\n\t\t\t},\n\t\t\tmodelViewMatrix: {\n\t\t\t\tvalue: new Matrix4()\n\t\t\t},\n\t\t\tnormalMatrix: {\n\t\t\t\tvalue: new Matrix3()\n\t\t\t}\n\t\t} );\n\n\t\tthis.matrix = new Matrix4();\n\t\tthis.matrixWorld = new Matrix4();\n\n\t\tthis.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;\n\t\tthis.matrixWorldNeedsUpdate = false;\n\n\t\tthis.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer\n\n\t\tthis.layers = new Layers();\n\t\tthis.visible = true;\n\n\t\tthis.castShadow = false;\n\t\tthis.receiveShadow = false;\n\n\t\tthis.frustumCulled = true;\n\t\tthis.renderOrder = 0;\n\n\t\tthis.animations = [];\n\n\t\tthis.userData = {};\n\n\t}\n\n\tonBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}\n\n\tonAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}\n\n\tapplyMatrix4( matrix ) {\n\n\t\tif ( this.matrixAutoUpdate ) this.updateMatrix();\n\n\t\tthis.matrix.premultiply( matrix );\n\n\t\tthis.matrix.decompose( this.position, this.quaternion, this.scale );\n\n\t}\n\n\tapplyQuaternion( q ) {\n\n\t\tthis.quaternion.premultiply( q );\n\n\t\treturn this;\n\n\t}\n\n\tsetRotationFromAxisAngle( axis, angle ) {\n\n\t\t// assumes axis is normalized\n\n\t\tthis.quaternion.setFromAxisAngle( axis, angle );\n\n\t}\n\n\tsetRotationFromEuler( euler ) {\n\n\t\tthis.quaternion.setFromEuler( euler, true );\n\n\t}\n\n\tsetRotationFromMatrix( m ) {\n\n\t\t// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)\n\n\t\tthis.quaternion.setFromRotationMatrix( m );\n\n\t}\n\n\tsetRotationFromQuaternion( q ) {\n\n\t\t// assumes q is normalized\n\n\t\tthis.quaternion.copy( q );\n\n\t}\n\n\trotateOnAxis( axis, angle ) {\n\n\t\t// rotate object on axis in object space\n\t\t// axis is assumed to be normalized\n\n\t\t_q1.setFromAxisAngle( axis, angle );\n\n\t\tthis.quaternion.multiply( _q1 );\n\n\t\treturn this;\n\n\t}\n\n\trotateOnWorldAxis( axis, angle ) {\n\n\t\t// rotate object on axis in world space\n\t\t// axis is assumed to be normalized\n\t\t// method assumes no rotated parent\n\n\t\t_q1.setFromAxisAngle( axis, angle );\n\n\t\tthis.quaternion.premultiply( _q1 );\n\n\t\treturn this;\n\n\t}\n\n\trotateX( angle ) {\n\n\t\treturn this.rotateOnAxis( _xAxis, angle );\n\n\t}\n\n\trotateY( angle ) {\n\n\t\treturn this.rotateOnAxis( _yAxis, angle );\n\n\t}\n\n\trotateZ( angle ) {\n\n\t\treturn this.rotateOnAxis( _zAxis, angle );\n\n\t}\n\n\ttranslateOnAxis( axis, distance ) {\n\n\t\t// translate object by distance along axis in object space\n\t\t// axis is assumed to be normalized\n\n\t\t_v1$4.copy( axis ).applyQuaternion( this.quaternion );\n\n\t\tthis.position.add( _v1$4.multiplyScalar( distance ) );\n\n\t\treturn this;\n\n\t}\n\n\ttranslateX( distance ) {\n\n\t\treturn this.translateOnAxis( _xAxis, distance );\n\n\t}\n\n\ttranslateY( distance ) {\n\n\t\treturn this.translateOnAxis( _yAxis, distance );\n\n\t}\n\n\ttranslateZ( distance ) {\n\n\t\treturn this.translateOnAxis( _zAxis, distance );\n\n\t}\n\n\tlocalToWorld( vector ) {\n\n\t\tthis.updateWorldMatrix( true, false );\n\n\t\treturn vector.applyMatrix4( this.matrixWorld );\n\n\t}\n\n\tworldToLocal( vector ) {\n\n\t\tthis.updateWorldMatrix( true, false );\n\n\t\treturn vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );\n\n\t}\n\n\tlookAt( x, y, z ) {\n\n\t\t// This method does not support objects having non-uniformly-scaled parent(s)\n\n\t\tif ( x.isVector3 ) {\n\n\t\t\t_target.copy( x );\n\n\t\t} else {\n\n\t\t\t_target.set( x, y, z );\n\n\t\t}\n\n\t\tconst parent = this.parent;\n\n\t\tthis.updateWorldMatrix( true, false );\n\n\t\t_position$3.setFromMatrixPosition( this.matrixWorld );\n\n\t\tif ( this.isCamera || this.isLight ) {\n\n\t\t\t_m1$1.lookAt( _position$3, _target, this.up );\n\n\t\t} else {\n\n\t\t\t_m1$1.lookAt( _target, _position$3, this.up );\n\n\t\t}\n\n\t\tthis.quaternion.setFromRotationMatrix( _m1$1 );\n\n\t\tif ( parent ) {\n\n\t\t\t_m1$1.extractRotation( parent.matrixWorld );\n\t\t\t_q1.setFromRotationMatrix( _m1$1 );\n\t\t\tthis.quaternion.premultiply( _q1.invert() );\n\n\t\t}\n\n\t}\n\n\tadd( object ) {\n\n\t\tif ( arguments.length > 1 ) {\n\n\t\t\tfor ( let i = 0; i < arguments.length; i ++ ) {\n\n\t\t\t\tthis.add( arguments[ i ] );\n\n\t\t\t}\n\n\t\t\treturn this;\n\n\t\t}\n\n\t\tif ( object === this ) {\n\n\t\t\tconsole.error( 'THREE.Object3D.add: object can\\'t be added as a child of itself.', object );\n\t\t\treturn this;\n\n\t\t}\n\n\t\tif ( object && object.isObject3D ) {\n\n\t\t\tif ( object.parent !== null ) {\n\n\t\t\t\tobject.parent.remove( object );\n\n\t\t\t}\n\n\t\t\tobject.parent = this;\n\t\t\tthis.children.push( object );\n\n\t\t\tobject.dispatchEvent( _addedEvent );\n\n\t\t} else {\n\n\t\t\tconsole.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tremove( object ) {\n\n\t\tif ( arguments.length > 1 ) {\n\n\t\t\tfor ( let i = 0; i < arguments.length; i ++ ) {\n\n\t\t\t\tthis.remove( arguments[ i ] );\n\n\t\t\t}\n\n\t\t\treturn this;\n\n\t\t}\n\n\t\tconst index = this.children.indexOf( object );\n\n\t\tif ( index !== - 1 ) {\n\n\t\t\tobject.parent = null;\n\t\t\tthis.children.splice( index, 1 );\n\n\t\t\tobject.dispatchEvent( _removedEvent );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tremoveFromParent() {\n\n\t\tconst parent = this.parent;\n\n\t\tif ( parent !== null ) {\n\n\t\t\tparent.remove( this );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tclear() {\n\n\t\tfor ( let i = 0; i < this.children.length; i ++ ) {\n\n\t\t\tconst object = this.children[ i ];\n\n\t\t\tobject.parent = null;\n\n\t\t\tobject.dispatchEvent( _removedEvent );\n\n\t\t}\n\n\t\tthis.children.length = 0;\n\n\t\treturn this;\n\n\n\t}\n\n\tattach( object ) {\n\n\t\t// adds object as a child of this, while maintaining the object's world transform\n\n\t\t// Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)\n\n\t\tthis.updateWorldMatrix( true, false );\n\n\t\t_m1$1.copy( this.matrixWorld ).invert();\n\n\t\tif ( object.parent !== null ) {\n\n\t\t\tobject.parent.updateWorldMatrix( true, false );\n\n\t\t\t_m1$1.multiply( object.parent.matrixWorld );\n\n\t\t}\n\n\t\tobject.applyMatrix4( _m1$1 );\n\n\t\tthis.add( object );\n\n\t\tobject.updateWorldMatrix( false, true );\n\n\t\treturn this;\n\n\t}\n\n\tgetObjectById( id ) {\n\n\t\treturn this.getObjectByProperty( 'id', id );\n\n\t}\n\n\tgetObjectByName( name ) {\n\n\t\treturn this.getObjectByProperty( 'name', name );\n\n\t}\n\n\tgetObjectByProperty( name, value ) {\n\n\t\tif ( this[ name ] === value ) return this;\n\n\t\tfor ( let i = 0, l = this.children.length; i < l; i ++ ) {\n\n\t\t\tconst child = this.children[ i ];\n\t\t\tconst object = child.getObjectByProperty( name, value );\n\n\t\t\tif ( object !== undefined ) {\n\n\t\t\t\treturn object;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn undefined;\n\n\t}\n\n\tgetObjectsByProperty( name, value ) {\n\n\t\tlet result = [];\n\n\t\tif ( this[ name ] === value ) result.push( this );\n\n\t\tfor ( let i = 0, l = this.children.length; i < l; i ++ ) {\n\n\t\t\tconst childResult = this.children[ i ].getObjectsByProperty( name, value );\n\n\t\t\tif ( childResult.length > 0 ) {\n\n\t\t\t\tresult = result.concat( childResult );\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn result;\n\n\t}\n\n\tgetWorldPosition( target ) {\n\n\t\tthis.updateWorldMatrix( true, false );\n\n\t\treturn target.setFromMatrixPosition( this.matrixWorld );\n\n\t}\n\n\tgetWorldQuaternion( target ) {\n\n\t\tthis.updateWorldMatrix( true, false );\n\n\t\tthis.matrixWorld.decompose( _position$3, target, _scale$2 );\n\n\t\treturn target;\n\n\t}\n\n\tgetWorldScale( target ) {\n\n\t\tthis.updateWorldMatrix( true, false );\n\n\t\tthis.matrixWorld.decompose( _position$3, _quaternion$2, target );\n\n\t\treturn target;\n\n\t}\n\n\tgetWorldDirection( target ) {\n\n\t\tthis.updateWorldMatrix( true, false );\n\n\t\tconst e = this.matrixWorld.elements;\n\n\t\treturn target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();\n\n\t}\n\n\traycast( /* raycaster, intersects */ ) {}\n\n\ttraverse( callback ) {\n\n\t\tcallback( this );\n\n\t\tconst children = this.children;\n\n\t\tfor ( let i = 0, l = children.length; i < l; i ++ ) {\n\n\t\t\tchildren[ i ].traverse( callback );\n\n\t\t}\n\n\t}\n\n\ttraverseVisible( callback ) {\n\n\t\tif ( this.visible === false ) return;\n\n\t\tcallback( this );\n\n\t\tconst children = this.children;\n\n\t\tfor ( let i = 0, l = children.length; i < l; i ++ ) {\n\n\t\t\tchildren[ i ].traverseVisible( callback );\n\n\t\t}\n\n\t}\n\n\ttraverseAncestors( callback ) {\n\n\t\tconst parent = this.parent;\n\n\t\tif ( parent !== null ) {\n\n\t\t\tcallback( parent );\n\n\t\t\tparent.traverseAncestors( callback );\n\n\t\t}\n\n\t}\n\n\tupdateMatrix() {\n\n\t\tthis.matrix.compose( this.position, this.quaternion, this.scale );\n\n\t\tthis.matrixWorldNeedsUpdate = true;\n\n\t}\n\n\tupdateMatrixWorld( force ) {\n\n\t\tif ( this.matrixAutoUpdate ) this.updateMatrix();\n\n\t\tif ( this.matrixWorldNeedsUpdate || force ) {\n\n\t\t\tif ( this.parent === null ) {\n\n\t\t\t\tthis.matrixWorld.copy( this.matrix );\n\n\t\t\t} else {\n\n\t\t\t\tthis.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );\n\n\t\t\t}\n\n\t\t\tthis.matrixWorldNeedsUpdate = false;\n\n\t\t\tforce = true;\n\n\t\t}\n\n\t\t// update children\n\n\t\tconst children = this.children;\n\n\t\tfor ( let i = 0, l = children.length; i < l; i ++ ) {\n\n\t\t\tconst child = children[ i ];\n\n\t\t\tif ( child.matrixWorldAutoUpdate === true || force === true ) {\n\n\t\t\t\tchild.updateMatrixWorld( force );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tupdateWorldMatrix( updateParents, updateChildren ) {\n\n\t\tconst parent = this.parent;\n\n\t\tif ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {\n\n\t\t\tparent.updateWorldMatrix( true, false );\n\n\t\t}\n\n\t\tif ( this.matrixAutoUpdate ) this.updateMatrix();\n\n\t\tif ( this.parent === null ) {\n\n\t\t\tthis.matrixWorld.copy( this.matrix );\n\n\t\t} else {\n\n\t\t\tthis.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );\n\n\t\t}\n\n\t\t// update children\n\n\t\tif ( updateChildren === true ) {\n\n\t\t\tconst children = this.children;\n\n\t\t\tfor ( let i = 0, l = children.length; i < l; i ++ ) {\n\n\t\t\t\tconst child = children[ i ];\n\n\t\t\t\tif ( child.matrixWorldAutoUpdate === true ) {\n\n\t\t\t\t\tchild.updateWorldMatrix( false, true );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\ttoJSON( meta ) {\n\n\t\t// meta is a string when called from JSON.stringify\n\t\tconst isRootObject = ( meta === undefined || typeof meta === 'string' );\n\n\t\tconst output = {};\n\n\t\t// meta is a hash used to collect geometries, materials.\n\t\t// not providing it implies that this is the root object\n\t\t// being serialized.\n\t\tif ( isRootObject ) {\n\n\t\t\t// initialize meta obj\n\t\t\tmeta = {\n\t\t\t\tgeometries: {},\n\t\t\t\tmaterials: {},\n\t\t\t\ttextures: {},\n\t\t\t\timages: {},\n\t\t\t\tshapes: {},\n\t\t\t\tskeletons: {},\n\t\t\t\tanimations: {},\n\t\t\t\tnodes: {}\n\t\t\t};\n\n\t\t\toutput.metadata = {\n\t\t\t\tversion: 4.5,\n\t\t\t\ttype: 'Object',\n\t\t\t\tgenerator: 'Object3D.toJSON'\n\t\t\t};\n\n\t\t}\n\n\t\t// standard Object3D serialization\n\n\t\tconst object = {};\n\n\t\tobject.uuid = this.uuid;\n\t\tobject.type = this.type;\n\n\t\tif ( this.name !== '' ) object.name = this.name;\n\t\tif ( this.castShadow === true ) object.castShadow = true;\n\t\tif ( this.receiveShadow === true ) object.receiveShadow = true;\n\t\tif ( this.visible === false ) object.visible = false;\n\t\tif ( this.frustumCulled === false ) object.frustumCulled = false;\n\t\tif ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;\n\t\tif ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;\n\n\t\tobject.layers = this.layers.mask;\n\t\tobject.matrix = this.matrix.toArray();\n\t\tobject.up = this.up.toArray();\n\n\t\tif ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;\n\n\t\t// object specific properties\n\n\t\tif ( this.isInstancedMesh ) {\n\n\t\t\tobject.type = 'InstancedMesh';\n\t\t\tobject.count = this.count;\n\t\t\tobject.instanceMatrix = this.instanceMatrix.toJSON();\n\t\t\tif ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();\n\n\t\t}\n\n\t\t//\n\n\t\tfunction serialize( library, element ) {\n\n\t\t\tif ( library[ element.uuid ] === undefined ) {\n\n\t\t\t\tlibrary[ element.uuid ] = element.toJSON( meta );\n\n\t\t\t}\n\n\t\t\treturn element.uuid;\n\n\t\t}\n\n\t\tif ( this.isScene ) {\n\n\t\t\tif ( this.background ) {\n\n\t\t\t\tif ( this.background.isColor ) {\n\n\t\t\t\t\tobject.background = this.background.toJSON();\n\n\t\t\t\t} else if ( this.background.isTexture ) {\n\n\t\t\t\t\tobject.background = this.background.toJSON( meta ).uuid;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {\n\n\t\t\t\tobject.environment = this.environment.toJSON( meta ).uuid;\n\n\t\t\t}\n\n\t\t} else if ( this.isMesh || this.isLine || this.isPoints ) {\n\n\t\t\tobject.geometry = serialize( meta.geometries, this.geometry );\n\n\t\t\tconst parameters = this.geometry.parameters;\n\n\t\t\tif ( parameters !== undefined && parameters.shapes !== undefined ) {\n\n\t\t\t\tconst shapes = parameters.shapes;\n\n\t\t\t\tif ( Array.isArray( shapes ) ) {\n\n\t\t\t\t\tfor ( let i = 0, l = shapes.length; i < l; i ++ ) {\n\n\t\t\t\t\t\tconst shape = shapes[ i ];\n\n\t\t\t\t\t\tserialize( meta.shapes, shape );\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\tserialize( meta.shapes, shapes );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( this.isSkinnedMesh ) {\n\n\t\t\tobject.bindMode = this.bindMode;\n\t\t\tobject.bindMatrix = this.bindMatrix.toArray();\n\n\t\t\tif ( this.skeleton !== undefined ) {\n\n\t\t\t\tserialize( meta.skeletons, this.skeleton );\n\n\t\t\t\tobject.skeleton = this.skeleton.uuid;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( this.material !== undefined ) {\n\n\t\t\tif ( Array.isArray( this.material ) ) {\n\n\t\t\t\tconst uuids = [];\n\n\t\t\t\tfor ( let i = 0, l = this.material.length; i < l; i ++ ) {\n\n\t\t\t\t\tuuids.push( serialize( meta.materials, this.material[ i ] ) );\n\n\t\t\t\t}\n\n\t\t\t\tobject.material = uuids;\n\n\t\t\t} else {\n\n\t\t\t\tobject.material = serialize( meta.materials, this.material );\n\n\t\t\t}\n\n\t\t}\n\n\t\t//\n\n\t\tif ( this.children.length > 0 ) {\n\n\t\t\tobject.children = [];\n\n\t\t\tfor ( let i = 0; i < this.children.length; i ++ ) {\n\n\t\t\t\tobject.children.push( this.children[ i ].toJSON( meta ).object );\n\n\t\t\t}\n\n\t\t}\n\n\t\t//\n\n\t\tif ( this.animations.length > 0 ) {\n\n\t\t\tobject.animations = [];\n\n\t\t\tfor ( let i = 0; i < this.animations.length; i ++ ) {\n\n\t\t\t\tconst animation = this.animations[ i ];\n\n\t\t\t\tobject.animations.push( serialize( meta.animations, animation ) );\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( isRootObject ) {\n\n\t\t\tconst geometries = extractFromCache( meta.geometries );\n\t\t\tconst materials = extractFromCache( meta.materials );\n\t\t\tconst textures = extractFromCache( meta.textures );\n\t\t\tconst images = extractFromCache( meta.images );\n\t\t\tconst shapes = extractFromCache( meta.shapes );\n\t\t\tconst skeletons = extractFromCache( meta.skeletons );\n\t\t\tconst animations = extractFromCache( meta.animations );\n\t\t\tconst nodes = extractFromCache( meta.nodes );\n\n\t\t\tif ( geometries.length > 0 ) output.geometries = geometries;\n\t\t\tif ( materials.length > 0 ) output.materials = materials;\n\t\t\tif ( textures.length > 0 ) output.textures = textures;\n\t\t\tif ( images.length > 0 ) output.images = images;\n\t\t\tif ( shapes.length > 0 ) output.shapes = shapes;\n\t\t\tif ( skeletons.length > 0 ) output.skeletons = skeletons;\n\t\t\tif ( animations.length > 0 ) output.animations = animations;\n\t\t\tif ( nodes.length > 0 ) output.nodes = nodes;\n\n\t\t}\n\n\t\toutput.object = object;\n\n\t\treturn output;\n\n\t\t// extract data from the cache hash\n\t\t// remove metadata on each item\n\t\t// and return as array\n\t\tfunction extractFromCache( cache ) {\n\n\t\t\tconst values = [];\n\t\t\tfor ( const key in cache ) {\n\n\t\t\t\tconst data = cache[ key ];\n\t\t\t\tdelete data.metadata;\n\t\t\t\tvalues.push( data );\n\n\t\t\t}\n\n\t\t\treturn values;\n\n\t\t}\n\n\t}\n\n\tclone( recursive ) {\n\n\t\treturn new this.constructor().copy( this, recursive );\n\n\t}\n\n\tcopy( source, recursive = true ) {\n\n\t\tthis.name = source.name;\n\n\t\tthis.up.copy( source.up );\n\n\t\tthis.position.copy( source.position );\n\t\tthis.rotation.order = source.rotation.order;\n\t\tthis.quaternion.copy( source.quaternion );\n\t\tthis.scale.copy( source.scale );\n\n\t\tthis.matrix.copy( source.matrix );\n\t\tthis.matrixWorld.copy( source.matrixWorld );\n\n\t\tthis.matrixAutoUpdate = source.matrixAutoUpdate;\n\t\tthis.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;\n\n\t\tthis.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;\n\n\t\tthis.layers.mask = source.layers.mask;\n\t\tthis.visible = source.visible;\n\n\t\tthis.castShadow = source.castShadow;\n\t\tthis.receiveShadow = source.receiveShadow;\n\n\t\tthis.frustumCulled = source.frustumCulled;\n\t\tthis.renderOrder = source.renderOrder;\n\n\t\tthis.animations = source.animations;\n\n\t\tthis.userData = JSON.parse( JSON.stringify( source.userData ) );\n\n\t\tif ( recursive === true ) {\n\n\t\t\tfor ( let i = 0; i < source.children.length; i ++ ) {\n\n\t\t\t\tconst child = source.children[ i ];\n\t\t\t\tthis.add( child.clone() );\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n}\n\nObject3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );\nObject3D.DEFAULT_MATRIX_AUTO_UPDATE = true;\nObject3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;\n\nconst _v0$1 = /*@__PURE__*/ new Vector3();\nconst _v1$3 = /*@__PURE__*/ new Vector3();\nconst _v2$2 = /*@__PURE__*/ new Vector3();\nconst _v3$1 = /*@__PURE__*/ new Vector3();\n\nconst _vab = /*@__PURE__*/ new Vector3();\nconst _vac = /*@__PURE__*/ new Vector3();\nconst _vbc = /*@__PURE__*/ new Vector3();\nconst _vap = /*@__PURE__*/ new Vector3();\nconst _vbp = /*@__PURE__*/ new Vector3();\nconst _vcp = /*@__PURE__*/ new Vector3();\n\nlet warnedGetUV = false;\n\nclass Triangle {\n\n\tconstructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {\n\n\t\tthis.a = a;\n\t\tthis.b = b;\n\t\tthis.c = c;\n\n\t}\n\n\tstatic getNormal( a, b, c, target ) {\n\n\t\ttarget.subVectors( c, b );\n\t\t_v0$1.subVectors( a, b );\n\t\ttarget.cross( _v0$1 );\n\n\t\tconst targetLengthSq = target.lengthSq();\n\t\tif ( targetLengthSq > 0 ) {\n\n\t\t\treturn target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );\n\n\t\t}\n\n\t\treturn target.set( 0, 0, 0 );\n\n\t}\n\n\t// static/instance method to calculate barycentric coordinates\n\t// based on: http://www.blackpawn.com/texts/pointinpoly/default.html\n\tstatic getBarycoord( point, a, b, c, target ) {\n\n\t\t_v0$1.subVectors( c, a );\n\t\t_v1$3.subVectors( b, a );\n\t\t_v2$2.subVectors( point, a );\n\n\t\tconst dot00 = _v0$1.dot( _v0$1 );\n\t\tconst dot01 = _v0$1.dot( _v1$3 );\n\t\tconst dot02 = _v0$1.dot( _v2$2 );\n\t\tconst dot11 = _v1$3.dot( _v1$3 );\n\t\tconst dot12 = _v1$3.dot( _v2$2 );\n\n\t\tconst denom = ( dot00 * dot11 - dot01 * dot01 );\n\n\t\t// collinear or singular triangle\n\t\tif ( denom === 0 ) {\n\n\t\t\t// arbitrary location outside of triangle?\n\t\t\t// not sure if this is the best idea, maybe should be returning undefined\n\t\t\treturn target.set( - 2, - 1, - 1 );\n\n\t\t}\n\n\t\tconst invDenom = 1 / denom;\n\t\tconst u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;\n\t\tconst v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;\n\n\t\t// barycentric coordinates must always sum to 1\n\t\treturn target.set( 1 - u - v, v, u );\n\n\t}\n\n\tstatic containsPoint( point, a, b, c ) {\n\n\t\tthis.getBarycoord( point, a, b, c, _v3$1 );\n\n\t\treturn ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );\n\n\t}\n\n\tstatic getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { // @deprecated, r151\n\n\t\tif ( warnedGetUV === false ) {\n\n\t\t\tconsole.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );\n\n\t\t\twarnedGetUV = true;\n\n\t\t}\n\n\t\treturn this.getInterpolation( point, p1, p2, p3, uv1, uv2, uv3, target );\n\n\t}\n\n\tstatic getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {\n\n\t\tthis.getBarycoord( point, p1, p2, p3, _v3$1 );\n\n\t\ttarget.setScalar( 0 );\n\t\ttarget.addScaledVector( v1, _v3$1.x );\n\t\ttarget.addScaledVector( v2, _v3$1.y );\n\t\ttarget.addScaledVector( v3, _v3$1.z );\n\n\t\treturn target;\n\n\t}\n\n\tstatic isFrontFacing( a, b, c, direction ) {\n\n\t\t_v0$1.subVectors( c, b );\n\t\t_v1$3.subVectors( a, b );\n\n\t\t// strictly front facing\n\t\treturn ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;\n\n\t}\n\n\tset( a, b, c ) {\n\n\t\tthis.a.copy( a );\n\t\tthis.b.copy( b );\n\t\tthis.c.copy( c );\n\n\t\treturn this;\n\n\t}\n\n\tsetFromPointsAndIndices( points, i0, i1, i2 ) {\n\n\t\tthis.a.copy( points[ i0 ] );\n\t\tthis.b.copy( points[ i1 ] );\n\t\tthis.c.copy( points[ i2 ] );\n\n\t\treturn this;\n\n\t}\n\n\tsetFromAttributeAndIndices( attribute, i0, i1, i2 ) {\n\n\t\tthis.a.fromBufferAttribute( attribute, i0 );\n\t\tthis.b.fromBufferAttribute( attribute, i1 );\n\t\tthis.c.fromBufferAttribute( attribute, i2 );\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n\tcopy( triangle ) {\n\n\t\tthis.a.copy( triangle.a );\n\t\tthis.b.copy( triangle.b );\n\t\tthis.c.copy( triangle.c );\n\n\t\treturn this;\n\n\t}\n\n\tgetArea() {\n\n\t\t_v0$1.subVectors( this.c, this.b );\n\t\t_v1$3.subVectors( this.a, this.b );\n\n\t\treturn _v0$1.cross( _v1$3 ).length() * 0.5;\n\n\t}\n\n\tgetMidpoint( target ) {\n\n\t\treturn target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );\n\n\t}\n\n\tgetNormal( target ) {\n\n\t\treturn Triangle.getNormal( this.a, this.b, this.c, target );\n\n\t}\n\n\tgetPlane( target ) {\n\n\t\treturn target.setFromCoplanarPoints( this.a, this.b, this.c );\n\n\t}\n\n\tgetBarycoord( point, target ) {\n\n\t\treturn Triangle.getBarycoord( point, this.a, this.b, this.c, target );\n\n\t}\n\n\tgetUV( point, uv1, uv2, uv3, target ) { // @deprecated, r151\n\n\t\tif ( warnedGetUV === false ) {\n\n\t\t\tconsole.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );\n\n\t\t\twarnedGetUV = true;\n\n\t\t}\n\n\t\treturn Triangle.getInterpolation( point, this.a, this.b, this.c, uv1, uv2, uv3, target );\n\n\t}\n\n\tgetInterpolation( point, v1, v2, v3, target ) {\n\n\t\treturn Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );\n\n\t}\n\n\tcontainsPoint( point ) {\n\n\t\treturn Triangle.containsPoint( point, this.a, this.b, this.c );\n\n\t}\n\n\tisFrontFacing( direction ) {\n\n\t\treturn Triangle.isFrontFacing( this.a, this.b, this.c, direction );\n\n\t}\n\n\tintersectsBox( box ) {\n\n\t\treturn box.intersectsTriangle( this );\n\n\t}\n\n\tclosestPointToPoint( p, target ) {\n\n\t\tconst a = this.a, b = this.b, c = this.c;\n\t\tlet v, w;\n\n\t\t// algorithm thanks to Real-Time Collision Detection by Christer Ericson,\n\t\t// published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,\n\t\t// under the accompanying license; see chapter 5.1.5 for detailed explanation.\n\t\t// basically, we're distinguishing which of the voronoi regions of the triangle\n\t\t// the point lies in with the minimum amount of redundant computation.\n\n\t\t_vab.subVectors( b, a );\n\t\t_vac.subVectors( c, a );\n\t\t_vap.subVectors( p, a );\n\t\tconst d1 = _vab.dot( _vap );\n\t\tconst d2 = _vac.dot( _vap );\n\t\tif ( d1 <= 0 && d2 <= 0 ) {\n\n\t\t\t// vertex region of A; barycentric coords (1, 0, 0)\n\t\t\treturn target.copy( a );\n\n\t\t}\n\n\t\t_vbp.subVectors( p, b );\n\t\tconst d3 = _vab.dot( _vbp );\n\t\tconst d4 = _vac.dot( _vbp );\n\t\tif ( d3 >= 0 && d4 <= d3 ) {\n\n\t\t\t// vertex region of B; barycentric coords (0, 1, 0)\n\t\t\treturn target.copy( b );\n\n\t\t}\n\n\t\tconst vc = d1 * d4 - d3 * d2;\n\t\tif ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {\n\n\t\t\tv = d1 / ( d1 - d3 );\n\t\t\t// edge region of AB; barycentric coords (1-v, v, 0)\n\t\t\treturn target.copy( a ).addScaledVector( _vab, v );\n\n\t\t}\n\n\t\t_vcp.subVectors( p, c );\n\t\tconst d5 = _vab.dot( _vcp );\n\t\tconst d6 = _vac.dot( _vcp );\n\t\tif ( d6 >= 0 && d5 <= d6 ) {\n\n\t\t\t// vertex region of C; barycentric coords (0, 0, 1)\n\t\t\treturn target.copy( c );\n\n\t\t}\n\n\t\tconst vb = d5 * d2 - d1 * d6;\n\t\tif ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {\n\n\t\t\tw = d2 / ( d2 - d6 );\n\t\t\t// edge region of AC; barycentric coords (1-w, 0, w)\n\t\t\treturn target.copy( a ).addScaledVector( _vac, w );\n\n\t\t}\n\n\t\tconst va = d3 * d6 - d5 * d4;\n\t\tif ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {\n\n\t\t\t_vbc.subVectors( c, b );\n\t\t\tw = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );\n\t\t\t// edge region of BC; barycentric coords (0, 1-w, w)\n\t\t\treturn target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC\n\n\t\t}\n\n\t\t// face region\n\t\tconst denom = 1 / ( va + vb + vc );\n\t\t// u = va * denom\n\t\tv = vb * denom;\n\t\tw = vc * denom;\n\n\t\treturn target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );\n\n\t}\n\n\tequals( triangle ) {\n\n\t\treturn triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );\n\n\t}\n\n}\n\nlet materialId = 0;\n\nclass Material extends EventDispatcher {\n\n\tconstructor() {\n\n\t\tsuper();\n\n\t\tthis.isMaterial = true;\n\n\t\tObject.defineProperty( this, 'id', { value: materialId ++ } );\n\n\t\tthis.uuid = generateUUID();\n\n\t\tthis.name = '';\n\t\tthis.type = 'Material';\n\n\t\tthis.blending = NormalBlending;\n\t\tthis.side = FrontSide;\n\t\tthis.vertexColors = false;\n\n\t\tthis.opacity = 1;\n\t\tthis.transparent = false;\n\n\t\tthis.blendSrc = SrcAlphaFactor;\n\t\tthis.blendDst = OneMinusSrcAlphaFactor;\n\t\tthis.blendEquation = AddEquation;\n\t\tthis.blendSrcAlpha = null;\n\t\tthis.blendDstAlpha = null;\n\t\tthis.blendEquationAlpha = null;\n\n\t\tthis.depthFunc = LessEqualDepth;\n\t\tthis.depthTest = true;\n\t\tthis.depthWrite = true;\n\n\t\tthis.stencilWriteMask = 0xff;\n\t\tthis.stencilFunc = AlwaysStencilFunc;\n\t\tthis.stencilRef = 0;\n\t\tthis.stencilFuncMask = 0xff;\n\t\tthis.stencilFail = KeepStencilOp;\n\t\tthis.stencilZFail = KeepStencilOp;\n\t\tthis.stencilZPass = KeepStencilOp;\n\t\tthis.stencilWrite = false;\n\n\t\tthis.clippingPlanes = null;\n\t\tthis.clipIntersection = false;\n\t\tthis.clipShadows = false;\n\n\t\tthis.shadowSide = null;\n\n\t\tthis.colorWrite = true;\n\n\t\tthis.precision = null; // override the renderer's default precision for this material\n\n\t\tthis.polygonOffset = false;\n\t\tthis.polygonOffsetFactor = 0;\n\t\tthis.polygonOffsetUnits = 0;\n\n\t\tthis.dithering = false;\n\n\t\tthis.alphaToCoverage = false;\n\t\tthis.premultipliedAlpha = false;\n\t\tthis.forceSinglePass = false;\n\n\t\tthis.visible = true;\n\n\t\tthis.toneMapped = true;\n\n\t\tthis.userData = {};\n\n\t\tthis.version = 0;\n\n\t\tthis._alphaTest = 0;\n\n\t}\n\n\tget alphaTest() {\n\n\t\treturn this._alphaTest;\n\n\t}\n\n\tset alphaTest( value ) {\n\n\t\tif ( this._alphaTest > 0 !== value > 0 ) {\n\n\t\t\tthis.version ++;\n\n\t\t}\n\n\t\tthis._alphaTest = value;\n\n\t}\n\n\tonBuild( /* shaderobject, renderer */ ) {}\n\n\tonBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}\n\n\tonBeforeCompile( /* shaderobject, renderer */ ) {}\n\n\tcustomProgramCacheKey() {\n\n\t\treturn this.onBeforeCompile.toString();\n\n\t}\n\n\tsetValues( values ) {\n\n\t\tif ( values === undefined ) return;\n\n\t\tfor ( const key in values ) {\n\n\t\t\tconst newValue = values[ key ];\n\n\t\t\tif ( newValue === undefined ) {\n\n\t\t\t\tconsole.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t\tconst currentValue = this[ key ];\n\n\t\t\tif ( currentValue === undefined ) {\n\n\t\t\t\tconsole.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t\tif ( currentValue && currentValue.isColor ) {\n\n\t\t\t\tcurrentValue.set( newValue );\n\n\t\t\t} else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {\n\n\t\t\t\tcurrentValue.copy( newValue );\n\n\t\t\t} else {\n\n\t\t\t\tthis[ key ] = newValue;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\ttoJSON( meta ) {\n\n\t\tconst isRootObject = ( meta === undefined || typeof meta === 'string' );\n\n\t\tif ( isRootObject ) {\n\n\t\t\tmeta = {\n\t\t\t\ttextures: {},\n\t\t\t\timages: {}\n\t\t\t};\n\n\t\t}\n\n\t\tconst data = {\n\t\t\tmetadata: {\n\t\t\t\tversion: 4.5,\n\t\t\t\ttype: 'Material',\n\t\t\t\tgenerator: 'Material.toJSON'\n\t\t\t}\n\t\t};\n\n\t\t// standard Material serialization\n\t\tdata.uuid = this.uuid;\n\t\tdata.type = this.type;\n\n\t\tif ( this.name !== '' ) data.name = this.name;\n\n\t\tif ( this.color && this.color.isColor ) data.color = this.color.getHex();\n\n\t\tif ( this.roughness !== undefined ) data.roughness = this.roughness;\n\t\tif ( this.metalness !== undefined ) data.metalness = this.metalness;\n\n\t\tif ( this.sheen !== undefined ) data.sheen = this.sheen;\n\t\tif ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();\n\t\tif ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;\n\t\tif ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();\n\t\tif ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;\n\n\t\tif ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();\n\t\tif ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;\n\t\tif ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();\n\t\tif ( this.shininess !== undefined ) data.shininess = this.shininess;\n\t\tif ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;\n\t\tif ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;\n\n\t\tif ( this.clearcoatMap && this.clearcoatMap.isTexture ) {\n\n\t\t\tdata.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;\n\n\t\t}\n\n\t\tif ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {\n\n\t\t\tdata.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;\n\n\t\t}\n\n\t\tif ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {\n\n\t\t\tdata.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;\n\t\t\tdata.clearcoatNormalScale = this.clearcoatNormalScale.toArray();\n\n\t\t}\n\n\t\tif ( this.iridescence !== undefined ) data.iridescence = this.iridescence;\n\t\tif ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;\n\t\tif ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;\n\n\t\tif ( this.iridescenceMap && this.iridescenceMap.isTexture ) {\n\n\t\t\tdata.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;\n\n\t\t}\n\n\t\tif ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {\n\n\t\t\tdata.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;\n\n\t\t}\n\n\t\tif ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;\n\t\tif ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;\n\t\tif ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;\n\n\t\tif ( this.lightMap && this.lightMap.isTexture ) {\n\n\t\t\tdata.lightMap = this.lightMap.toJSON( meta ).uuid;\n\t\t\tdata.lightMapIntensity = this.lightMapIntensity;\n\n\t\t}\n\n\t\tif ( this.aoMap && this.aoMap.isTexture ) {\n\n\t\t\tdata.aoMap = this.aoMap.toJSON( meta ).uuid;\n\t\t\tdata.aoMapIntensity = this.aoMapIntensity;\n\n\t\t}\n\n\t\tif ( this.bumpMap && this.bumpMap.isTexture ) {\n\n\t\t\tdata.bumpMap = this.bumpMap.toJSON( meta ).uuid;\n\t\t\tdata.bumpScale = this.bumpScale;\n\n\t\t}\n\n\t\tif ( this.normalMap && this.normalMap.isTexture ) {\n\n\t\t\tdata.normalMap = this.normalMap.toJSON( meta ).uuid;\n\t\t\tdata.normalMapType = this.normalMapType;\n\t\t\tdata.normalScale = this.normalScale.toArray();\n\n\t\t}\n\n\t\tif ( this.displacementMap && this.displacementMap.isTexture ) {\n\n\t\t\tdata.displacementMap = this.displacementMap.toJSON( meta ).uuid;\n\t\t\tdata.displacementScale = this.displacementScale;\n\t\t\tdata.displacementBias = this.displacementBias;\n\n\t\t}\n\n\t\tif ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;\n\t\tif ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;\n\n\t\tif ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;\n\t\tif ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;\n\t\tif ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;\n\t\tif ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;\n\n\t\tif ( this.envMap && this.envMap.isTexture ) {\n\n\t\t\tdata.envMap = this.envMap.toJSON( meta ).uuid;\n\n\t\t\tif ( this.combine !== undefined ) data.combine = this.combine;\n\n\t\t}\n\n\t\tif ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;\n\t\tif ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;\n\t\tif ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;\n\n\t\tif ( this.gradientMap && this.gradientMap.isTexture ) {\n\n\t\t\tdata.gradientMap = this.gradientMap.toJSON( meta ).uuid;\n\n\t\t}\n\n\t\tif ( this.transmission !== undefined ) data.transmission = this.transmission;\n\t\tif ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;\n\t\tif ( this.thickness !== undefined ) data.thickness = this.thickness;\n\t\tif ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;\n\t\tif ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;\n\t\tif ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();\n\n\t\tif ( this.size !== undefined ) data.size = this.size;\n\t\tif ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;\n\t\tif ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;\n\n\t\tif ( this.blending !== NormalBlending ) data.blending = this.blending;\n\t\tif ( this.side !== FrontSide ) data.side = this.side;\n\t\tif ( this.vertexColors ) data.vertexColors = true;\n\n\t\tif ( this.opacity < 1 ) data.opacity = this.opacity;\n\t\tif ( this.transparent === true ) data.transparent = this.transparent;\n\n\t\tdata.depthFunc = this.depthFunc;\n\t\tdata.depthTest = this.depthTest;\n\t\tdata.depthWrite = this.depthWrite;\n\t\tdata.colorWrite = this.colorWrite;\n\n\t\tdata.stencilWrite = this.stencilWrite;\n\t\tdata.stencilWriteMask = this.stencilWriteMask;\n\t\tdata.stencilFunc = this.stencilFunc;\n\t\tdata.stencilRef = this.stencilRef;\n\t\tdata.stencilFuncMask = this.stencilFuncMask;\n\t\tdata.stencilFail = this.stencilFail;\n\t\tdata.stencilZFail = this.stencilZFail;\n\t\tdata.stencilZPass = this.stencilZPass;\n\n\t\t// rotation (SpriteMaterial)\n\t\tif ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;\n\n\t\tif ( this.polygonOffset === true ) data.polygonOffset = true;\n\t\tif ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;\n\t\tif ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;\n\n\t\tif ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;\n\t\tif ( this.dashSize !== undefined ) data.dashSize = this.dashSize;\n\t\tif ( this.gapSize !== undefined ) data.gapSize = this.gapSize;\n\t\tif ( this.scale !== undefined ) data.scale = this.scale;\n\n\t\tif ( this.dithering === true ) data.dithering = true;\n\n\t\tif ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;\n\t\tif ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;\n\t\tif ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;\n\t\tif ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;\n\n\t\tif ( this.wireframe === true ) data.wireframe = this.wireframe;\n\t\tif ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;\n\t\tif ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;\n\t\tif ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;\n\n\t\tif ( this.flatShading === true ) data.flatShading = this.flatShading;\n\n\t\tif ( this.visible === false ) data.visible = false;\n\n\t\tif ( this.toneMapped === false ) data.toneMapped = false;\n\n\t\tif ( this.fog === false ) data.fog = false;\n\n\t\tif ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;\n\n\t\t// TODO: Copied from Object3D.toJSON\n\n\t\tfunction extractFromCache( cache ) {\n\n\t\t\tconst values = [];\n\n\t\t\tfor ( const key in cache ) {\n\n\t\t\t\tconst data = cache[ key ];\n\t\t\t\tdelete data.metadata;\n\t\t\t\tvalues.push( data );\n\n\t\t\t}\n\n\t\t\treturn values;\n\n\t\t}\n\n\t\tif ( isRootObject ) {\n\n\t\t\tconst textures = extractFromCache( meta.textures );\n\t\t\tconst images = extractFromCache( meta.images );\n\n\t\t\tif ( textures.length > 0 ) data.textures = textures;\n\t\t\tif ( images.length > 0 ) data.images = images;\n\n\t\t}\n\n\t\treturn data;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tthis.name = source.name;\n\n\t\tthis.blending = source.blending;\n\t\tthis.side = source.side;\n\t\tthis.vertexColors = source.vertexColors;\n\n\t\tthis.opacity = source.opacity;\n\t\tthis.transparent = source.transparent;\n\n\t\tthis.blendSrc = source.blendSrc;\n\t\tthis.blendDst = source.blendDst;\n\t\tthis.blendEquation = source.blendEquation;\n\t\tthis.blendSrcAlpha = source.blendSrcAlpha;\n\t\tthis.blendDstAlpha = source.blendDstAlpha;\n\t\tthis.blendEquationAlpha = source.blendEquationAlpha;\n\n\t\tthis.depthFunc = source.depthFunc;\n\t\tthis.depthTest = source.depthTest;\n\t\tthis.depthWrite = source.depthWrite;\n\n\t\tthis.stencilWriteMask = source.stencilWriteMask;\n\t\tthis.stencilFunc = source.stencilFunc;\n\t\tthis.stencilRef = source.stencilRef;\n\t\tthis.stencilFuncMask = source.stencilFuncMask;\n\t\tthis.stencilFail = source.stencilFail;\n\t\tthis.stencilZFail = source.stencilZFail;\n\t\tthis.stencilZPass = source.stencilZPass;\n\t\tthis.stencilWrite = source.stencilWrite;\n\n\t\tconst srcPlanes = source.clippingPlanes;\n\t\tlet dstPlanes = null;\n\n\t\tif ( srcPlanes !== null ) {\n\n\t\t\tconst n = srcPlanes.length;\n\t\t\tdstPlanes = new Array( n );\n\n\t\t\tfor ( let i = 0; i !== n; ++ i ) {\n\n\t\t\t\tdstPlanes[ i ] = srcPlanes[ i ].clone();\n\n\t\t\t}\n\n\t\t}\n\n\t\tthis.clippingPlanes = dstPlanes;\n\t\tthis.clipIntersection = source.clipIntersection;\n\t\tthis.clipShadows = source.clipShadows;\n\n\t\tthis.shadowSide = source.shadowSide;\n\n\t\tthis.colorWrite = source.colorWrite;\n\n\t\tthis.precision = source.precision;\n\n\t\tthis.polygonOffset = source.polygonOffset;\n\t\tthis.polygonOffsetFactor = source.polygonOffsetFactor;\n\t\tthis.polygonOffsetUnits = source.polygonOffsetUnits;\n\n\t\tthis.dithering = source.dithering;\n\n\t\tthis.alphaTest = source.alphaTest;\n\t\tthis.alphaToCoverage = source.alphaToCoverage;\n\t\tthis.premultipliedAlpha = source.premultipliedAlpha;\n\t\tthis.forceSinglePass = source.forceSinglePass;\n\n\t\tthis.visible = source.visible;\n\n\t\tthis.toneMapped = source.toneMapped;\n\n\t\tthis.userData = JSON.parse( JSON.stringify( source.userData ) );\n\n\t\treturn this;\n\n\t}\n\n\tdispose() {\n\n\t\tthis.dispatchEvent( { type: 'dispose' } );\n\n\t}\n\n\tset needsUpdate( value ) {\n\n\t\tif ( value === true ) this.version ++;\n\n\t}\n\n}\n\nconst _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,\n\t'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,\n\t'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,\n\t'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,\n\t'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,\n\t'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,\n\t'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,\n\t'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,\n\t'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,\n\t'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,\n\t'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,\n\t'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,\n\t'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,\n\t'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,\n\t'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,\n\t'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,\n\t'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,\n\t'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,\n\t'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,\n\t'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,\n\t'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,\n\t'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,\n\t'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,\n\t'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };\n\nconst _hslA = { h: 0, s: 0, l: 0 };\nconst _hslB = { h: 0, s: 0, l: 0 };\n\nfunction hue2rgb( p, q, t ) {\n\n\tif ( t < 0 ) t += 1;\n\tif ( t > 1 ) t -= 1;\n\tif ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;\n\tif ( t < 1 / 2 ) return q;\n\tif ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );\n\treturn p;\n\n}\n\nclass Color {\n\n\tconstructor( r, g, b ) {\n\n\t\tthis.isColor = true;\n\n\t\tthis.r = 1;\n\t\tthis.g = 1;\n\t\tthis.b = 1;\n\n\t\tif ( g === undefined && b === undefined ) {\n\n\t\t\t// r is THREE.Color, hex or string\n\t\t\treturn this.set( r );\n\n\t\t}\n\n\t\treturn this.setRGB( r, g, b );\n\n\t}\n\n\tset( value ) {\n\n\t\tif ( value && value.isColor ) {\n\n\t\t\tthis.copy( value );\n\n\t\t} else if ( typeof value === 'number' ) {\n\n\t\t\tthis.setHex( value );\n\n\t\t} else if ( typeof value === 'string' ) {\n\n\t\t\tthis.setStyle( value );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tsetScalar( scalar ) {\n\n\t\tthis.r = scalar;\n\t\tthis.g = scalar;\n\t\tthis.b = scalar;\n\n\t\treturn this;\n\n\t}\n\n\tsetHex( hex, colorSpace = SRGBColorSpace ) {\n\n\t\thex = Math.floor( hex );\n\n\t\tthis.r = ( hex >> 16 & 255 ) / 255;\n\t\tthis.g = ( hex >> 8 & 255 ) / 255;\n\t\tthis.b = ( hex & 255 ) / 255;\n\n\t\tColorManagement.toWorkingColorSpace( this, colorSpace );\n\n\t\treturn this;\n\n\t}\n\n\tsetRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {\n\n\t\tthis.r = r;\n\t\tthis.g = g;\n\t\tthis.b = b;\n\n\t\tColorManagement.toWorkingColorSpace( this, colorSpace );\n\n\t\treturn this;\n\n\t}\n\n\tsetHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {\n\n\t\t// h,s,l ranges are in 0.0 - 1.0\n\t\th = euclideanModulo( h, 1 );\n\t\ts = clamp( s, 0, 1 );\n\t\tl = clamp( l, 0, 1 );\n\n\t\tif ( s === 0 ) {\n\n\t\t\tthis.r = this.g = this.b = l;\n\n\t\t} else {\n\n\t\t\tconst p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );\n\t\t\tconst q = ( 2 * l ) - p;\n\n\t\t\tthis.r = hue2rgb( q, p, h + 1 / 3 );\n\t\t\tthis.g = hue2rgb( q, p, h );\n\t\t\tthis.b = hue2rgb( q, p, h - 1 / 3 );\n\n\t\t}\n\n\t\tColorManagement.toWorkingColorSpace( this, colorSpace );\n\n\t\treturn this;\n\n\t}\n\n\tsetStyle( style, colorSpace = SRGBColorSpace ) {\n\n\t\tfunction handleAlpha( string ) {\n\n\t\t\tif ( string === undefined ) return;\n\n\t\t\tif ( parseFloat( string ) < 1 ) {\n\n\t\t\t\tconsole.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );\n\n\t\t\t}\n\n\t\t}\n\n\n\t\tlet m;\n\n\t\tif ( m = /^(\\w+)\\(([^\\)]*)\\)/.exec( style ) ) {\n\n\t\t\t// rgb / hsl\n\n\t\t\tlet color;\n\t\t\tconst name = m[ 1 ];\n\t\t\tconst components = m[ 2 ];\n\n\t\t\tswitch ( name ) {\n\n\t\t\t\tcase 'rgb':\n\t\t\t\tcase 'rgba':\n\n\t\t\t\t\tif ( color = /^\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*(\\d*\\.?\\d+)\\s*)?$/.exec( components ) ) {\n\n\t\t\t\t\t\t// rgb(255,0,0) rgba(255,0,0,0.5)\n\n\t\t\t\t\t\thandleAlpha( color[ 4 ] );\n\n\t\t\t\t\t\treturn this.setRGB(\n\t\t\t\t\t\t\tMath.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,\n\t\t\t\t\t\t\tMath.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,\n\t\t\t\t\t\t\tMath.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,\n\t\t\t\t\t\t\tcolorSpace\n\t\t\t\t\t\t);\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( color = /^\\s*(\\d+)\\%\\s*,\\s*(\\d+)\\%\\s*,\\s*(\\d+)\\%\\s*(?:,\\s*(\\d*\\.?\\d+)\\s*)?$/.exec( components ) ) {\n\n\t\t\t\t\t\t// rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)\n\n\t\t\t\t\t\thandleAlpha( color[ 4 ] );\n\n\t\t\t\t\t\treturn this.setRGB(\n\t\t\t\t\t\t\tMath.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,\n\t\t\t\t\t\t\tMath.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,\n\t\t\t\t\t\t\tMath.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,\n\t\t\t\t\t\t\tcolorSpace\n\t\t\t\t\t\t);\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'hsl':\n\t\t\t\tcase 'hsla':\n\n\t\t\t\t\tif ( color = /^\\s*(\\d*\\.?\\d+)\\s*,\\s*(\\d*\\.?\\d+)\\%\\s*,\\s*(\\d*\\.?\\d+)\\%\\s*(?:,\\s*(\\d*\\.?\\d+)\\s*)?$/.exec( components ) ) {\n\n\t\t\t\t\t\t// hsl(120,50%,50%) hsla(120,50%,50%,0.5)\n\n\t\t\t\t\t\thandleAlpha( color[ 4 ] );\n\n\t\t\t\t\t\treturn this.setHSL(\n\t\t\t\t\t\t\tparseFloat( color[ 1 ] ) / 360,\n\t\t\t\t\t\t\tparseFloat( color[ 2 ] ) / 100,\n\t\t\t\t\t\t\tparseFloat( color[ 3 ] ) / 100,\n\t\t\t\t\t\t\tcolorSpace\n\t\t\t\t\t\t);\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\n\t\t\t\t\tconsole.warn( 'THREE.Color: Unknown color model ' + style );\n\n\t\t\t}\n\n\t\t} else if ( m = /^\\#([A-Fa-f\\d]+)$/.exec( style ) ) {\n\n\t\t\t// hex color\n\n\t\t\tconst hex = m[ 1 ];\n\t\t\tconst size = hex.length;\n\n\t\t\tif ( size === 3 ) {\n\n\t\t\t\t// #ff0\n\t\t\t\treturn this.setRGB(\n\t\t\t\t\tparseInt( hex.charAt( 0 ), 16 ) / 15,\n\t\t\t\t\tparseInt( hex.charAt( 1 ), 16 ) / 15,\n\t\t\t\t\tparseInt( hex.charAt( 2 ), 16 ) / 15,\n\t\t\t\t\tcolorSpace\n\t\t\t\t);\n\n\t\t\t} else if ( size === 6 ) {\n\n\t\t\t\t// #ff0000\n\t\t\t\treturn this.setHex( parseInt( hex, 16 ), colorSpace );\n\n\t\t\t} else {\n\n\t\t\t\tconsole.warn( 'THREE.Color: Invalid hex color ' + style );\n\n\t\t\t}\n\n\t\t} else if ( style && style.length > 0 ) {\n\n\t\t\treturn this.setColorName( style, colorSpace );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tsetColorName( style, colorSpace = SRGBColorSpace ) {\n\n\t\t// color keywords\n\t\tconst hex = _colorKeywords[ style.toLowerCase() ];\n\n\t\tif ( hex !== undefined ) {\n\n\t\t\t// red\n\t\t\tthis.setHex( hex, colorSpace );\n\n\t\t} else {\n\n\t\t\t// unknown color\n\t\t\tconsole.warn( 'THREE.Color: Unknown color ' + style );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor( this.r, this.g, this.b );\n\n\t}\n\n\tcopy( color ) {\n\n\t\tthis.r = color.r;\n\t\tthis.g = color.g;\n\t\tthis.b = color.b;\n\n\t\treturn this;\n\n\t}\n\n\tcopySRGBToLinear( color ) {\n\n\t\tthis.r = SRGBToLinear( color.r );\n\t\tthis.g = SRGBToLinear( color.g );\n\t\tthis.b = SRGBToLinear( color.b );\n\n\t\treturn this;\n\n\t}\n\n\tcopyLinearToSRGB( color ) {\n\n\t\tthis.r = LinearToSRGB( color.r );\n\t\tthis.g = LinearToSRGB( color.g );\n\t\tthis.b = LinearToSRGB( color.b );\n\n\t\treturn this;\n\n\t}\n\n\tconvertSRGBToLinear() {\n\n\t\tthis.copySRGBToLinear( this );\n\n\t\treturn this;\n\n\t}\n\n\tconvertLinearToSRGB() {\n\n\t\tthis.copyLinearToSRGB( this );\n\n\t\treturn this;\n\n\t}\n\n\tgetHex( colorSpace = SRGBColorSpace ) {\n\n\t\tColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );\n\n\t\treturn Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) );\n\n\t}\n\n\tgetHexString( colorSpace = SRGBColorSpace ) {\n\n\t\treturn ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );\n\n\t}\n\n\tgetHSL( target, colorSpace = ColorManagement.workingColorSpace ) {\n\n\t\t// h,s,l ranges are in 0.0 - 1.0\n\n\t\tColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );\n\n\t\tconst r = _color.r, g = _color.g, b = _color.b;\n\n\t\tconst max = Math.max( r, g, b );\n\t\tconst min = Math.min( r, g, b );\n\n\t\tlet hue, saturation;\n\t\tconst lightness = ( min + max ) / 2.0;\n\n\t\tif ( min === max ) {\n\n\t\t\thue = 0;\n\t\t\tsaturation = 0;\n\n\t\t} else {\n\n\t\t\tconst delta = max - min;\n\n\t\t\tsaturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );\n\n\t\t\tswitch ( max ) {\n\n\t\t\t\tcase r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;\n\t\t\t\tcase g: hue = ( b - r ) / delta + 2; break;\n\t\t\t\tcase b: hue = ( r - g ) / delta + 4; break;\n\n\t\t\t}\n\n\t\t\thue /= 6;\n\n\t\t}\n\n\t\ttarget.h = hue;\n\t\ttarget.s = saturation;\n\t\ttarget.l = lightness;\n\n\t\treturn target;\n\n\t}\n\n\tgetRGB( target, colorSpace = ColorManagement.workingColorSpace ) {\n\n\t\tColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );\n\n\t\ttarget.r = _color.r;\n\t\ttarget.g = _color.g;\n\t\ttarget.b = _color.b;\n\n\t\treturn target;\n\n\t}\n\n\tgetStyle( colorSpace = SRGBColorSpace ) {\n\n\t\tColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );\n\n\t\tconst r = _color.r, g = _color.g, b = _color.b;\n\n\t\tif ( colorSpace !== SRGBColorSpace ) {\n\n\t\t\t// Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).\n\t\t\treturn `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;\n\n\t\t}\n\n\t\treturn `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;\n\n\t}\n\n\toffsetHSL( h, s, l ) {\n\n\t\tthis.getHSL( _hslA );\n\n\t\t_hslA.h += h; _hslA.s += s; _hslA.l += l;\n\n\t\tthis.setHSL( _hslA.h, _hslA.s, _hslA.l );\n\n\t\treturn this;\n\n\t}\n\n\tadd( color ) {\n\n\t\tthis.r += color.r;\n\t\tthis.g += color.g;\n\t\tthis.b += color.b;\n\n\t\treturn this;\n\n\t}\n\n\taddColors( color1, color2 ) {\n\n\t\tthis.r = color1.r + color2.r;\n\t\tthis.g = color1.g + color2.g;\n\t\tthis.b = color1.b + color2.b;\n\n\t\treturn this;\n\n\t}\n\n\taddScalar( s ) {\n\n\t\tthis.r += s;\n\t\tthis.g += s;\n\t\tthis.b += s;\n\n\t\treturn this;\n\n\t}\n\n\tsub( color ) {\n\n\t\tthis.r = Math.max( 0, this.r - color.r );\n\t\tthis.g = Math.max( 0, this.g - color.g );\n\t\tthis.b = Math.max( 0, this.b - color.b );\n\n\t\treturn this;\n\n\t}\n\n\tmultiply( color ) {\n\n\t\tthis.r *= color.r;\n\t\tthis.g *= color.g;\n\t\tthis.b *= color.b;\n\n\t\treturn this;\n\n\t}\n\n\tmultiplyScalar( s ) {\n\n\t\tthis.r *= s;\n\t\tthis.g *= s;\n\t\tthis.b *= s;\n\n\t\treturn this;\n\n\t}\n\n\tlerp( color, alpha ) {\n\n\t\tthis.r += ( color.r - this.r ) * alpha;\n\t\tthis.g += ( color.g - this.g ) * alpha;\n\t\tthis.b += ( color.b - this.b ) * alpha;\n\n\t\treturn this;\n\n\t}\n\n\tlerpColors( color1, color2, alpha ) {\n\n\t\tthis.r = color1.r + ( color2.r - color1.r ) * alpha;\n\t\tthis.g = color1.g + ( color2.g - color1.g ) * alpha;\n\t\tthis.b = color1.b + ( color2.b - color1.b ) * alpha;\n\n\t\treturn this;\n\n\t}\n\n\tlerpHSL( color, alpha ) {\n\n\t\tthis.getHSL( _hslA );\n\t\tcolor.getHSL( _hslB );\n\n\t\tconst h = lerp( _hslA.h, _hslB.h, alpha );\n\t\tconst s = lerp( _hslA.s, _hslB.s, alpha );\n\t\tconst l = lerp( _hslA.l, _hslB.l, alpha );\n\n\t\tthis.setHSL( h, s, l );\n\n\t\treturn this;\n\n\t}\n\n\tsetFromVector3( v ) {\n\n\t\tthis.r = v.x;\n\t\tthis.g = v.y;\n\t\tthis.b = v.z;\n\n\t\treturn this;\n\n\t}\n\n\tapplyMatrix3( m ) {\n\n\t\tconst r = this.r, g = this.g, b = this.b;\n\t\tconst e = m.elements;\n\n\t\tthis.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;\n\t\tthis.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;\n\t\tthis.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;\n\n\t\treturn this;\n\n\t}\n\n\tequals( c ) {\n\n\t\treturn ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );\n\n\t}\n\n\tfromArray( array, offset = 0 ) {\n\n\t\tthis.r = array[ offset ];\n\t\tthis.g = array[ offset + 1 ];\n\t\tthis.b = array[ offset + 2 ];\n\n\t\treturn this;\n\n\t}\n\n\ttoArray( array = [], offset = 0 ) {\n\n\t\tarray[ offset ] = this.r;\n\t\tarray[ offset + 1 ] = this.g;\n\t\tarray[ offset + 2 ] = this.b;\n\n\t\treturn array;\n\n\t}\n\n\tfromBufferAttribute( attribute, index ) {\n\n\t\tthis.r = attribute.getX( index );\n\t\tthis.g = attribute.getY( index );\n\t\tthis.b = attribute.getZ( index );\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\treturn this.getHex();\n\n\t}\n\n\t*[ Symbol.iterator ]() {\n\n\t\tyield this.r;\n\t\tyield this.g;\n\t\tyield this.b;\n\n\t}\n\n}\n\nconst _color = /*@__PURE__*/ new Color();\n\nColor.NAMES = _colorKeywords;\n\nclass MeshBasicMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isMeshBasicMaterial = true;\n\n\t\tthis.type = 'MeshBasicMaterial';\n\n\t\tthis.color = new Color( 0xffffff ); // emissive\n\n\t\tthis.map = null;\n\n\t\tthis.lightMap = null;\n\t\tthis.lightMapIntensity = 1.0;\n\n\t\tthis.aoMap = null;\n\t\tthis.aoMapIntensity = 1.0;\n\n\t\tthis.specularMap = null;\n\n\t\tthis.alphaMap = null;\n\n\t\tthis.envMap = null;\n\t\tthis.combine = MultiplyOperation;\n\t\tthis.reflectivity = 1;\n\t\tthis.refractionRatio = 0.98;\n\n\t\tthis.wireframe = false;\n\t\tthis.wireframeLinewidth = 1;\n\t\tthis.wireframeLinecap = 'round';\n\t\tthis.wireframeLinejoin = 'round';\n\n\t\tthis.fog = true;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.color.copy( source.color );\n\n\t\tthis.map = source.map;\n\n\t\tthis.lightMap = source.lightMap;\n\t\tthis.lightMapIntensity = source.lightMapIntensity;\n\n\t\tthis.aoMap = source.aoMap;\n\t\tthis.aoMapIntensity = source.aoMapIntensity;\n\n\t\tthis.specularMap = source.specularMap;\n\n\t\tthis.alphaMap = source.alphaMap;\n\n\t\tthis.envMap = source.envMap;\n\t\tthis.combine = source.combine;\n\t\tthis.reflectivity = source.reflectivity;\n\t\tthis.refractionRatio = source.refractionRatio;\n\n\t\tthis.wireframe = source.wireframe;\n\t\tthis.wireframeLinewidth = source.wireframeLinewidth;\n\t\tthis.wireframeLinecap = source.wireframeLinecap;\n\t\tthis.wireframeLinejoin = source.wireframeLinejoin;\n\n\t\tthis.fog = source.fog;\n\n\t\treturn this;\n\n\t}\n\n}\n\n// Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n\nconst _tables = /*@__PURE__*/ _generateTables();\n\nfunction _generateTables() {\n\n\t// float32 to float16 helpers\n\n\tconst buffer = new ArrayBuffer( 4 );\n\tconst floatView = new Float32Array( buffer );\n\tconst uint32View = new Uint32Array( buffer );\n\n\tconst baseTable = new Uint32Array( 512 );\n\tconst shiftTable = new Uint32Array( 512 );\n\n\tfor ( let i = 0; i < 256; ++ i ) {\n\n\t\tconst e = i - 127;\n\n\t\t// very small number (0, -0)\n\n\t\tif ( e < - 27 ) {\n\n\t\t\tbaseTable[ i ] = 0x0000;\n\t\t\tbaseTable[ i | 0x100 ] = 0x8000;\n\t\t\tshiftTable[ i ] = 24;\n\t\t\tshiftTable[ i | 0x100 ] = 24;\n\n\t\t\t// small number (denorm)\n\n\t\t} else if ( e < - 14 ) {\n\n\t\t\tbaseTable[ i ] = 0x0400 >> ( - e - 14 );\n\t\t\tbaseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;\n\t\t\tshiftTable[ i ] = - e - 1;\n\t\t\tshiftTable[ i | 0x100 ] = - e - 1;\n\n\t\t\t// normal number\n\n\t\t} else if ( e <= 15 ) {\n\n\t\t\tbaseTable[ i ] = ( e + 15 ) << 10;\n\t\t\tbaseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;\n\t\t\tshiftTable[ i ] = 13;\n\t\t\tshiftTable[ i | 0x100 ] = 13;\n\n\t\t\t// large number (Infinity, -Infinity)\n\n\t\t} else if ( e < 128 ) {\n\n\t\t\tbaseTable[ i ] = 0x7c00;\n\t\t\tbaseTable[ i | 0x100 ] = 0xfc00;\n\t\t\tshiftTable[ i ] = 24;\n\t\t\tshiftTable[ i | 0x100 ] = 24;\n\n\t\t\t// stay (NaN, Infinity, -Infinity)\n\n\t\t} else {\n\n\t\t\tbaseTable[ i ] = 0x7c00;\n\t\t\tbaseTable[ i | 0x100 ] = 0xfc00;\n\t\t\tshiftTable[ i ] = 13;\n\t\t\tshiftTable[ i | 0x100 ] = 13;\n\n\t\t}\n\n\t}\n\n\t// float16 to float32 helpers\n\n\tconst mantissaTable = new Uint32Array( 2048 );\n\tconst exponentTable = new Uint32Array( 64 );\n\tconst offsetTable = new Uint32Array( 64 );\n\n\tfor ( let i = 1; i < 1024; ++ i ) {\n\n\t\tlet m = i << 13; // zero pad mantissa bits\n\t\tlet e = 0; // zero exponent\n\n\t\t// normalized\n\t\twhile ( ( m & 0x00800000 ) === 0 ) {\n\n\t\t\tm <<= 1;\n\t\t\te -= 0x00800000; // decrement exponent\n\n\t\t}\n\n\t\tm &= ~ 0x00800000; // clear leading 1 bit\n\t\te += 0x38800000; // adjust bias\n\n\t\tmantissaTable[ i ] = m | e;\n\n\t}\n\n\tfor ( let i = 1024; i < 2048; ++ i ) {\n\n\t\tmantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );\n\n\t}\n\n\tfor ( let i = 1; i < 31; ++ i ) {\n\n\t\texponentTable[ i ] = i << 23;\n\n\t}\n\n\texponentTable[ 31 ] = 0x47800000;\n\texponentTable[ 32 ] = 0x80000000;\n\n\tfor ( let i = 33; i < 63; ++ i ) {\n\n\t\texponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );\n\n\t}\n\n\texponentTable[ 63 ] = 0xc7800000;\n\n\tfor ( let i = 1; i < 64; ++ i ) {\n\n\t\tif ( i !== 32 ) {\n\n\t\t\toffsetTable[ i ] = 1024;\n\n\t\t}\n\n\t}\n\n\treturn {\n\t\tfloatView: floatView,\n\t\tuint32View: uint32View,\n\t\tbaseTable: baseTable,\n\t\tshiftTable: shiftTable,\n\t\tmantissaTable: mantissaTable,\n\t\texponentTable: exponentTable,\n\t\toffsetTable: offsetTable\n\t};\n\n}\n\n// float32 to float16\n\nfunction toHalfFloat( val ) {\n\n\tif ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );\n\n\tval = clamp( val, - 65504, 65504 );\n\n\t_tables.floatView[ 0 ] = val;\n\tconst f = _tables.uint32View[ 0 ];\n\tconst e = ( f >> 23 ) & 0x1ff;\n\treturn _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );\n\n}\n\n// float16 to float32\n\nfunction fromHalfFloat( val ) {\n\n\tconst m = val >> 10;\n\t_tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];\n\treturn _tables.floatView[ 0 ];\n\n}\n\nconst DataUtils = {\n\ttoHalfFloat: toHalfFloat,\n\tfromHalfFloat: fromHalfFloat,\n};\n\nconst _vector$8 = /*@__PURE__*/ new Vector3();\nconst _vector2$1 = /*@__PURE__*/ new Vector2();\n\nclass BufferAttribute {\n\n\tconstructor( array, itemSize, normalized = false ) {\n\n\t\tif ( Array.isArray( array ) ) {\n\n\t\t\tthrow new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );\n\n\t\t}\n\n\t\tthis.isBufferAttribute = true;\n\n\t\tthis.name = '';\n\n\t\tthis.array = array;\n\t\tthis.itemSize = itemSize;\n\t\tthis.count = array !== undefined ? array.length / itemSize : 0;\n\t\tthis.normalized = normalized;\n\n\t\tthis.usage = StaticDrawUsage;\n\t\tthis.updateRange = { offset: 0, count: - 1 };\n\n\t\tthis.version = 0;\n\n\t}\n\n\tonUploadCallback() {}\n\n\tset needsUpdate( value ) {\n\n\t\tif ( value === true ) this.version ++;\n\n\t}\n\n\tsetUsage( value ) {\n\n\t\tthis.usage = value;\n\n\t\treturn this;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tthis.name = source.name;\n\t\tthis.array = new source.array.constructor( source.array );\n\t\tthis.itemSize = source.itemSize;\n\t\tthis.count = source.count;\n\t\tthis.normalized = source.normalized;\n\n\t\tthis.usage = source.usage;\n\n\t\treturn this;\n\n\t}\n\n\tcopyAt( index1, attribute, index2 ) {\n\n\t\tindex1 *= this.itemSize;\n\t\tindex2 *= attribute.itemSize;\n\n\t\tfor ( let i = 0, l = this.itemSize; i < l; i ++ ) {\n\n\t\t\tthis.array[ index1 + i ] = attribute.array[ index2 + i ];\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tcopyArray( array ) {\n\n\t\tthis.array.set( array );\n\n\t\treturn this;\n\n\t}\n\n\tapplyMatrix3( m ) {\n\n\t\tif ( this.itemSize === 2 ) {\n\n\t\t\tfor ( let i = 0, l = this.count; i < l; i ++ ) {\n\n\t\t\t\t_vector2$1.fromBufferAttribute( this, i );\n\t\t\t\t_vector2$1.applyMatrix3( m );\n\n\t\t\t\tthis.setXY( i, _vector2$1.x, _vector2$1.y );\n\n\t\t\t}\n\n\t\t} else if ( this.itemSize === 3 ) {\n\n\t\t\tfor ( let i = 0, l = this.count; i < l; i ++ ) {\n\n\t\t\t\t_vector$8.fromBufferAttribute( this, i );\n\t\t\t\t_vector$8.applyMatrix3( m );\n\n\t\t\t\tthis.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tapplyMatrix4( m ) {\n\n\t\tfor ( let i = 0, l = this.count; i < l; i ++ ) {\n\n\t\t\t_vector$8.fromBufferAttribute( this, i );\n\n\t\t\t_vector$8.applyMatrix4( m );\n\n\t\t\tthis.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tapplyNormalMatrix( m ) {\n\n\t\tfor ( let i = 0, l = this.count; i < l; i ++ ) {\n\n\t\t\t_vector$8.fromBufferAttribute( this, i );\n\n\t\t\t_vector$8.applyNormalMatrix( m );\n\n\t\t\tthis.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\ttransformDirection( m ) {\n\n\t\tfor ( let i = 0, l = this.count; i < l; i ++ ) {\n\n\t\t\t_vector$8.fromBufferAttribute( this, i );\n\n\t\t\t_vector$8.transformDirection( m );\n\n\t\t\tthis.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tset( value, offset = 0 ) {\n\n\t\t// Matching BufferAttribute constructor, do not normalize the array.\n\t\tthis.array.set( value, offset );\n\n\t\treturn this;\n\n\t}\n\n\tgetX( index ) {\n\n\t\tlet x = this.array[ index * this.itemSize ];\n\n\t\tif ( this.normalized ) x = denormalize( x, this.array );\n\n\t\treturn x;\n\n\t}\n\n\tsetX( index, x ) {\n\n\t\tif ( this.normalized ) x = normalize( x, this.array );\n\n\t\tthis.array[ index * this.itemSize ] = x;\n\n\t\treturn this;\n\n\t}\n\n\tgetY( index ) {\n\n\t\tlet y = this.array[ index * this.itemSize + 1 ];\n\n\t\tif ( this.normalized ) y = denormalize( y, this.array );\n\n\t\treturn y;\n\n\t}\n\n\tsetY( index, y ) {\n\n\t\tif ( this.normalized ) y = normalize( y, this.array );\n\n\t\tthis.array[ index * this.itemSize + 1 ] = y;\n\n\t\treturn this;\n\n\t}\n\n\tgetZ( index ) {\n\n\t\tlet z = this.array[ index * this.itemSize + 2 ];\n\n\t\tif ( this.normalized ) z = denormalize( z, this.array );\n\n\t\treturn z;\n\n\t}\n\n\tsetZ( index, z ) {\n\n\t\tif ( this.normalized ) z = normalize( z, this.array );\n\n\t\tthis.array[ index * this.itemSize + 2 ] = z;\n\n\t\treturn this;\n\n\t}\n\n\tgetW( index ) {\n\n\t\tlet w = this.array[ index * this.itemSize + 3 ];\n\n\t\tif ( this.normalized ) w = denormalize( w, this.array );\n\n\t\treturn w;\n\n\t}\n\n\tsetW( index, w ) {\n\n\t\tif ( this.normalized ) w = normalize( w, this.array );\n\n\t\tthis.array[ index * this.itemSize + 3 ] = w;\n\n\t\treturn this;\n\n\t}\n\n\tsetXY( index, x, y ) {\n\n\t\tindex *= this.itemSize;\n\n\t\tif ( this.normalized ) {\n\n\t\t\tx = normalize( x, this.array );\n\t\t\ty = normalize( y, this.array );\n\n\t\t}\n\n\t\tthis.array[ index + 0 ] = x;\n\t\tthis.array[ index + 1 ] = y;\n\n\t\treturn this;\n\n\t}\n\n\tsetXYZ( index, x, y, z ) {\n\n\t\tindex *= this.itemSize;\n\n\t\tif ( this.normalized ) {\n\n\t\t\tx = normalize( x, this.array );\n\t\t\ty = normalize( y, this.array );\n\t\t\tz = normalize( z, this.array );\n\n\t\t}\n\n\t\tthis.array[ index + 0 ] = x;\n\t\tthis.array[ index + 1 ] = y;\n\t\tthis.array[ index + 2 ] = z;\n\n\t\treturn this;\n\n\t}\n\n\tsetXYZW( index, x, y, z, w ) {\n\n\t\tindex *= this.itemSize;\n\n\t\tif ( this.normalized ) {\n\n\t\t\tx = normalize( x, this.array );\n\t\t\ty = normalize( y, this.array );\n\t\t\tz = normalize( z, this.array );\n\t\t\tw = normalize( w, this.array );\n\n\t\t}\n\n\t\tthis.array[ index + 0 ] = x;\n\t\tthis.array[ index + 1 ] = y;\n\t\tthis.array[ index + 2 ] = z;\n\t\tthis.array[ index + 3 ] = w;\n\n\t\treturn this;\n\n\t}\n\n\tonUpload( callback ) {\n\n\t\tthis.onUploadCallback = callback;\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor( this.array, this.itemSize ).copy( this );\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = {\n\t\t\titemSize: this.itemSize,\n\t\t\ttype: this.array.constructor.name,\n\t\t\tarray: Array.from( this.array ),\n\t\t\tnormalized: this.normalized\n\t\t};\n\n\t\tif ( this.name !== '' ) data.name = this.name;\n\t\tif ( this.usage !== StaticDrawUsage ) data.usage = this.usage;\n\t\tif ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;\n\n\t\treturn data;\n\n\t}\n\n\tcopyColorsArray() { // @deprecated, r144\n\n\t\tconsole.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );\n\n\t}\n\n\tcopyVector2sArray() { // @deprecated, r144\n\n\t\tconsole.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );\n\n\t}\n\n\tcopyVector3sArray() { // @deprecated, r144\n\n\t\tconsole.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );\n\n\t}\n\n\tcopyVector4sArray() { // @deprecated, r144\n\n\t\tconsole.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );\n\n\t}\n\n}\n\n//\n\nclass Int8BufferAttribute extends BufferAttribute {\n\n\tconstructor( array, itemSize, normalized ) {\n\n\t\tsuper( new Int8Array( array ), itemSize, normalized );\n\n\t}\n\n}\n\nclass Uint8BufferAttribute extends BufferAttribute {\n\n\tconstructor( array, itemSize, normalized ) {\n\n\t\tsuper( new Uint8Array( array ), itemSize, normalized );\n\n\t}\n\n}\n\nclass Uint8ClampedBufferAttribute extends BufferAttribute {\n\n\tconstructor( array, itemSize, normalized ) {\n\n\t\tsuper( new Uint8ClampedArray( array ), itemSize, normalized );\n\n\t}\n\n}\n\nclass Int16BufferAttribute extends BufferAttribute {\n\n\tconstructor( array, itemSize, normalized ) {\n\n\t\tsuper( new Int16Array( array ), itemSize, normalized );\n\n\t}\n\n}\n\nclass Uint16BufferAttribute extends BufferAttribute {\n\n\tconstructor( array, itemSize, normalized ) {\n\n\t\tsuper( new Uint16Array( array ), itemSize, normalized );\n\n\t}\n\n}\n\nclass Int32BufferAttribute extends BufferAttribute {\n\n\tconstructor( array, itemSize, normalized ) {\n\n\t\tsuper( new Int32Array( array ), itemSize, normalized );\n\n\t}\n\n}\n\nclass Uint32BufferAttribute extends BufferAttribute {\n\n\tconstructor( array, itemSize, normalized ) {\n\n\t\tsuper( new Uint32Array( array ), itemSize, normalized );\n\n\t}\n\n}\n\nclass Float16BufferAttribute extends BufferAttribute {\n\n\tconstructor( array, itemSize, normalized ) {\n\n\t\tsuper( new Uint16Array( array ), itemSize, normalized );\n\n\t\tthis.isFloat16BufferAttribute = true;\n\n\t}\n\n\tgetX( index ) {\n\n\t\tlet x = fromHalfFloat( this.array[ index * this.itemSize ] );\n\n\t\tif ( this.normalized ) x = denormalize( x, this.array );\n\n\t\treturn x;\n\n\t}\n\n\tsetX( index, x ) {\n\n\t\tif ( this.normalized ) x = normalize( x, this.array );\n\n\t\tthis.array[ index * this.itemSize ] = toHalfFloat( x );\n\n\t\treturn this;\n\n\t}\n\n\tgetY( index ) {\n\n\t\tlet y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );\n\n\t\tif ( this.normalized ) y = denormalize( y, this.array );\n\n\t\treturn y;\n\n\t}\n\n\tsetY( index, y ) {\n\n\t\tif ( this.normalized ) y = normalize( y, this.array );\n\n\t\tthis.array[ index * this.itemSize + 1 ] = toHalfFloat( y );\n\n\t\treturn this;\n\n\t}\n\n\tgetZ( index ) {\n\n\t\tlet z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );\n\n\t\tif ( this.normalized ) z = denormalize( z, this.array );\n\n\t\treturn z;\n\n\t}\n\n\tsetZ( index, z ) {\n\n\t\tif ( this.normalized ) z = normalize( z, this.array );\n\n\t\tthis.array[ index * this.itemSize + 2 ] = toHalfFloat( z );\n\n\t\treturn this;\n\n\t}\n\n\tgetW( index ) {\n\n\t\tlet w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );\n\n\t\tif ( this.normalized ) w = denormalize( w, this.array );\n\n\t\treturn w;\n\n\t}\n\n\tsetW( index, w ) {\n\n\t\tif ( this.normalized ) w = normalize( w, this.array );\n\n\t\tthis.array[ index * this.itemSize + 3 ] = toHalfFloat( w );\n\n\t\treturn this;\n\n\t}\n\n\tsetXY( index, x, y ) {\n\n\t\tindex *= this.itemSize;\n\n\t\tif ( this.normalized ) {\n\n\t\t\tx = normalize( x, this.array );\n\t\t\ty = normalize( y, this.array );\n\n\t\t}\n\n\t\tthis.array[ index + 0 ] = toHalfFloat( x );\n\t\tthis.array[ index + 1 ] = toHalfFloat( y );\n\n\t\treturn this;\n\n\t}\n\n\tsetXYZ( index, x, y, z ) {\n\n\t\tindex *= this.itemSize;\n\n\t\tif ( this.normalized ) {\n\n\t\t\tx = normalize( x, this.array );\n\t\t\ty = normalize( y, this.array );\n\t\t\tz = normalize( z, this.array );\n\n\t\t}\n\n\t\tthis.array[ index + 0 ] = toHalfFloat( x );\n\t\tthis.array[ index + 1 ] = toHalfFloat( y );\n\t\tthis.array[ index + 2 ] = toHalfFloat( z );\n\n\t\treturn this;\n\n\t}\n\n\tsetXYZW( index, x, y, z, w ) {\n\n\t\tindex *= this.itemSize;\n\n\t\tif ( this.normalized ) {\n\n\t\t\tx = normalize( x, this.array );\n\t\t\ty = normalize( y, this.array );\n\t\t\tz = normalize( z, this.array );\n\t\t\tw = normalize( w, this.array );\n\n\t\t}\n\n\t\tthis.array[ index + 0 ] = toHalfFloat( x );\n\t\tthis.array[ index + 1 ] = toHalfFloat( y );\n\t\tthis.array[ index + 2 ] = toHalfFloat( z );\n\t\tthis.array[ index + 3 ] = toHalfFloat( w );\n\n\t\treturn this;\n\n\t}\n\n}\n\n\nclass Float32BufferAttribute extends BufferAttribute {\n\n\tconstructor( array, itemSize, normalized ) {\n\n\t\tsuper( new Float32Array( array ), itemSize, normalized );\n\n\t}\n\n}\n\nclass Float64BufferAttribute extends BufferAttribute {\n\n\tconstructor( array, itemSize, normalized ) {\n\n\t\tsuper( new Float64Array( array ), itemSize, normalized );\n\n\t}\n\n}\n\nlet _id$1 = 0;\n\nconst _m1 = /*@__PURE__*/ new Matrix4();\nconst _obj = /*@__PURE__*/ new Object3D();\nconst _offset = /*@__PURE__*/ new Vector3();\nconst _box$1 = /*@__PURE__*/ new Box3();\nconst _boxMorphTargets = /*@__PURE__*/ new Box3();\nconst _vector$7 = /*@__PURE__*/ new Vector3();\n\nclass BufferGeometry extends EventDispatcher {\n\n\tconstructor() {\n\n\t\tsuper();\n\n\t\tthis.isBufferGeometry = true;\n\n\t\tObject.defineProperty( this, 'id', { value: _id$1 ++ } );\n\n\t\tthis.uuid = generateUUID();\n\n\t\tthis.name = '';\n\t\tthis.type = 'BufferGeometry';\n\n\t\tthis.index = null;\n\t\tthis.attributes = {};\n\n\t\tthis.morphAttributes = {};\n\t\tthis.morphTargetsRelative = false;\n\n\t\tthis.groups = [];\n\n\t\tthis.boundingBox = null;\n\t\tthis.boundingSphere = null;\n\n\t\tthis.drawRange = { start: 0, count: Infinity };\n\n\t\tthis.userData = {};\n\n\t}\n\n\tgetIndex() {\n\n\t\treturn this.index;\n\n\t}\n\n\tsetIndex( index ) {\n\n\t\tif ( Array.isArray( index ) ) {\n\n\t\t\tthis.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );\n\n\t\t} else {\n\n\t\t\tthis.index = index;\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tgetAttribute( name ) {\n\n\t\treturn this.attributes[ name ];\n\n\t}\n\n\tsetAttribute( name, attribute ) {\n\n\t\tthis.attributes[ name ] = attribute;\n\n\t\treturn this;\n\n\t}\n\n\tdeleteAttribute( name ) {\n\n\t\tdelete this.attributes[ name ];\n\n\t\treturn this;\n\n\t}\n\n\thasAttribute( name ) {\n\n\t\treturn this.attributes[ name ] !== undefined;\n\n\t}\n\n\taddGroup( start, count, materialIndex = 0 ) {\n\n\t\tthis.groups.push( {\n\n\t\t\tstart: start,\n\t\t\tcount: count,\n\t\t\tmaterialIndex: materialIndex\n\n\t\t} );\n\n\t}\n\n\tclearGroups() {\n\n\t\tthis.groups = [];\n\n\t}\n\n\tsetDrawRange( start, count ) {\n\n\t\tthis.drawRange.start = start;\n\t\tthis.drawRange.count = count;\n\n\t}\n\n\tapplyMatrix4( matrix ) {\n\n\t\tconst position = this.attributes.position;\n\n\t\tif ( position !== undefined ) {\n\n\t\t\tposition.applyMatrix4( matrix );\n\n\t\t\tposition.needsUpdate = true;\n\n\t\t}\n\n\t\tconst normal = this.attributes.normal;\n\n\t\tif ( normal !== undefined ) {\n\n\t\t\tconst normalMatrix = new Matrix3().getNormalMatrix( matrix );\n\n\t\t\tnormal.applyNormalMatrix( normalMatrix );\n\n\t\t\tnormal.needsUpdate = true;\n\n\t\t}\n\n\t\tconst tangent = this.attributes.tangent;\n\n\t\tif ( tangent !== undefined ) {\n\n\t\t\ttangent.transformDirection( matrix );\n\n\t\t\ttangent.needsUpdate = true;\n\n\t\t}\n\n\t\tif ( this.boundingBox !== null ) {\n\n\t\t\tthis.computeBoundingBox();\n\n\t\t}\n\n\t\tif ( this.boundingSphere !== null ) {\n\n\t\t\tthis.computeBoundingSphere();\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tapplyQuaternion( q ) {\n\n\t\t_m1.makeRotationFromQuaternion( q );\n\n\t\tthis.applyMatrix4( _m1 );\n\n\t\treturn this;\n\n\t}\n\n\trotateX( angle ) {\n\n\t\t// rotate geometry around world x-axis\n\n\t\t_m1.makeRotationX( angle );\n\n\t\tthis.applyMatrix4( _m1 );\n\n\t\treturn this;\n\n\t}\n\n\trotateY( angle ) {\n\n\t\t// rotate geometry around world y-axis\n\n\t\t_m1.makeRotationY( angle );\n\n\t\tthis.applyMatrix4( _m1 );\n\n\t\treturn this;\n\n\t}\n\n\trotateZ( angle ) {\n\n\t\t// rotate geometry around world z-axis\n\n\t\t_m1.makeRotationZ( angle );\n\n\t\tthis.applyMatrix4( _m1 );\n\n\t\treturn this;\n\n\t}\n\n\ttranslate( x, y, z ) {\n\n\t\t// translate geometry\n\n\t\t_m1.makeTranslation( x, y, z );\n\n\t\tthis.applyMatrix4( _m1 );\n\n\t\treturn this;\n\n\t}\n\n\tscale( x, y, z ) {\n\n\t\t// scale geometry\n\n\t\t_m1.makeScale( x, y, z );\n\n\t\tthis.applyMatrix4( _m1 );\n\n\t\treturn this;\n\n\t}\n\n\tlookAt( vector ) {\n\n\t\t_obj.lookAt( vector );\n\n\t\t_obj.updateMatrix();\n\n\t\tthis.applyMatrix4( _obj.matrix );\n\n\t\treturn this;\n\n\t}\n\n\tcenter() {\n\n\t\tthis.computeBoundingBox();\n\n\t\tthis.boundingBox.getCenter( _offset ).negate();\n\n\t\tthis.translate( _offset.x, _offset.y, _offset.z );\n\n\t\treturn this;\n\n\t}\n\n\tsetFromPoints( points ) {\n\n\t\tconst position = [];\n\n\t\tfor ( let i = 0, l = points.length; i < l; i ++ ) {\n\n\t\t\tconst point = points[ i ];\n\t\t\tposition.push( point.x, point.y, point.z || 0 );\n\n\t\t}\n\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );\n\n\t\treturn this;\n\n\t}\n\n\tcomputeBoundingBox() {\n\n\t\tif ( this.boundingBox === null ) {\n\n\t\t\tthis.boundingBox = new Box3();\n\n\t\t}\n\n\t\tconst position = this.attributes.position;\n\t\tconst morphAttributesPosition = this.morphAttributes.position;\n\n\t\tif ( position && position.isGLBufferAttribute ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set \"mesh.frustumCulled\" to \"false\".', this );\n\n\t\t\tthis.boundingBox.set(\n\t\t\t\tnew Vector3( - Infinity, - Infinity, - Infinity ),\n\t\t\t\tnew Vector3( + Infinity, + Infinity, + Infinity )\n\t\t\t);\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tif ( position !== undefined ) {\n\n\t\t\tthis.boundingBox.setFromBufferAttribute( position );\n\n\t\t\t// process morph attributes if present\n\n\t\t\tif ( morphAttributesPosition ) {\n\n\t\t\t\tfor ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {\n\n\t\t\t\t\tconst morphAttribute = morphAttributesPosition[ i ];\n\t\t\t\t\t_box$1.setFromBufferAttribute( morphAttribute );\n\n\t\t\t\t\tif ( this.morphTargetsRelative ) {\n\n\t\t\t\t\t\t_vector$7.addVectors( this.boundingBox.min, _box$1.min );\n\t\t\t\t\t\tthis.boundingBox.expandByPoint( _vector$7 );\n\n\t\t\t\t\t\t_vector$7.addVectors( this.boundingBox.max, _box$1.max );\n\t\t\t\t\t\tthis.boundingBox.expandByPoint( _vector$7 );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tthis.boundingBox.expandByPoint( _box$1.min );\n\t\t\t\t\t\tthis.boundingBox.expandByPoint( _box$1.max );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tthis.boundingBox.makeEmpty();\n\n\t\t}\n\n\t\tif ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The \"position\" attribute is likely to have NaN values.', this );\n\n\t\t}\n\n\t}\n\n\tcomputeBoundingSphere() {\n\n\t\tif ( this.boundingSphere === null ) {\n\n\t\t\tthis.boundingSphere = new Sphere();\n\n\t\t}\n\n\t\tconst position = this.attributes.position;\n\t\tconst morphAttributesPosition = this.morphAttributes.position;\n\n\t\tif ( position && position.isGLBufferAttribute ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set \"mesh.frustumCulled\" to \"false\".', this );\n\n\t\t\tthis.boundingSphere.set( new Vector3(), Infinity );\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tif ( position ) {\n\n\t\t\t// first, find the center of the bounding sphere\n\n\t\t\tconst center = this.boundingSphere.center;\n\n\t\t\t_box$1.setFromBufferAttribute( position );\n\n\t\t\t// process morph attributes if present\n\n\t\t\tif ( morphAttributesPosition ) {\n\n\t\t\t\tfor ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {\n\n\t\t\t\t\tconst morphAttribute = morphAttributesPosition[ i ];\n\t\t\t\t\t_boxMorphTargets.setFromBufferAttribute( morphAttribute );\n\n\t\t\t\t\tif ( this.morphTargetsRelative ) {\n\n\t\t\t\t\t\t_vector$7.addVectors( _box$1.min, _boxMorphTargets.min );\n\t\t\t\t\t\t_box$1.expandByPoint( _vector$7 );\n\n\t\t\t\t\t\t_vector$7.addVectors( _box$1.max, _boxMorphTargets.max );\n\t\t\t\t\t\t_box$1.expandByPoint( _vector$7 );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t_box$1.expandByPoint( _boxMorphTargets.min );\n\t\t\t\t\t\t_box$1.expandByPoint( _boxMorphTargets.max );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t_box$1.getCenter( center );\n\n\t\t\t// second, try to find a boundingSphere with a radius smaller than the\n\t\t\t// boundingSphere of the boundingBox: sqrt(3) smaller in the best case\n\n\t\t\tlet maxRadiusSq = 0;\n\n\t\t\tfor ( let i = 0, il = position.count; i < il; i ++ ) {\n\n\t\t\t\t_vector$7.fromBufferAttribute( position, i );\n\n\t\t\t\tmaxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );\n\n\t\t\t}\n\n\t\t\t// process morph attributes if present\n\n\t\t\tif ( morphAttributesPosition ) {\n\n\t\t\t\tfor ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {\n\n\t\t\t\t\tconst morphAttribute = morphAttributesPosition[ i ];\n\t\t\t\t\tconst morphTargetsRelative = this.morphTargetsRelative;\n\n\t\t\t\t\tfor ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {\n\n\t\t\t\t\t\t_vector$7.fromBufferAttribute( morphAttribute, j );\n\n\t\t\t\t\t\tif ( morphTargetsRelative ) {\n\n\t\t\t\t\t\t\t_offset.fromBufferAttribute( position, j );\n\t\t\t\t\t\t\t_vector$7.add( _offset );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tmaxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tthis.boundingSphere.radius = Math.sqrt( maxRadiusSq );\n\n\t\t\tif ( isNaN( this.boundingSphere.radius ) ) {\n\n\t\t\t\tconsole.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The \"position\" attribute is likely to have NaN values.', this );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tcomputeTangents() {\n\n\t\tconst index = this.index;\n\t\tconst attributes = this.attributes;\n\n\t\t// based on http://www.terathon.com/code/tangent.html\n\t\t// (per vertex tangents)\n\n\t\tif ( index === null ||\n\t\t\t attributes.position === undefined ||\n\t\t\t attributes.normal === undefined ||\n\t\t\t attributes.uv === undefined ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );\n\t\t\treturn;\n\n\t\t}\n\n\t\tconst indices = index.array;\n\t\tconst positions = attributes.position.array;\n\t\tconst normals = attributes.normal.array;\n\t\tconst uvs = attributes.uv.array;\n\n\t\tconst nVertices = positions.length / 3;\n\n\t\tif ( this.hasAttribute( 'tangent' ) === false ) {\n\n\t\t\tthis.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );\n\n\t\t}\n\n\t\tconst tangents = this.getAttribute( 'tangent' ).array;\n\n\t\tconst tan1 = [], tan2 = [];\n\n\t\tfor ( let i = 0; i < nVertices; i ++ ) {\n\n\t\t\ttan1[ i ] = new Vector3();\n\t\t\ttan2[ i ] = new Vector3();\n\n\t\t}\n\n\t\tconst vA = new Vector3(),\n\t\t\tvB = new Vector3(),\n\t\t\tvC = new Vector3(),\n\n\t\t\tuvA = new Vector2(),\n\t\t\tuvB = new Vector2(),\n\t\t\tuvC = new Vector2(),\n\n\t\t\tsdir = new Vector3(),\n\t\t\ttdir = new Vector3();\n\n\t\tfunction handleTriangle( a, b, c ) {\n\n\t\t\tvA.fromArray( positions, a * 3 );\n\t\t\tvB.fromArray( positions, b * 3 );\n\t\t\tvC.fromArray( positions, c * 3 );\n\n\t\t\tuvA.fromArray( uvs, a * 2 );\n\t\t\tuvB.fromArray( uvs, b * 2 );\n\t\t\tuvC.fromArray( uvs, c * 2 );\n\n\t\t\tvB.sub( vA );\n\t\t\tvC.sub( vA );\n\n\t\t\tuvB.sub( uvA );\n\t\t\tuvC.sub( uvA );\n\n\t\t\tconst r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );\n\n\t\t\t// silently ignore degenerate uv triangles having coincident or colinear vertices\n\n\t\t\tif ( ! isFinite( r ) ) return;\n\n\t\t\tsdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );\n\t\t\ttdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );\n\n\t\t\ttan1[ a ].add( sdir );\n\t\t\ttan1[ b ].add( sdir );\n\t\t\ttan1[ c ].add( sdir );\n\n\t\t\ttan2[ a ].add( tdir );\n\t\t\ttan2[ b ].add( tdir );\n\t\t\ttan2[ c ].add( tdir );\n\n\t\t}\n\n\t\tlet groups = this.groups;\n\n\t\tif ( groups.length === 0 ) {\n\n\t\t\tgroups = [ {\n\t\t\t\tstart: 0,\n\t\t\t\tcount: indices.length\n\t\t\t} ];\n\n\t\t}\n\n\t\tfor ( let i = 0, il = groups.length; i < il; ++ i ) {\n\n\t\t\tconst group = groups[ i ];\n\n\t\t\tconst start = group.start;\n\t\t\tconst count = group.count;\n\n\t\t\tfor ( let j = start, jl = start + count; j < jl; j += 3 ) {\n\n\t\t\t\thandleTriangle(\n\t\t\t\t\tindices[ j + 0 ],\n\t\t\t\t\tindices[ j + 1 ],\n\t\t\t\t\tindices[ j + 2 ]\n\t\t\t\t);\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst tmp = new Vector3(), tmp2 = new Vector3();\n\t\tconst n = new Vector3(), n2 = new Vector3();\n\n\t\tfunction handleVertex( v ) {\n\n\t\t\tn.fromArray( normals, v * 3 );\n\t\t\tn2.copy( n );\n\n\t\t\tconst t = tan1[ v ];\n\n\t\t\t// Gram-Schmidt orthogonalize\n\n\t\t\ttmp.copy( t );\n\t\t\ttmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();\n\n\t\t\t// Calculate handedness\n\n\t\t\ttmp2.crossVectors( n2, t );\n\t\t\tconst test = tmp2.dot( tan2[ v ] );\n\t\t\tconst w = ( test < 0.0 ) ? - 1.0 : 1.0;\n\n\t\t\ttangents[ v * 4 ] = tmp.x;\n\t\t\ttangents[ v * 4 + 1 ] = tmp.y;\n\t\t\ttangents[ v * 4 + 2 ] = tmp.z;\n\t\t\ttangents[ v * 4 + 3 ] = w;\n\n\t\t}\n\n\t\tfor ( let i = 0, il = groups.length; i < il; ++ i ) {\n\n\t\t\tconst group = groups[ i ];\n\n\t\t\tconst start = group.start;\n\t\t\tconst count = group.count;\n\n\t\t\tfor ( let j = start, jl = start + count; j < jl; j += 3 ) {\n\n\t\t\t\thandleVertex( indices[ j + 0 ] );\n\t\t\t\thandleVertex( indices[ j + 1 ] );\n\t\t\t\thandleVertex( indices[ j + 2 ] );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tcomputeVertexNormals() {\n\n\t\tconst index = this.index;\n\t\tconst positionAttribute = this.getAttribute( 'position' );\n\n\t\tif ( positionAttribute !== undefined ) {\n\n\t\t\tlet normalAttribute = this.getAttribute( 'normal' );\n\n\t\t\tif ( normalAttribute === undefined ) {\n\n\t\t\t\tnormalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );\n\t\t\t\tthis.setAttribute( 'normal', normalAttribute );\n\n\t\t\t} else {\n\n\t\t\t\t// reset existing normals to zero\n\n\t\t\t\tfor ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {\n\n\t\t\t\t\tnormalAttribute.setXYZ( i, 0, 0, 0 );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tconst pA = new Vector3(), pB = new Vector3(), pC = new Vector3();\n\t\t\tconst nA = new Vector3(), nB = new Vector3(), nC = new Vector3();\n\t\t\tconst cb = new Vector3(), ab = new Vector3();\n\n\t\t\t// indexed elements\n\n\t\t\tif ( index ) {\n\n\t\t\t\tfor ( let i = 0, il = index.count; i < il; i += 3 ) {\n\n\t\t\t\t\tconst vA = index.getX( i + 0 );\n\t\t\t\t\tconst vB = index.getX( i + 1 );\n\t\t\t\t\tconst vC = index.getX( i + 2 );\n\n\t\t\t\t\tpA.fromBufferAttribute( positionAttribute, vA );\n\t\t\t\t\tpB.fromBufferAttribute( positionAttribute, vB );\n\t\t\t\t\tpC.fromBufferAttribute( positionAttribute, vC );\n\n\t\t\t\t\tcb.subVectors( pC, pB );\n\t\t\t\t\tab.subVectors( pA, pB );\n\t\t\t\t\tcb.cross( ab );\n\n\t\t\t\t\tnA.fromBufferAttribute( normalAttribute, vA );\n\t\t\t\t\tnB.fromBufferAttribute( normalAttribute, vB );\n\t\t\t\t\tnC.fromBufferAttribute( normalAttribute, vC );\n\n\t\t\t\t\tnA.add( cb );\n\t\t\t\t\tnB.add( cb );\n\t\t\t\t\tnC.add( cb );\n\n\t\t\t\t\tnormalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );\n\t\t\t\t\tnormalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );\n\t\t\t\t\tnormalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\t// non-indexed elements (unconnected triangle soup)\n\n\t\t\t\tfor ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {\n\n\t\t\t\t\tpA.fromBufferAttribute( positionAttribute, i + 0 );\n\t\t\t\t\tpB.fromBufferAttribute( positionAttribute, i + 1 );\n\t\t\t\t\tpC.fromBufferAttribute( positionAttribute, i + 2 );\n\n\t\t\t\t\tcb.subVectors( pC, pB );\n\t\t\t\t\tab.subVectors( pA, pB );\n\t\t\t\t\tcb.cross( ab );\n\n\t\t\t\t\tnormalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );\n\t\t\t\t\tnormalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );\n\t\t\t\t\tnormalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tthis.normalizeNormals();\n\n\t\t\tnormalAttribute.needsUpdate = true;\n\n\t\t}\n\n\t}\n\n\tmerge() { // @deprecated, r144\n\n\t\tconsole.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeGeometries() instead.' );\n\t\treturn this;\n\n\t}\n\n\tnormalizeNormals() {\n\n\t\tconst normals = this.attributes.normal;\n\n\t\tfor ( let i = 0, il = normals.count; i < il; i ++ ) {\n\n\t\t\t_vector$7.fromBufferAttribute( normals, i );\n\n\t\t\t_vector$7.normalize();\n\n\t\t\tnormals.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );\n\n\t\t}\n\n\t}\n\n\ttoNonIndexed() {\n\n\t\tfunction convertBufferAttribute( attribute, indices ) {\n\n\t\t\tconst array = attribute.array;\n\t\t\tconst itemSize = attribute.itemSize;\n\t\t\tconst normalized = attribute.normalized;\n\n\t\t\tconst array2 = new array.constructor( indices.length * itemSize );\n\n\t\t\tlet index = 0, index2 = 0;\n\n\t\t\tfor ( let i = 0, l = indices.length; i < l; i ++ ) {\n\n\t\t\t\tif ( attribute.isInterleavedBufferAttribute ) {\n\n\t\t\t\t\tindex = indices[ i ] * attribute.data.stride + attribute.offset;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tindex = indices[ i ] * itemSize;\n\n\t\t\t\t}\n\n\t\t\t\tfor ( let j = 0; j < itemSize; j ++ ) {\n\n\t\t\t\t\tarray2[ index2 ++ ] = array[ index ++ ];\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn new BufferAttribute( array2, itemSize, normalized );\n\n\t\t}\n\n\t\t//\n\n\t\tif ( this.index === null ) {\n\n\t\t\tconsole.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );\n\t\t\treturn this;\n\n\t\t}\n\n\t\tconst geometry2 = new BufferGeometry();\n\n\t\tconst indices = this.index.array;\n\t\tconst attributes = this.attributes;\n\n\t\t// attributes\n\n\t\tfor ( const name in attributes ) {\n\n\t\t\tconst attribute = attributes[ name ];\n\n\t\t\tconst newAttribute = convertBufferAttribute( attribute, indices );\n\n\t\t\tgeometry2.setAttribute( name, newAttribute );\n\n\t\t}\n\n\t\t// morph attributes\n\n\t\tconst morphAttributes = this.morphAttributes;\n\n\t\tfor ( const name in morphAttributes ) {\n\n\t\t\tconst morphArray = [];\n\t\t\tconst morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes\n\n\t\t\tfor ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {\n\n\t\t\t\tconst attribute = morphAttribute[ i ];\n\n\t\t\t\tconst newAttribute = convertBufferAttribute( attribute, indices );\n\n\t\t\t\tmorphArray.push( newAttribute );\n\n\t\t\t}\n\n\t\t\tgeometry2.morphAttributes[ name ] = morphArray;\n\n\t\t}\n\n\t\tgeometry2.morphTargetsRelative = this.morphTargetsRelative;\n\n\t\t// groups\n\n\t\tconst groups = this.groups;\n\n\t\tfor ( let i = 0, l = groups.length; i < l; i ++ ) {\n\n\t\t\tconst group = groups[ i ];\n\t\t\tgeometry2.addGroup( group.start, group.count, group.materialIndex );\n\n\t\t}\n\n\t\treturn geometry2;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = {\n\t\t\tmetadata: {\n\t\t\t\tversion: 4.5,\n\t\t\t\ttype: 'BufferGeometry',\n\t\t\t\tgenerator: 'BufferGeometry.toJSON'\n\t\t\t}\n\t\t};\n\n\t\t// standard BufferGeometry serialization\n\n\t\tdata.uuid = this.uuid;\n\t\tdata.type = this.type;\n\t\tif ( this.name !== '' ) data.name = this.name;\n\t\tif ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;\n\n\t\tif ( this.parameters !== undefined ) {\n\n\t\t\tconst parameters = this.parameters;\n\n\t\t\tfor ( const key in parameters ) {\n\n\t\t\t\tif ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];\n\n\t\t\t}\n\n\t\t\treturn data;\n\n\t\t}\n\n\t\t// for simplicity the code assumes attributes are not shared across geometries, see #15811\n\n\t\tdata.data = { attributes: {} };\n\n\t\tconst index = this.index;\n\n\t\tif ( index !== null ) {\n\n\t\t\tdata.data.index = {\n\t\t\t\ttype: index.array.constructor.name,\n\t\t\t\tarray: Array.prototype.slice.call( index.array )\n\t\t\t};\n\n\t\t}\n\n\t\tconst attributes = this.attributes;\n\n\t\tfor ( const key in attributes ) {\n\n\t\t\tconst attribute = attributes[ key ];\n\n\t\t\tdata.data.attributes[ key ] = attribute.toJSON( data.data );\n\n\t\t}\n\n\t\tconst morphAttributes = {};\n\t\tlet hasMorphAttributes = false;\n\n\t\tfor ( const key in this.morphAttributes ) {\n\n\t\t\tconst attributeArray = this.morphAttributes[ key ];\n\n\t\t\tconst array = [];\n\n\t\t\tfor ( let i = 0, il = attributeArray.length; i < il; i ++ ) {\n\n\t\t\t\tconst attribute = attributeArray[ i ];\n\n\t\t\t\tarray.push( attribute.toJSON( data.data ) );\n\n\t\t\t}\n\n\t\t\tif ( array.length > 0 ) {\n\n\t\t\t\tmorphAttributes[ key ] = array;\n\n\t\t\t\thasMorphAttributes = true;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( hasMorphAttributes ) {\n\n\t\t\tdata.data.morphAttributes = morphAttributes;\n\t\t\tdata.data.morphTargetsRelative = this.morphTargetsRelative;\n\n\t\t}\n\n\t\tconst groups = this.groups;\n\n\t\tif ( groups.length > 0 ) {\n\n\t\t\tdata.data.groups = JSON.parse( JSON.stringify( groups ) );\n\n\t\t}\n\n\t\tconst boundingSphere = this.boundingSphere;\n\n\t\tif ( boundingSphere !== null ) {\n\n\t\t\tdata.data.boundingSphere = {\n\t\t\t\tcenter: boundingSphere.center.toArray(),\n\t\t\t\tradius: boundingSphere.radius\n\t\t\t};\n\n\t\t}\n\n\t\treturn data;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n\tcopy( source ) {\n\n\t\t// reset\n\n\t\tthis.index = null;\n\t\tthis.attributes = {};\n\t\tthis.morphAttributes = {};\n\t\tthis.groups = [];\n\t\tthis.boundingBox = null;\n\t\tthis.boundingSphere = null;\n\n\t\t// used for storing cloned, shared data\n\n\t\tconst data = {};\n\n\t\t// name\n\n\t\tthis.name = source.name;\n\n\t\t// index\n\n\t\tconst index = source.index;\n\n\t\tif ( index !== null ) {\n\n\t\t\tthis.setIndex( index.clone( data ) );\n\n\t\t}\n\n\t\t// attributes\n\n\t\tconst attributes = source.attributes;\n\n\t\tfor ( const name in attributes ) {\n\n\t\t\tconst attribute = attributes[ name ];\n\t\t\tthis.setAttribute( name, attribute.clone( data ) );\n\n\t\t}\n\n\t\t// morph attributes\n\n\t\tconst morphAttributes = source.morphAttributes;\n\n\t\tfor ( const name in morphAttributes ) {\n\n\t\t\tconst array = [];\n\t\t\tconst morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes\n\n\t\t\tfor ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {\n\n\t\t\t\tarray.push( morphAttribute[ i ].clone( data ) );\n\n\t\t\t}\n\n\t\t\tthis.morphAttributes[ name ] = array;\n\n\t\t}\n\n\t\tthis.morphTargetsRelative = source.morphTargetsRelative;\n\n\t\t// groups\n\n\t\tconst groups = source.groups;\n\n\t\tfor ( let i = 0, l = groups.length; i < l; i ++ ) {\n\n\t\t\tconst group = groups[ i ];\n\t\t\tthis.addGroup( group.start, group.count, group.materialIndex );\n\n\t\t}\n\n\t\t// bounding box\n\n\t\tconst boundingBox = source.boundingBox;\n\n\t\tif ( boundingBox !== null ) {\n\n\t\t\tthis.boundingBox = boundingBox.clone();\n\n\t\t}\n\n\t\t// bounding sphere\n\n\t\tconst boundingSphere = source.boundingSphere;\n\n\t\tif ( boundingSphere !== null ) {\n\n\t\t\tthis.boundingSphere = boundingSphere.clone();\n\n\t\t}\n\n\t\t// draw range\n\n\t\tthis.drawRange.start = source.drawRange.start;\n\t\tthis.drawRange.count = source.drawRange.count;\n\n\t\t// user data\n\n\t\tthis.userData = source.userData;\n\n\t\treturn this;\n\n\t}\n\n\tdispose() {\n\n\t\tthis.dispatchEvent( { type: 'dispose' } );\n\n\t}\n\n}\n\nconst _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();\nconst _ray$2 = /*@__PURE__*/ new Ray();\nconst _sphere$4 = /*@__PURE__*/ new Sphere();\nconst _sphereHitAt = /*@__PURE__*/ new Vector3();\n\nconst _vA$1 = /*@__PURE__*/ new Vector3();\nconst _vB$1 = /*@__PURE__*/ new Vector3();\nconst _vC$1 = /*@__PURE__*/ new Vector3();\n\nconst _tempA = /*@__PURE__*/ new Vector3();\nconst _morphA = /*@__PURE__*/ new Vector3();\n\nconst _uvA$1 = /*@__PURE__*/ new Vector2();\nconst _uvB$1 = /*@__PURE__*/ new Vector2();\nconst _uvC$1 = /*@__PURE__*/ new Vector2();\n\nconst _normalA = /*@__PURE__*/ new Vector3();\nconst _normalB = /*@__PURE__*/ new Vector3();\nconst _normalC = /*@__PURE__*/ new Vector3();\n\nconst _intersectionPoint = /*@__PURE__*/ new Vector3();\nconst _intersectionPointWorld = /*@__PURE__*/ new Vector3();\n\nclass Mesh extends Object3D {\n\n\tconstructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {\n\n\t\tsuper();\n\n\t\tthis.isMesh = true;\n\n\t\tthis.type = 'Mesh';\n\n\t\tthis.geometry = geometry;\n\t\tthis.material = material;\n\n\t\tthis.updateMorphTargets();\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tif ( source.morphTargetInfluences !== undefined ) {\n\n\t\t\tthis.morphTargetInfluences = source.morphTargetInfluences.slice();\n\n\t\t}\n\n\t\tif ( source.morphTargetDictionary !== undefined ) {\n\n\t\t\tthis.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );\n\n\t\t}\n\n\t\tthis.material = source.material;\n\t\tthis.geometry = source.geometry;\n\n\t\treturn this;\n\n\t}\n\n\tupdateMorphTargets() {\n\n\t\tconst geometry = this.geometry;\n\n\t\tconst morphAttributes = geometry.morphAttributes;\n\t\tconst keys = Object.keys( morphAttributes );\n\n\t\tif ( keys.length > 0 ) {\n\n\t\t\tconst morphAttribute = morphAttributes[ keys[ 0 ] ];\n\n\t\t\tif ( morphAttribute !== undefined ) {\n\n\t\t\t\tthis.morphTargetInfluences = [];\n\t\t\t\tthis.morphTargetDictionary = {};\n\n\t\t\t\tfor ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {\n\n\t\t\t\t\tconst name = morphAttribute[ m ].name || String( m );\n\n\t\t\t\t\tthis.morphTargetInfluences.push( 0 );\n\t\t\t\t\tthis.morphTargetDictionary[ name ] = m;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tgetVertexPosition( index, target ) {\n\n\t\tconst geometry = this.geometry;\n\t\tconst position = geometry.attributes.position;\n\t\tconst morphPosition = geometry.morphAttributes.position;\n\t\tconst morphTargetsRelative = geometry.morphTargetsRelative;\n\n\t\ttarget.fromBufferAttribute( position, index );\n\n\t\tconst morphInfluences = this.morphTargetInfluences;\n\n\t\tif ( morphPosition && morphInfluences ) {\n\n\t\t\t_morphA.set( 0, 0, 0 );\n\n\t\t\tfor ( let i = 0, il = morphPosition.length; i < il; i ++ ) {\n\n\t\t\t\tconst influence = morphInfluences[ i ];\n\t\t\t\tconst morphAttribute = morphPosition[ i ];\n\n\t\t\t\tif ( influence === 0 ) continue;\n\n\t\t\t\t_tempA.fromBufferAttribute( morphAttribute, index );\n\n\t\t\t\tif ( morphTargetsRelative ) {\n\n\t\t\t\t\t_morphA.addScaledVector( _tempA, influence );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t_morphA.addScaledVector( _tempA.sub( target ), influence );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\ttarget.add( _morphA );\n\n\t\t}\n\n\t\treturn target;\n\n\t}\n\n\traycast( raycaster, intersects ) {\n\n\t\tconst geometry = this.geometry;\n\t\tconst material = this.material;\n\t\tconst matrixWorld = this.matrixWorld;\n\n\t\tif ( material === undefined ) return;\n\n\t\t// Checking boundingSphere distance to ray\n\n\t\tif ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();\n\n\t\t_sphere$4.copy( geometry.boundingSphere );\n\t\t_sphere$4.applyMatrix4( matrixWorld );\n\n\t\t_ray$2.copy( raycaster.ray ).recast( raycaster.near );\n\n\t\tif ( _sphere$4.containsPoint( _ray$2.origin ) === false ) {\n\n\t\t\tif ( _ray$2.intersectSphere( _sphere$4, _sphereHitAt ) === null ) return;\n\n\t\t\tif ( _ray$2.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;\n\n\t\t}\n\n\t\t//\n\n\t\t_inverseMatrix$2.copy( matrixWorld ).invert();\n\t\t_ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );\n\n\t\t// Check boundingBox before continuing\n\n\t\tif ( geometry.boundingBox !== null ) {\n\n\t\t\tif ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;\n\n\t\t}\n\n\t\tthis._computeIntersections( raycaster, intersects );\n\n\t}\n\n\t_computeIntersections( raycaster, intersects ) {\n\n\t\tlet intersection;\n\n\t\tconst geometry = this.geometry;\n\t\tconst material = this.material;\n\n\t\tconst index = geometry.index;\n\t\tconst position = geometry.attributes.position;\n\t\tconst uv = geometry.attributes.uv;\n\t\tconst uv1 = geometry.attributes.uv1;\n\t\tconst normal = geometry.attributes.normal;\n\t\tconst groups = geometry.groups;\n\t\tconst drawRange = geometry.drawRange;\n\n\t\tif ( index !== null ) {\n\n\t\t\t// indexed buffer geometry\n\n\t\t\tif ( Array.isArray( material ) ) {\n\n\t\t\t\tfor ( let i = 0, il = groups.length; i < il; i ++ ) {\n\n\t\t\t\t\tconst group = groups[ i ];\n\t\t\t\t\tconst groupMaterial = material[ group.materialIndex ];\n\n\t\t\t\t\tconst start = Math.max( group.start, drawRange.start );\n\t\t\t\t\tconst end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );\n\n\t\t\t\t\tfor ( let j = start, jl = end; j < jl; j += 3 ) {\n\n\t\t\t\t\t\tconst a = index.getX( j );\n\t\t\t\t\t\tconst b = index.getX( j + 1 );\n\t\t\t\t\t\tconst c = index.getX( j + 2 );\n\n\t\t\t\t\t\tintersection = checkGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv1, normal, a, b, c );\n\n\t\t\t\t\t\tif ( intersection ) {\n\n\t\t\t\t\t\t\tintersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics\n\t\t\t\t\t\t\tintersection.face.materialIndex = group.materialIndex;\n\t\t\t\t\t\t\tintersects.push( intersection );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tconst start = Math.max( 0, drawRange.start );\n\t\t\t\tconst end = Math.min( index.count, ( drawRange.start + drawRange.count ) );\n\n\t\t\t\tfor ( let i = start, il = end; i < il; i += 3 ) {\n\n\t\t\t\t\tconst a = index.getX( i );\n\t\t\t\t\tconst b = index.getX( i + 1 );\n\t\t\t\t\tconst c = index.getX( i + 2 );\n\n\t\t\t\t\tintersection = checkGeometryIntersection( this, material, raycaster, _ray$2, uv, uv1, normal, a, b, c );\n\n\t\t\t\t\tif ( intersection ) {\n\n\t\t\t\t\t\tintersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics\n\t\t\t\t\t\tintersects.push( intersection );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else if ( position !== undefined ) {\n\n\t\t\t// non-indexed buffer geometry\n\n\t\t\tif ( Array.isArray( material ) ) {\n\n\t\t\t\tfor ( let i = 0, il = groups.length; i < il; i ++ ) {\n\n\t\t\t\t\tconst group = groups[ i ];\n\t\t\t\t\tconst groupMaterial = material[ group.materialIndex ];\n\n\t\t\t\t\tconst start = Math.max( group.start, drawRange.start );\n\t\t\t\t\tconst end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );\n\n\t\t\t\t\tfor ( let j = start, jl = end; j < jl; j += 3 ) {\n\n\t\t\t\t\t\tconst a = j;\n\t\t\t\t\t\tconst b = j + 1;\n\t\t\t\t\t\tconst c = j + 2;\n\n\t\t\t\t\t\tintersection = checkGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv1, normal, a, b, c );\n\n\t\t\t\t\t\tif ( intersection ) {\n\n\t\t\t\t\t\t\tintersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics\n\t\t\t\t\t\t\tintersection.face.materialIndex = group.materialIndex;\n\t\t\t\t\t\t\tintersects.push( intersection );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tconst start = Math.max( 0, drawRange.start );\n\t\t\t\tconst end = Math.min( position.count, ( drawRange.start + drawRange.count ) );\n\n\t\t\t\tfor ( let i = start, il = end; i < il; i += 3 ) {\n\n\t\t\t\t\tconst a = i;\n\t\t\t\t\tconst b = i + 1;\n\t\t\t\t\tconst c = i + 2;\n\n\t\t\t\t\tintersection = checkGeometryIntersection( this, material, raycaster, _ray$2, uv, uv1, normal, a, b, c );\n\n\t\t\t\t\tif ( intersection ) {\n\n\t\t\t\t\t\tintersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics\n\t\t\t\t\t\tintersects.push( intersection );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}\n\nfunction checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {\n\n\tlet intersect;\n\n\tif ( material.side === BackSide ) {\n\n\t\tintersect = ray.intersectTriangle( pC, pB, pA, true, point );\n\n\t} else {\n\n\t\tintersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );\n\n\t}\n\n\tif ( intersect === null ) return null;\n\n\t_intersectionPointWorld.copy( point );\n\t_intersectionPointWorld.applyMatrix4( object.matrixWorld );\n\n\tconst distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );\n\n\tif ( distance < raycaster.near || distance > raycaster.far ) return null;\n\n\treturn {\n\t\tdistance: distance,\n\t\tpoint: _intersectionPointWorld.clone(),\n\t\tobject: object\n\t};\n\n}\n\nfunction checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {\n\n\tobject.getVertexPosition( a, _vA$1 );\n\tobject.getVertexPosition( b, _vB$1 );\n\tobject.getVertexPosition( c, _vC$1 );\n\n\tconst intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );\n\n\tif ( intersection ) {\n\n\t\tif ( uv ) {\n\n\t\t\t_uvA$1.fromBufferAttribute( uv, a );\n\t\t\t_uvB$1.fromBufferAttribute( uv, b );\n\t\t\t_uvC$1.fromBufferAttribute( uv, c );\n\n\t\t\tintersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );\n\n\t\t}\n\n\t\tif ( uv1 ) {\n\n\t\t\t_uvA$1.fromBufferAttribute( uv1, a );\n\t\t\t_uvB$1.fromBufferAttribute( uv1, b );\n\t\t\t_uvC$1.fromBufferAttribute( uv1, c );\n\n\t\t\tintersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );\n\t\t\tintersection.uv2 = intersection.uv1; // Backwards compatibility\n\n\t\t}\n\n\t\tif ( normal ) {\n\n\t\t\t_normalA.fromBufferAttribute( normal, a );\n\t\t\t_normalB.fromBufferAttribute( normal, b );\n\t\t\t_normalC.fromBufferAttribute( normal, c );\n\n\t\t\tintersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );\n\n\t\t\tif ( intersection.normal.dot( ray.direction ) > 0 ) {\n\n\t\t\t\tintersection.normal.multiplyScalar( - 1 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst face = {\n\t\t\ta: a,\n\t\t\tb: b,\n\t\t\tc: c,\n\t\t\tnormal: new Vector3(),\n\t\t\tmaterialIndex: 0\n\t\t};\n\n\t\tTriangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );\n\n\t\tintersection.face = face;\n\n\t}\n\n\treturn intersection;\n\n}\n\nclass BoxGeometry extends BufferGeometry {\n\n\tconstructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'BoxGeometry';\n\n\t\tthis.parameters = {\n\t\t\twidth: width,\n\t\t\theight: height,\n\t\t\tdepth: depth,\n\t\t\twidthSegments: widthSegments,\n\t\t\theightSegments: heightSegments,\n\t\t\tdepthSegments: depthSegments\n\t\t};\n\n\t\tconst scope = this;\n\n\t\t// segments\n\n\t\twidthSegments = Math.floor( widthSegments );\n\t\theightSegments = Math.floor( heightSegments );\n\t\tdepthSegments = Math.floor( depthSegments );\n\n\t\t// buffers\n\n\t\tconst indices = [];\n\t\tconst vertices = [];\n\t\tconst normals = [];\n\t\tconst uvs = [];\n\n\t\t// helper variables\n\n\t\tlet numberOfVertices = 0;\n\t\tlet groupStart = 0;\n\n\t\t// build each side of the box geometry\n\n\t\tbuildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px\n\t\tbuildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx\n\t\tbuildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py\n\t\tbuildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny\n\t\tbuildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz\n\t\tbuildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz\n\n\t\t// build geometry\n\n\t\tthis.setIndex( indices );\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tthis.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );\n\n\t\tfunction buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {\n\n\t\t\tconst segmentWidth = width / gridX;\n\t\t\tconst segmentHeight = height / gridY;\n\n\t\t\tconst widthHalf = width / 2;\n\t\t\tconst heightHalf = height / 2;\n\t\t\tconst depthHalf = depth / 2;\n\n\t\t\tconst gridX1 = gridX + 1;\n\t\t\tconst gridY1 = gridY + 1;\n\n\t\t\tlet vertexCounter = 0;\n\t\t\tlet groupCount = 0;\n\n\t\t\tconst vector = new Vector3();\n\n\t\t\t// generate vertices, normals and uvs\n\n\t\t\tfor ( let iy = 0; iy < gridY1; iy ++ ) {\n\n\t\t\t\tconst y = iy * segmentHeight - heightHalf;\n\n\t\t\t\tfor ( let ix = 0; ix < gridX1; ix ++ ) {\n\n\t\t\t\t\tconst x = ix * segmentWidth - widthHalf;\n\n\t\t\t\t\t// set values to correct vector component\n\n\t\t\t\t\tvector[ u ] = x * udir;\n\t\t\t\t\tvector[ v ] = y * vdir;\n\t\t\t\t\tvector[ w ] = depthHalf;\n\n\t\t\t\t\t// now apply vector to vertex buffer\n\n\t\t\t\t\tvertices.push( vector.x, vector.y, vector.z );\n\n\t\t\t\t\t// set values to correct vector component\n\n\t\t\t\t\tvector[ u ] = 0;\n\t\t\t\t\tvector[ v ] = 0;\n\t\t\t\t\tvector[ w ] = depth > 0 ? 1 : - 1;\n\n\t\t\t\t\t// now apply vector to normal buffer\n\n\t\t\t\t\tnormals.push( vector.x, vector.y, vector.z );\n\n\t\t\t\t\t// uvs\n\n\t\t\t\t\tuvs.push( ix / gridX );\n\t\t\t\t\tuvs.push( 1 - ( iy / gridY ) );\n\n\t\t\t\t\t// counters\n\n\t\t\t\t\tvertexCounter += 1;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// indices\n\n\t\t\t// 1. you need three indices to draw a single face\n\t\t\t// 2. a single segment consists of two faces\n\t\t\t// 3. so we need to generate six (2*3) indices per segment\n\n\t\t\tfor ( let iy = 0; iy < gridY; iy ++ ) {\n\n\t\t\t\tfor ( let ix = 0; ix < gridX; ix ++ ) {\n\n\t\t\t\t\tconst a = numberOfVertices + ix + gridX1 * iy;\n\t\t\t\t\tconst b = numberOfVertices + ix + gridX1 * ( iy + 1 );\n\t\t\t\t\tconst c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );\n\t\t\t\t\tconst d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;\n\n\t\t\t\t\t// faces\n\n\t\t\t\t\tindices.push( a, b, d );\n\t\t\t\t\tindices.push( b, c, d );\n\n\t\t\t\t\t// increase counter\n\n\t\t\t\t\tgroupCount += 6;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// add a group to the geometry. this will ensure multi material support\n\n\t\t\tscope.addGroup( groupStart, groupCount, materialIndex );\n\n\t\t\t// calculate new start value for groups\n\n\t\t\tgroupStart += groupCount;\n\n\t\t\t// update total number of vertices\n\n\t\t\tnumberOfVertices += vertexCounter;\n\n\t\t}\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );\n\n\t}\n\n}\n\n/**\n * Uniform Utilities\n */\n\nfunction cloneUniforms( src ) {\n\n\tconst dst = {};\n\n\tfor ( const u in src ) {\n\n\t\tdst[ u ] = {};\n\n\t\tfor ( const p in src[ u ] ) {\n\n\t\t\tconst property = src[ u ][ p ];\n\n\t\t\tif ( property && ( property.isColor ||\n\t\t\t\tproperty.isMatrix3 || property.isMatrix4 ||\n\t\t\t\tproperty.isVector2 || property.isVector3 || property.isVector4 ||\n\t\t\t\tproperty.isTexture || property.isQuaternion ) ) {\n\n\t\t\t\tif ( property.isRenderTargetTexture ) {\n\n\t\t\t\t\tconsole.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );\n\t\t\t\t\tdst[ u ][ p ] = null;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tdst[ u ][ p ] = property.clone();\n\n\t\t\t\t}\n\n\t\t\t} else if ( Array.isArray( property ) ) {\n\n\t\t\t\tdst[ u ][ p ] = property.slice();\n\n\t\t\t} else {\n\n\t\t\t\tdst[ u ][ p ] = property;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn dst;\n\n}\n\nfunction mergeUniforms( uniforms ) {\n\n\tconst merged = {};\n\n\tfor ( let u = 0; u < uniforms.length; u ++ ) {\n\n\t\tconst tmp = cloneUniforms( uniforms[ u ] );\n\n\t\tfor ( const p in tmp ) {\n\n\t\t\tmerged[ p ] = tmp[ p ];\n\n\t\t}\n\n\t}\n\n\treturn merged;\n\n}\n\nfunction cloneUniformsGroups( src ) {\n\n\tconst dst = [];\n\n\tfor ( let u = 0; u < src.length; u ++ ) {\n\n\t\tdst.push( src[ u ].clone() );\n\n\t}\n\n\treturn dst;\n\n}\n\nfunction getUnlitUniformColorSpace( renderer ) {\n\n\tif ( renderer.getRenderTarget() === null ) {\n\n\t\t// https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398\n\t\treturn renderer.outputColorSpace;\n\n\t}\n\n\treturn LinearSRGBColorSpace;\n\n}\n\n// Legacy\n\nconst UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };\n\nvar default_vertex = \"void main() {\\n\\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\\n}\";\n\nvar default_fragment = \"void main() {\\n\\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\\n}\";\n\nclass ShaderMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isShaderMaterial = true;\n\n\t\tthis.type = 'ShaderMaterial';\n\n\t\tthis.defines = {};\n\t\tthis.uniforms = {};\n\t\tthis.uniformsGroups = [];\n\n\t\tthis.vertexShader = default_vertex;\n\t\tthis.fragmentShader = default_fragment;\n\n\t\tthis.linewidth = 1;\n\n\t\tthis.wireframe = false;\n\t\tthis.wireframeLinewidth = 1;\n\n\t\tthis.fog = false; // set to use scene fog\n\t\tthis.lights = false; // set to use scene lights\n\t\tthis.clipping = false; // set to use user-defined clipping planes\n\n\t\tthis.forceSinglePass = true;\n\n\t\tthis.extensions = {\n\t\t\tderivatives: false, // set to use derivatives\n\t\t\tfragDepth: false, // set to use fragment depth values\n\t\t\tdrawBuffers: false, // set to use draw buffers\n\t\t\tshaderTextureLOD: false // set to use shader texture LOD\n\t\t};\n\n\t\t// When rendered geometry doesn't include these attributes but the material does,\n\t\t// use these default values in WebGL. This avoids errors when buffer data is missing.\n\t\tthis.defaultAttributeValues = {\n\t\t\t'color': [ 1, 1, 1 ],\n\t\t\t'uv': [ 0, 0 ],\n\t\t\t'uv1': [ 0, 0 ]\n\t\t};\n\n\t\tthis.index0AttributeName = undefined;\n\t\tthis.uniformsNeedUpdate = false;\n\n\t\tthis.glslVersion = null;\n\n\t\tif ( parameters !== undefined ) {\n\n\t\t\tthis.setValues( parameters );\n\n\t\t}\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.fragmentShader = source.fragmentShader;\n\t\tthis.vertexShader = source.vertexShader;\n\n\t\tthis.uniforms = cloneUniforms( source.uniforms );\n\t\tthis.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );\n\n\t\tthis.defines = Object.assign( {}, source.defines );\n\n\t\tthis.wireframe = source.wireframe;\n\t\tthis.wireframeLinewidth = source.wireframeLinewidth;\n\n\t\tthis.fog = source.fog;\n\t\tthis.lights = source.lights;\n\t\tthis.clipping = source.clipping;\n\n\t\tthis.extensions = Object.assign( {}, source.extensions );\n\n\t\tthis.glslVersion = source.glslVersion;\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON( meta ) {\n\n\t\tconst data = super.toJSON( meta );\n\n\t\tdata.glslVersion = this.glslVersion;\n\t\tdata.uniforms = {};\n\n\t\tfor ( const name in this.uniforms ) {\n\n\t\t\tconst uniform = this.uniforms[ name ];\n\t\t\tconst value = uniform.value;\n\n\t\t\tif ( value && value.isTexture ) {\n\n\t\t\t\tdata.uniforms[ name ] = {\n\t\t\t\t\ttype: 't',\n\t\t\t\t\tvalue: value.toJSON( meta ).uuid\n\t\t\t\t};\n\n\t\t\t} else if ( value && value.isColor ) {\n\n\t\t\t\tdata.uniforms[ name ] = {\n\t\t\t\t\ttype: 'c',\n\t\t\t\t\tvalue: value.getHex()\n\t\t\t\t};\n\n\t\t\t} else if ( value && value.isVector2 ) {\n\n\t\t\t\tdata.uniforms[ name ] = {\n\t\t\t\t\ttype: 'v2',\n\t\t\t\t\tvalue: value.toArray()\n\t\t\t\t};\n\n\t\t\t} else if ( value && value.isVector3 ) {\n\n\t\t\t\tdata.uniforms[ name ] = {\n\t\t\t\t\ttype: 'v3',\n\t\t\t\t\tvalue: value.toArray()\n\t\t\t\t};\n\n\t\t\t} else if ( value && value.isVector4 ) {\n\n\t\t\t\tdata.uniforms[ name ] = {\n\t\t\t\t\ttype: 'v4',\n\t\t\t\t\tvalue: value.toArray()\n\t\t\t\t};\n\n\t\t\t} else if ( value && value.isMatrix3 ) {\n\n\t\t\t\tdata.uniforms[ name ] = {\n\t\t\t\t\ttype: 'm3',\n\t\t\t\t\tvalue: value.toArray()\n\t\t\t\t};\n\n\t\t\t} else if ( value && value.isMatrix4 ) {\n\n\t\t\t\tdata.uniforms[ name ] = {\n\t\t\t\t\ttype: 'm4',\n\t\t\t\t\tvalue: value.toArray()\n\t\t\t\t};\n\n\t\t\t} else {\n\n\t\t\t\tdata.uniforms[ name ] = {\n\t\t\t\t\tvalue: value\n\t\t\t\t};\n\n\t\t\t\t// note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;\n\n\t\tdata.vertexShader = this.vertexShader;\n\t\tdata.fragmentShader = this.fragmentShader;\n\n\t\tdata.lights = this.lights;\n\t\tdata.clipping = this.clipping;\n\n\t\tconst extensions = {};\n\n\t\tfor ( const key in this.extensions ) {\n\n\t\t\tif ( this.extensions[ key ] === true ) extensions[ key ] = true;\n\n\t\t}\n\n\t\tif ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;\n\n\t\treturn data;\n\n\t}\n\n}\n\nclass Camera extends Object3D {\n\n\tconstructor() {\n\n\t\tsuper();\n\n\t\tthis.isCamera = true;\n\n\t\tthis.type = 'Camera';\n\n\t\tthis.matrixWorldInverse = new Matrix4();\n\n\t\tthis.projectionMatrix = new Matrix4();\n\t\tthis.projectionMatrixInverse = new Matrix4();\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tthis.matrixWorldInverse.copy( source.matrixWorldInverse );\n\n\t\tthis.projectionMatrix.copy( source.projectionMatrix );\n\t\tthis.projectionMatrixInverse.copy( source.projectionMatrixInverse );\n\n\t\treturn this;\n\n\t}\n\n\tgetWorldDirection( target ) {\n\n\t\tthis.updateWorldMatrix( true, false );\n\n\t\tconst e = this.matrixWorld.elements;\n\n\t\treturn target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();\n\n\t}\n\n\tupdateMatrixWorld( force ) {\n\n\t\tsuper.updateMatrixWorld( force );\n\n\t\tthis.matrixWorldInverse.copy( this.matrixWorld ).invert();\n\n\t}\n\n\tupdateWorldMatrix( updateParents, updateChildren ) {\n\n\t\tsuper.updateWorldMatrix( updateParents, updateChildren );\n\n\t\tthis.matrixWorldInverse.copy( this.matrixWorld ).invert();\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n}\n\nclass PerspectiveCamera extends Camera {\n\n\tconstructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {\n\n\t\tsuper();\n\n\t\tthis.isPerspectiveCamera = true;\n\n\t\tthis.type = 'PerspectiveCamera';\n\n\t\tthis.fov = fov;\n\t\tthis.zoom = 1;\n\n\t\tthis.near = near;\n\t\tthis.far = far;\n\t\tthis.focus = 10;\n\n\t\tthis.aspect = aspect;\n\t\tthis.view = null;\n\n\t\tthis.filmGauge = 35;\t// width of the film (default in millimeters)\n\t\tthis.filmOffset = 0;\t// horizontal film offset (same unit as gauge)\n\n\t\tthis.updateProjectionMatrix();\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tthis.fov = source.fov;\n\t\tthis.zoom = source.zoom;\n\n\t\tthis.near = source.near;\n\t\tthis.far = source.far;\n\t\tthis.focus = source.focus;\n\n\t\tthis.aspect = source.aspect;\n\t\tthis.view = source.view === null ? null : Object.assign( {}, source.view );\n\n\t\tthis.filmGauge = source.filmGauge;\n\t\tthis.filmOffset = source.filmOffset;\n\n\t\treturn this;\n\n\t}\n\n\t/**\n\t * Sets the FOV by focal length in respect to the current .filmGauge.\n\t *\n\t * The default film gauge is 35, so that the focal length can be specified for\n\t * a 35mm (full frame) camera.\n\t *\n\t * Values for focal length and film gauge must have the same unit.\n\t */\n\tsetFocalLength( focalLength ) {\n\n\t\t/** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */\n\t\tconst vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;\n\n\t\tthis.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );\n\t\tthis.updateProjectionMatrix();\n\n\t}\n\n\t/**\n\t * Calculates the focal length from the current .fov and .filmGauge.\n\t */\n\tgetFocalLength() {\n\n\t\tconst vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );\n\n\t\treturn 0.5 * this.getFilmHeight() / vExtentSlope;\n\n\t}\n\n\tgetEffectiveFOV() {\n\n\t\treturn RAD2DEG * 2 * Math.atan(\n\t\t\tMath.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );\n\n\t}\n\n\tgetFilmWidth() {\n\n\t\t// film not completely covered in portrait format (aspect < 1)\n\t\treturn this.filmGauge * Math.min( this.aspect, 1 );\n\n\t}\n\n\tgetFilmHeight() {\n\n\t\t// film not completely covered in landscape format (aspect > 1)\n\t\treturn this.filmGauge / Math.max( this.aspect, 1 );\n\n\t}\n\n\t/**\n\t * Sets an offset in a larger frustum. This is useful for multi-window or\n\t * multi-monitor/multi-machine setups.\n\t *\n\t * For example, if you have 3x2 monitors and each monitor is 1920x1080 and\n\t * the monitors are in grid like this\n\t *\n\t * +---+---+---+\n\t * | A | B | C |\n\t * +---+---+---+\n\t * | D | E | F |\n\t * +---+---+---+\n\t *\n\t * then for each monitor you would call it like this\n\t *\n\t * const w = 1920;\n\t * const h = 1080;\n\t * const fullWidth = w * 3;\n\t * const fullHeight = h * 2;\n\t *\n\t * --A--\n\t * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );\n\t * --B--\n\t * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );\n\t * --C--\n\t * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );\n\t * --D--\n\t * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );\n\t * --E--\n\t * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );\n\t * --F--\n\t * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );\n\t *\n\t * Note there is no reason monitors have to be the same size or in a grid.\n\t */\n\tsetViewOffset( fullWidth, fullHeight, x, y, width, height ) {\n\n\t\tthis.aspect = fullWidth / fullHeight;\n\n\t\tif ( this.view === null ) {\n\n\t\t\tthis.view = {\n\t\t\t\tenabled: true,\n\t\t\t\tfullWidth: 1,\n\t\t\t\tfullHeight: 1,\n\t\t\t\toffsetX: 0,\n\t\t\t\toffsetY: 0,\n\t\t\t\twidth: 1,\n\t\t\t\theight: 1\n\t\t\t};\n\n\t\t}\n\n\t\tthis.view.enabled = true;\n\t\tthis.view.fullWidth = fullWidth;\n\t\tthis.view.fullHeight = fullHeight;\n\t\tthis.view.offsetX = x;\n\t\tthis.view.offsetY = y;\n\t\tthis.view.width = width;\n\t\tthis.view.height = height;\n\n\t\tthis.updateProjectionMatrix();\n\n\t}\n\n\tclearViewOffset() {\n\n\t\tif ( this.view !== null ) {\n\n\t\t\tthis.view.enabled = false;\n\n\t\t}\n\n\t\tthis.updateProjectionMatrix();\n\n\t}\n\n\tupdateProjectionMatrix() {\n\n\t\tconst near = this.near;\n\t\tlet top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;\n\t\tlet height = 2 * top;\n\t\tlet width = this.aspect * height;\n\t\tlet left = - 0.5 * width;\n\t\tconst view = this.view;\n\n\t\tif ( this.view !== null && this.view.enabled ) {\n\n\t\t\tconst fullWidth = view.fullWidth,\n\t\t\t\tfullHeight = view.fullHeight;\n\n\t\t\tleft += view.offsetX * width / fullWidth;\n\t\t\ttop -= view.offsetY * height / fullHeight;\n\t\t\twidth *= view.width / fullWidth;\n\t\t\theight *= view.height / fullHeight;\n\n\t\t}\n\n\t\tconst skew = this.filmOffset;\n\t\tif ( skew !== 0 ) left += near * skew / this.getFilmWidth();\n\n\t\tthis.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );\n\n\t\tthis.projectionMatrixInverse.copy( this.projectionMatrix ).invert();\n\n\t}\n\n\ttoJSON( meta ) {\n\n\t\tconst data = super.toJSON( meta );\n\n\t\tdata.object.fov = this.fov;\n\t\tdata.object.zoom = this.zoom;\n\n\t\tdata.object.near = this.near;\n\t\tdata.object.far = this.far;\n\t\tdata.object.focus = this.focus;\n\n\t\tdata.object.aspect = this.aspect;\n\n\t\tif ( this.view !== null ) data.object.view = Object.assign( {}, this.view );\n\n\t\tdata.object.filmGauge = this.filmGauge;\n\t\tdata.object.filmOffset = this.filmOffset;\n\n\t\treturn data;\n\n\t}\n\n}\n\nconst fov = - 90; // negative fov is not an error\nconst aspect = 1;\n\nclass CubeCamera extends Object3D {\n\n\tconstructor( near, far, renderTarget ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'CubeCamera';\n\n\t\tthis.renderTarget = renderTarget;\n\n\t\tconst cameraPX = new PerspectiveCamera( fov, aspect, near, far );\n\t\tcameraPX.layers = this.layers;\n\t\tcameraPX.up.set( 0, 1, 0 );\n\t\tcameraPX.lookAt( 1, 0, 0 );\n\t\tthis.add( cameraPX );\n\n\t\tconst cameraNX = new PerspectiveCamera( fov, aspect, near, far );\n\t\tcameraNX.layers = this.layers;\n\t\tcameraNX.up.set( 0, 1, 0 );\n\t\tcameraNX.lookAt( - 1, 0, 0 );\n\t\tthis.add( cameraNX );\n\n\t\tconst cameraPY = new PerspectiveCamera( fov, aspect, near, far );\n\t\tcameraPY.layers = this.layers;\n\t\tcameraPY.up.set( 0, 0, - 1 );\n\t\tcameraPY.lookAt( 0, 1, 0 );\n\t\tthis.add( cameraPY );\n\n\t\tconst cameraNY = new PerspectiveCamera( fov, aspect, near, far );\n\t\tcameraNY.layers = this.layers;\n\t\tcameraNY.up.set( 0, 0, 1 );\n\t\tcameraNY.lookAt( 0, - 1, 0 );\n\t\tthis.add( cameraNY );\n\n\t\tconst cameraPZ = new PerspectiveCamera( fov, aspect, near, far );\n\t\tcameraPZ.layers = this.layers;\n\t\tcameraPZ.up.set( 0, 1, 0 );\n\t\tcameraPZ.lookAt( 0, 0, 1 );\n\t\tthis.add( cameraPZ );\n\n\t\tconst cameraNZ = new PerspectiveCamera( fov, aspect, near, far );\n\t\tcameraNZ.layers = this.layers;\n\t\tcameraNZ.up.set( 0, 1, 0 );\n\t\tcameraNZ.lookAt( 0, 0, - 1 );\n\t\tthis.add( cameraNZ );\n\n\t}\n\n\tupdate( renderer, scene ) {\n\n\t\tif ( this.parent === null ) this.updateMatrixWorld();\n\n\t\tconst renderTarget = this.renderTarget;\n\n\t\tconst [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;\n\n\t\tconst currentRenderTarget = renderer.getRenderTarget();\n\n\t\tconst currentToneMapping = renderer.toneMapping;\n\t\tconst currentXrEnabled = renderer.xr.enabled;\n\n\t\trenderer.toneMapping = NoToneMapping;\n\t\trenderer.xr.enabled = false;\n\n\t\tconst generateMipmaps = renderTarget.texture.generateMipmaps;\n\n\t\trenderTarget.texture.generateMipmaps = false;\n\n\t\trenderer.setRenderTarget( renderTarget, 0 );\n\t\trenderer.render( scene, cameraPX );\n\n\t\trenderer.setRenderTarget( renderTarget, 1 );\n\t\trenderer.render( scene, cameraNX );\n\n\t\trenderer.setRenderTarget( renderTarget, 2 );\n\t\trenderer.render( scene, cameraPY );\n\n\t\trenderer.setRenderTarget( renderTarget, 3 );\n\t\trenderer.render( scene, cameraNY );\n\n\t\trenderer.setRenderTarget( renderTarget, 4 );\n\t\trenderer.render( scene, cameraPZ );\n\n\t\trenderTarget.texture.generateMipmaps = generateMipmaps;\n\n\t\trenderer.setRenderTarget( renderTarget, 5 );\n\t\trenderer.render( scene, cameraNZ );\n\n\t\trenderer.setRenderTarget( currentRenderTarget );\n\n\t\trenderer.toneMapping = currentToneMapping;\n\t\trenderer.xr.enabled = currentXrEnabled;\n\n\t\trenderTarget.texture.needsPMREMUpdate = true;\n\n\t}\n\n}\n\nclass CubeTexture extends Texture {\n\n\tconstructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {\n\n\t\timages = images !== undefined ? images : [];\n\t\tmapping = mapping !== undefined ? mapping : CubeReflectionMapping;\n\n\t\tsuper( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );\n\n\t\tthis.isCubeTexture = true;\n\n\t\tthis.flipY = false;\n\n\t}\n\n\tget images() {\n\n\t\treturn this.image;\n\n\t}\n\n\tset images( value ) {\n\n\t\tthis.image = value;\n\n\t}\n\n}\n\nclass WebGLCubeRenderTarget extends WebGLRenderTarget {\n\n\tconstructor( size = 1, options = {} ) {\n\n\t\tsuper( size, size, options );\n\n\t\tthis.isWebGLCubeRenderTarget = true;\n\n\t\tconst image = { width: size, height: size, depth: 1 };\n\t\tconst images = [ image, image, image, image, image, image ];\n\n\t\tif ( options.encoding !== undefined ) {\n\n\t\t\t// @deprecated, r152\n\t\t\twarnOnce( 'THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace.' );\n\t\t\toptions.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;\n\n\t\t}\n\n\t\tthis.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );\n\n\t\t// By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)\n\t\t// in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,\n\t\t// in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.\n\n\t\t// three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped\n\t\t// and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture\n\t\t// as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).\n\n\t\tthis.texture.isRenderTargetTexture = true;\n\n\t\tthis.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;\n\t\tthis.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;\n\n\t}\n\n\tfromEquirectangularTexture( renderer, texture ) {\n\n\t\tthis.texture.type = texture.type;\n\t\tthis.texture.colorSpace = texture.colorSpace;\n\n\t\tthis.texture.generateMipmaps = texture.generateMipmaps;\n\t\tthis.texture.minFilter = texture.minFilter;\n\t\tthis.texture.magFilter = texture.magFilter;\n\n\t\tconst shader = {\n\n\t\t\tuniforms: {\n\t\t\t\ttEquirect: { value: null },\n\t\t\t},\n\n\t\t\tvertexShader: /* glsl */`\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t`,\n\n\t\t\tfragmentShader: /* glsl */`\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t`\n\t\t};\n\n\t\tconst geometry = new BoxGeometry( 5, 5, 5 );\n\n\t\tconst material = new ShaderMaterial( {\n\n\t\t\tname: 'CubemapFromEquirect',\n\n\t\t\tuniforms: cloneUniforms( shader.uniforms ),\n\t\t\tvertexShader: shader.vertexShader,\n\t\t\tfragmentShader: shader.fragmentShader,\n\t\t\tside: BackSide,\n\t\t\tblending: NoBlending\n\n\t\t} );\n\n\t\tmaterial.uniforms.tEquirect.value = texture;\n\n\t\tconst mesh = new Mesh( geometry, material );\n\n\t\tconst currentMinFilter = texture.minFilter;\n\n\t\t// Avoid blurred poles\n\t\tif ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;\n\n\t\tconst camera = new CubeCamera( 1, 10, this );\n\t\tcamera.update( renderer, mesh );\n\n\t\ttexture.minFilter = currentMinFilter;\n\n\t\tmesh.geometry.dispose();\n\t\tmesh.material.dispose();\n\n\t\treturn this;\n\n\t}\n\n\tclear( renderer, color, depth, stencil ) {\n\n\t\tconst currentRenderTarget = renderer.getRenderTarget();\n\n\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\trenderer.setRenderTarget( this, i );\n\n\t\t\trenderer.clear( color, depth, stencil );\n\n\t\t}\n\n\t\trenderer.setRenderTarget( currentRenderTarget );\n\n\t}\n\n}\n\nconst _vector1 = /*@__PURE__*/ new Vector3();\nconst _vector2 = /*@__PURE__*/ new Vector3();\nconst _normalMatrix = /*@__PURE__*/ new Matrix3();\n\nclass Plane {\n\n\tconstructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {\n\n\t\tthis.isPlane = true;\n\n\t\t// normal is assumed to be normalized\n\n\t\tthis.normal = normal;\n\t\tthis.constant = constant;\n\n\t}\n\n\tset( normal, constant ) {\n\n\t\tthis.normal.copy( normal );\n\t\tthis.constant = constant;\n\n\t\treturn this;\n\n\t}\n\n\tsetComponents( x, y, z, w ) {\n\n\t\tthis.normal.set( x, y, z );\n\t\tthis.constant = w;\n\n\t\treturn this;\n\n\t}\n\n\tsetFromNormalAndCoplanarPoint( normal, point ) {\n\n\t\tthis.normal.copy( normal );\n\t\tthis.constant = - point.dot( this.normal );\n\n\t\treturn this;\n\n\t}\n\n\tsetFromCoplanarPoints( a, b, c ) {\n\n\t\tconst normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();\n\n\t\t// Q: should an error be thrown if normal is zero (e.g. degenerate plane)?\n\n\t\tthis.setFromNormalAndCoplanarPoint( normal, a );\n\n\t\treturn this;\n\n\t}\n\n\tcopy( plane ) {\n\n\t\tthis.normal.copy( plane.normal );\n\t\tthis.constant = plane.constant;\n\n\t\treturn this;\n\n\t}\n\n\tnormalize() {\n\n\t\t// Note: will lead to a divide by zero if the plane is invalid.\n\n\t\tconst inverseNormalLength = 1.0 / this.normal.length();\n\t\tthis.normal.multiplyScalar( inverseNormalLength );\n\t\tthis.constant *= inverseNormalLength;\n\n\t\treturn this;\n\n\t}\n\n\tnegate() {\n\n\t\tthis.constant *= - 1;\n\t\tthis.normal.negate();\n\n\t\treturn this;\n\n\t}\n\n\tdistanceToPoint( point ) {\n\n\t\treturn this.normal.dot( point ) + this.constant;\n\n\t}\n\n\tdistanceToSphere( sphere ) {\n\n\t\treturn this.distanceToPoint( sphere.center ) - sphere.radius;\n\n\t}\n\n\tprojectPoint( point, target ) {\n\n\t\treturn target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );\n\n\t}\n\n\tintersectLine( line, target ) {\n\n\t\tconst direction = line.delta( _vector1 );\n\n\t\tconst denominator = this.normal.dot( direction );\n\n\t\tif ( denominator === 0 ) {\n\n\t\t\t// line is coplanar, return origin\n\t\t\tif ( this.distanceToPoint( line.start ) === 0 ) {\n\n\t\t\t\treturn target.copy( line.start );\n\n\t\t\t}\n\n\t\t\t// Unsure if this is the correct method to handle this case.\n\t\t\treturn null;\n\n\t\t}\n\n\t\tconst t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;\n\n\t\tif ( t < 0 || t > 1 ) {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\treturn target.copy( line.start ).addScaledVector( direction, t );\n\n\t}\n\n\tintersectsLine( line ) {\n\n\t\t// Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.\n\n\t\tconst startSign = this.distanceToPoint( line.start );\n\t\tconst endSign = this.distanceToPoint( line.end );\n\n\t\treturn ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );\n\n\t}\n\n\tintersectsBox( box ) {\n\n\t\treturn box.intersectsPlane( this );\n\n\t}\n\n\tintersectsSphere( sphere ) {\n\n\t\treturn sphere.intersectsPlane( this );\n\n\t}\n\n\tcoplanarPoint( target ) {\n\n\t\treturn target.copy( this.normal ).multiplyScalar( - this.constant );\n\n\t}\n\n\tapplyMatrix4( matrix, optionalNormalMatrix ) {\n\n\t\tconst normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );\n\n\t\tconst referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );\n\n\t\tconst normal = this.normal.applyMatrix3( normalMatrix ).normalize();\n\n\t\tthis.constant = - referencePoint.dot( normal );\n\n\t\treturn this;\n\n\t}\n\n\ttranslate( offset ) {\n\n\t\tthis.constant -= offset.dot( this.normal );\n\n\t\treturn this;\n\n\t}\n\n\tequals( plane ) {\n\n\t\treturn plane.normal.equals( this.normal ) && ( plane.constant === this.constant );\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n}\n\nconst _sphere$3 = /*@__PURE__*/ new Sphere();\nconst _vector$6 = /*@__PURE__*/ new Vector3();\n\nclass Frustum {\n\n\tconstructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {\n\n\t\tthis.planes = [ p0, p1, p2, p3, p4, p5 ];\n\n\t}\n\n\tset( p0, p1, p2, p3, p4, p5 ) {\n\n\t\tconst planes = this.planes;\n\n\t\tplanes[ 0 ].copy( p0 );\n\t\tplanes[ 1 ].copy( p1 );\n\t\tplanes[ 2 ].copy( p2 );\n\t\tplanes[ 3 ].copy( p3 );\n\t\tplanes[ 4 ].copy( p4 );\n\t\tplanes[ 5 ].copy( p5 );\n\n\t\treturn this;\n\n\t}\n\n\tcopy( frustum ) {\n\n\t\tconst planes = this.planes;\n\n\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\tplanes[ i ].copy( frustum.planes[ i ] );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tsetFromProjectionMatrix( m ) {\n\n\t\tconst planes = this.planes;\n\t\tconst me = m.elements;\n\t\tconst me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];\n\t\tconst me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];\n\t\tconst me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];\n\t\tconst me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];\n\n\t\tplanes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();\n\t\tplanes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();\n\t\tplanes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();\n\t\tplanes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();\n\t\tplanes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();\n\t\tplanes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();\n\n\t\treturn this;\n\n\t}\n\n\tintersectsObject( object ) {\n\n\t\tif ( object.boundingSphere !== undefined ) {\n\n\t\t\tif ( object.boundingSphere === null ) object.computeBoundingSphere();\n\n\t\t\t_sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );\n\n\t\t} else {\n\n\t\t\tconst geometry = object.geometry;\n\n\t\t\tif ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();\n\n\t\t\t_sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );\n\n\t\t}\n\n\t\treturn this.intersectsSphere( _sphere$3 );\n\n\t}\n\n\tintersectsSprite( sprite ) {\n\n\t\t_sphere$3.center.set( 0, 0, 0 );\n\t\t_sphere$3.radius = 0.7071067811865476;\n\t\t_sphere$3.applyMatrix4( sprite.matrixWorld );\n\n\t\treturn this.intersectsSphere( _sphere$3 );\n\n\t}\n\n\tintersectsSphere( sphere ) {\n\n\t\tconst planes = this.planes;\n\t\tconst center = sphere.center;\n\t\tconst negRadius = - sphere.radius;\n\n\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\tconst distance = planes[ i ].distanceToPoint( center );\n\n\t\t\tif ( distance < negRadius ) {\n\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\tintersectsBox( box ) {\n\n\t\tconst planes = this.planes;\n\n\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\tconst plane = planes[ i ];\n\n\t\t\t// corner at max distance\n\n\t\t\t_vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;\n\t\t\t_vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;\n\t\t\t_vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;\n\n\t\t\tif ( plane.distanceToPoint( _vector$6 ) < 0 ) {\n\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\tcontainsPoint( point ) {\n\n\t\tconst planes = this.planes;\n\n\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\tif ( planes[ i ].distanceToPoint( point ) < 0 ) {\n\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n}\n\nfunction WebGLAnimation() {\n\n\tlet context = null;\n\tlet isAnimating = false;\n\tlet animationLoop = null;\n\tlet requestId = null;\n\n\tfunction onAnimationFrame( time, frame ) {\n\n\t\tanimationLoop( time, frame );\n\n\t\trequestId = context.requestAnimationFrame( onAnimationFrame );\n\n\t}\n\n\treturn {\n\n\t\tstart: function () {\n\n\t\t\tif ( isAnimating === true ) return;\n\t\t\tif ( animationLoop === null ) return;\n\n\t\t\trequestId = context.requestAnimationFrame( onAnimationFrame );\n\n\t\t\tisAnimating = true;\n\n\t\t},\n\n\t\tstop: function () {\n\n\t\t\tcontext.cancelAnimationFrame( requestId );\n\n\t\t\tisAnimating = false;\n\n\t\t},\n\n\t\tsetAnimationLoop: function ( callback ) {\n\n\t\t\tanimationLoop = callback;\n\n\t\t},\n\n\t\tsetContext: function ( value ) {\n\n\t\t\tcontext = value;\n\n\t\t}\n\n\t};\n\n}\n\nfunction WebGLAttributes( gl, capabilities ) {\n\n\tconst isWebGL2 = capabilities.isWebGL2;\n\n\tconst buffers = new WeakMap();\n\n\tfunction createBuffer( attribute, bufferType ) {\n\n\t\tconst array = attribute.array;\n\t\tconst usage = attribute.usage;\n\n\t\tconst buffer = gl.createBuffer();\n\n\t\tgl.bindBuffer( bufferType, buffer );\n\t\tgl.bufferData( bufferType, array, usage );\n\n\t\tattribute.onUploadCallback();\n\n\t\tlet type;\n\n\t\tif ( array instanceof Float32Array ) {\n\n\t\t\ttype = gl.FLOAT;\n\n\t\t} else if ( array instanceof Uint16Array ) {\n\n\t\t\tif ( attribute.isFloat16BufferAttribute ) {\n\n\t\t\t\tif ( isWebGL2 ) {\n\n\t\t\t\t\ttype = gl.HALF_FLOAT;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tthrow new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\ttype = gl.UNSIGNED_SHORT;\n\n\t\t\t}\n\n\t\t} else if ( array instanceof Int16Array ) {\n\n\t\t\ttype = gl.SHORT;\n\n\t\t} else if ( array instanceof Uint32Array ) {\n\n\t\t\ttype = gl.UNSIGNED_INT;\n\n\t\t} else if ( array instanceof Int32Array ) {\n\n\t\t\ttype = gl.INT;\n\n\t\t} else if ( array instanceof Int8Array ) {\n\n\t\t\ttype = gl.BYTE;\n\n\t\t} else if ( array instanceof Uint8Array ) {\n\n\t\t\ttype = gl.UNSIGNED_BYTE;\n\n\t\t} else if ( array instanceof Uint8ClampedArray ) {\n\n\t\t\ttype = gl.UNSIGNED_BYTE;\n\n\t\t} else {\n\n\t\t\tthrow new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );\n\n\t\t}\n\n\t\treturn {\n\t\t\tbuffer: buffer,\n\t\t\ttype: type,\n\t\t\tbytesPerElement: array.BYTES_PER_ELEMENT,\n\t\t\tversion: attribute.version\n\t\t};\n\n\t}\n\n\tfunction updateBuffer( buffer, attribute, bufferType ) {\n\n\t\tconst array = attribute.array;\n\t\tconst updateRange = attribute.updateRange;\n\n\t\tgl.bindBuffer( bufferType, buffer );\n\n\t\tif ( updateRange.count === - 1 ) {\n\n\t\t\t// Not using update ranges\n\n\t\t\tgl.bufferSubData( bufferType, 0, array );\n\n\t\t} else {\n\n\t\t\tif ( isWebGL2 ) {\n\n\t\t\t\tgl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,\n\t\t\t\t\tarray, updateRange.offset, updateRange.count );\n\n\t\t\t} else {\n\n\t\t\t\tgl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,\n\t\t\t\t\tarray.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );\n\n\t\t\t}\n\n\t\t\tupdateRange.count = - 1; // reset range\n\n\t\t}\n\n\t\tattribute.onUploadCallback();\n\n\t}\n\n\t//\n\n\tfunction get( attribute ) {\n\n\t\tif ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;\n\n\t\treturn buffers.get( attribute );\n\n\t}\n\n\tfunction remove( attribute ) {\n\n\t\tif ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;\n\n\t\tconst data = buffers.get( attribute );\n\n\t\tif ( data ) {\n\n\t\t\tgl.deleteBuffer( data.buffer );\n\n\t\t\tbuffers.delete( attribute );\n\n\t\t}\n\n\t}\n\n\tfunction update( attribute, bufferType ) {\n\n\t\tif ( attribute.isGLBufferAttribute ) {\n\n\t\t\tconst cached = buffers.get( attribute );\n\n\t\t\tif ( ! cached || cached.version < attribute.version ) {\n\n\t\t\t\tbuffers.set( attribute, {\n\t\t\t\t\tbuffer: attribute.buffer,\n\t\t\t\t\ttype: attribute.type,\n\t\t\t\t\tbytesPerElement: attribute.elementSize,\n\t\t\t\t\tversion: attribute.version\n\t\t\t\t} );\n\n\t\t\t}\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tif ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;\n\n\t\tconst data = buffers.get( attribute );\n\n\t\tif ( data === undefined ) {\n\n\t\t\tbuffers.set( attribute, createBuffer( attribute, bufferType ) );\n\n\t\t} else if ( data.version < attribute.version ) {\n\n\t\t\tupdateBuffer( data.buffer, attribute, bufferType );\n\n\t\t\tdata.version = attribute.version;\n\n\t\t}\n\n\t}\n\n\treturn {\n\n\t\tget: get,\n\t\tremove: remove,\n\t\tupdate: update\n\n\t};\n\n}\n\nclass PlaneGeometry extends BufferGeometry {\n\n\tconstructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'PlaneGeometry';\n\n\t\tthis.parameters = {\n\t\t\twidth: width,\n\t\t\theight: height,\n\t\t\twidthSegments: widthSegments,\n\t\t\theightSegments: heightSegments\n\t\t};\n\n\t\tconst width_half = width / 2;\n\t\tconst height_half = height / 2;\n\n\t\tconst gridX = Math.floor( widthSegments );\n\t\tconst gridY = Math.floor( heightSegments );\n\n\t\tconst gridX1 = gridX + 1;\n\t\tconst gridY1 = gridY + 1;\n\n\t\tconst segment_width = width / gridX;\n\t\tconst segment_height = height / gridY;\n\n\t\t//\n\n\t\tconst indices = [];\n\t\tconst vertices = [];\n\t\tconst normals = [];\n\t\tconst uvs = [];\n\n\t\tfor ( let iy = 0; iy < gridY1; iy ++ ) {\n\n\t\t\tconst y = iy * segment_height - height_half;\n\n\t\t\tfor ( let ix = 0; ix < gridX1; ix ++ ) {\n\n\t\t\t\tconst x = ix * segment_width - width_half;\n\n\t\t\t\tvertices.push( x, - y, 0 );\n\n\t\t\t\tnormals.push( 0, 0, 1 );\n\n\t\t\t\tuvs.push( ix / gridX );\n\t\t\t\tuvs.push( 1 - ( iy / gridY ) );\n\n\t\t\t}\n\n\t\t}\n\n\t\tfor ( let iy = 0; iy < gridY; iy ++ ) {\n\n\t\t\tfor ( let ix = 0; ix < gridX; ix ++ ) {\n\n\t\t\t\tconst a = ix + gridX1 * iy;\n\t\t\t\tconst b = ix + gridX1 * ( iy + 1 );\n\t\t\t\tconst c = ( ix + 1 ) + gridX1 * ( iy + 1 );\n\t\t\t\tconst d = ( ix + 1 ) + gridX1 * iy;\n\n\t\t\t\tindices.push( a, b, d );\n\t\t\t\tindices.push( b, c, d );\n\n\t\t\t}\n\n\t\t}\n\n\t\tthis.setIndex( indices );\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tthis.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );\n\n\t}\n\n}\n\nvar alphamap_fragment = \"#ifdef USE_ALPHAMAP\\n\\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\\n#endif\";\n\nvar alphamap_pars_fragment = \"#ifdef USE_ALPHAMAP\\n\\tuniform sampler2D alphaMap;\\n#endif\";\n\nvar alphatest_fragment = \"#ifdef USE_ALPHATEST\\n\\tif ( diffuseColor.a < alphaTest ) discard;\\n#endif\";\n\nvar alphatest_pars_fragment = \"#ifdef USE_ALPHATEST\\n\\tuniform float alphaTest;\\n#endif\";\n\nvar aomap_fragment = \"#ifdef USE_AOMAP\\n\\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\\n\\treflectedLight.indirectDiffuse *= ambientOcclusion;\\n\\t#if defined( USE_ENVMAP ) && defined( STANDARD )\\n\\t\\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\\n\\t\\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\\n\\t#endif\\n#endif\";\n\nvar aomap_pars_fragment = \"#ifdef USE_AOMAP\\n\\tuniform sampler2D aoMap;\\n\\tuniform float aoMapIntensity;\\n#endif\";\n\nvar begin_vertex = \"vec3 transformed = vec3( position );\";\n\nvar beginnormal_vertex = \"vec3 objectNormal = vec3( normal );\\n#ifdef USE_TANGENT\\n\\tvec3 objectTangent = vec3( tangent.xyz );\\n#endif\";\n\nvar bsdfs = \"float G_BlinnPhong_Implicit( ) {\\n\\treturn 0.25;\\n}\\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\\n\\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\\n}\\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\\n\\tvec3 halfDir = normalize( lightDir + viewDir );\\n\\tfloat dotNH = saturate( dot( normal, halfDir ) );\\n\\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\\n\\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\\n\\tfloat G = G_BlinnPhong_Implicit( );\\n\\tfloat D = D_BlinnPhong( shininess, dotNH );\\n\\treturn F * ( G * D );\\n} // validated\";\n\nvar iridescence_fragment = \"#ifdef USE_IRIDESCENCE\\n\\tconst mat3 XYZ_TO_REC709 = mat3(\\n\\t\\t 3.2404542, -0.9692660, 0.0556434,\\n\\t\\t-1.5371385, 1.8760108, -0.2040259,\\n\\t\\t-0.4985314, 0.0415560, 1.0572252\\n\\t);\\n\\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\\n\\t\\tvec3 sqrtF0 = sqrt( fresnel0 );\\n\\t\\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\\n\\t}\\n\\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\\n\\t\\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\\n\\t}\\n\\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\\n\\t\\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\\n\\t}\\n\\tvec3 evalSensitivity( float OPD, vec3 shift ) {\\n\\t\\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\\n\\t\\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\\n\\t\\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\\n\\t\\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\\n\\t\\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\\n\\t\\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\\n\\t\\txyz /= 1.0685e-7;\\n\\t\\tvec3 rgb = XYZ_TO_REC709 * xyz;\\n\\t\\treturn rgb;\\n\\t}\\n\\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\\n\\t\\tvec3 I;\\n\\t\\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\\n\\t\\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\\n\\t\\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\\n\\t\\tif ( cosTheta2Sq < 0.0 ) {\\n\\t\\t\\t return vec3( 1.0 );\\n\\t\\t}\\n\\t\\tfloat cosTheta2 = sqrt( cosTheta2Sq );\\n\\t\\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\\n\\t\\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\\n\\t\\tfloat R21 = R12;\\n\\t\\tfloat T121 = 1.0 - R12;\\n\\t\\tfloat phi12 = 0.0;\\n\\t\\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\\n\\t\\tfloat phi21 = PI - phi12;\\n\\t\\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\\t\\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\\n\\t\\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\\n\\t\\tvec3 phi23 = vec3( 0.0 );\\n\\t\\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\\n\\t\\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\\n\\t\\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\\n\\t\\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\\n\\t\\tvec3 phi = vec3( phi21 ) + phi23;\\n\\t\\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\\n\\t\\tvec3 r123 = sqrt( R123 );\\n\\t\\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\\n\\t\\tvec3 C0 = R12 + Rs;\\n\\t\\tI = C0;\\n\\t\\tvec3 Cm = Rs - T121;\\n\\t\\tfor ( int m = 1; m <= 2; ++ m ) {\\n\\t\\t\\tCm *= r123;\\n\\t\\t\\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\\n\\t\\t\\tI += Cm * Sm;\\n\\t\\t}\\n\\t\\treturn max( I, vec3( 0.0 ) );\\n\\t}\\n#endif\";\n\nvar bumpmap_pars_fragment = \"#ifdef USE_BUMPMAP\\n\\tuniform sampler2D bumpMap;\\n\\tuniform float bumpScale;\\n\\tvec2 dHdxy_fwd() {\\n\\t\\tvec2 dSTdx = dFdx( vBumpMapUv );\\n\\t\\tvec2 dSTdy = dFdy( vBumpMapUv );\\n\\t\\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\\n\\t\\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\\n\\t\\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\\n\\t\\treturn vec2( dBx, dBy );\\n\\t}\\n\\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\\n\\t\\tvec3 vSigmaX = dFdx( surf_pos.xyz );\\n\\t\\tvec3 vSigmaY = dFdy( surf_pos.xyz );\\n\\t\\tvec3 vN = surf_norm;\\n\\t\\tvec3 R1 = cross( vSigmaY, vN );\\n\\t\\tvec3 R2 = cross( vN, vSigmaX );\\n\\t\\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\\n\\t\\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\\n\\t\\treturn normalize( abs( fDet ) * surf_norm - vGrad );\\n\\t}\\n#endif\";\n\nvar clipping_planes_fragment = \"#if NUM_CLIPPING_PLANES > 0\\n\\tvec4 plane;\\n\\t#pragma unroll_loop_start\\n\\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\\n\\t\\tplane = clippingPlanes[ i ];\\n\\t\\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\\n\\t}\\n\\t#pragma unroll_loop_end\\n\\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\\n\\t\\tbool clipped = true;\\n\\t\\t#pragma unroll_loop_start\\n\\t\\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\\n\\t\\t\\tplane = clippingPlanes[ i ];\\n\\t\\t\\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\\n\\t\\t}\\n\\t\\t#pragma unroll_loop_end\\n\\t\\tif ( clipped ) discard;\\n\\t#endif\\n#endif\";\n\nvar clipping_planes_pars_fragment = \"#if NUM_CLIPPING_PLANES > 0\\n\\tvarying vec3 vClipPosition;\\n\\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\\n#endif\";\n\nvar clipping_planes_pars_vertex = \"#if NUM_CLIPPING_PLANES > 0\\n\\tvarying vec3 vClipPosition;\\n#endif\";\n\nvar clipping_planes_vertex = \"#if NUM_CLIPPING_PLANES > 0\\n\\tvClipPosition = - mvPosition.xyz;\\n#endif\";\n\nvar color_fragment = \"#if defined( USE_COLOR_ALPHA )\\n\\tdiffuseColor *= vColor;\\n#elif defined( USE_COLOR )\\n\\tdiffuseColor.rgb *= vColor;\\n#endif\";\n\nvar color_pars_fragment = \"#if defined( USE_COLOR_ALPHA )\\n\\tvarying vec4 vColor;\\n#elif defined( USE_COLOR )\\n\\tvarying vec3 vColor;\\n#endif\";\n\nvar color_pars_vertex = \"#if defined( USE_COLOR_ALPHA )\\n\\tvarying vec4 vColor;\\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\\n\\tvarying vec3 vColor;\\n#endif\";\n\nvar color_vertex = \"#if defined( USE_COLOR_ALPHA )\\n\\tvColor = vec4( 1.0 );\\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\\n\\tvColor = vec3( 1.0 );\\n#endif\\n#ifdef USE_COLOR\\n\\tvColor *= color;\\n#endif\\n#ifdef USE_INSTANCING_COLOR\\n\\tvColor.xyz *= instanceColor.xyz;\\n#endif\";\n\nvar common = \"#define PI 3.141592653589793\\n#define PI2 6.283185307179586\\n#define PI_HALF 1.5707963267948966\\n#define RECIPROCAL_PI 0.3183098861837907\\n#define RECIPROCAL_PI2 0.15915494309189535\\n#define EPSILON 1e-6\\n#ifndef saturate\\n#define saturate( a ) clamp( a, 0.0, 1.0 )\\n#endif\\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\\nfloat pow2( const in float x ) { return x*x; }\\nvec3 pow2( const in vec3 x ) { return x*x; }\\nfloat pow3( const in float x ) { return x*x*x; }\\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\\nhighp float rand( const in vec2 uv ) {\\n\\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\\n\\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\\n\\treturn fract( sin( sn ) * c );\\n}\\n#ifdef HIGH_PRECISION\\n\\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\\n#else\\n\\tfloat precisionSafeLength( vec3 v ) {\\n\\t\\tfloat maxComponent = max3( abs( v ) );\\n\\t\\treturn length( v / maxComponent ) * maxComponent;\\n\\t}\\n#endif\\nstruct IncidentLight {\\n\\tvec3 color;\\n\\tvec3 direction;\\n\\tbool visible;\\n};\\nstruct ReflectedLight {\\n\\tvec3 directDiffuse;\\n\\tvec3 directSpecular;\\n\\tvec3 indirectDiffuse;\\n\\tvec3 indirectSpecular;\\n};\\nstruct GeometricContext {\\n\\tvec3 position;\\n\\tvec3 normal;\\n\\tvec3 viewDir;\\n#ifdef USE_CLEARCOAT\\n\\tvec3 clearcoatNormal;\\n#endif\\n};\\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\\n\\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\\n}\\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\\n\\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\\n}\\nmat3 transposeMat3( const in mat3 m ) {\\n\\tmat3 tmp;\\n\\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\\n\\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\\n\\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\\n\\treturn tmp;\\n}\\nfloat luminance( const in vec3 rgb ) {\\n\\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\\n\\treturn dot( weights, rgb );\\n}\\nbool isPerspectiveMatrix( mat4 m ) {\\n\\treturn m[ 2 ][ 3 ] == - 1.0;\\n}\\nvec2 equirectUv( in vec3 dir ) {\\n\\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\\n\\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\\n\\treturn vec2( u, v );\\n}\\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\\n\\treturn RECIPROCAL_PI * diffuseColor;\\n}\\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\\n\\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\\n\\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\\n}\\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\\n\\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\\n\\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\\n} // validated\";\n\nvar cube_uv_reflection_fragment = \"#ifdef ENVMAP_TYPE_CUBE_UV\\n\\t#define cubeUV_minMipLevel 4.0\\n\\t#define cubeUV_minTileSize 16.0\\n\\tfloat getFace( vec3 direction ) {\\n\\t\\tvec3 absDirection = abs( direction );\\n\\t\\tfloat face = - 1.0;\\n\\t\\tif ( absDirection.x > absDirection.z ) {\\n\\t\\t\\tif ( absDirection.x > absDirection.y )\\n\\t\\t\\t\\tface = direction.x > 0.0 ? 0.0 : 3.0;\\n\\t\\t\\telse\\n\\t\\t\\t\\tface = direction.y > 0.0 ? 1.0 : 4.0;\\n\\t\\t} else {\\n\\t\\t\\tif ( absDirection.z > absDirection.y )\\n\\t\\t\\t\\tface = direction.z > 0.0 ? 2.0 : 5.0;\\n\\t\\t\\telse\\n\\t\\t\\t\\tface = direction.y > 0.0 ? 1.0 : 4.0;\\n\\t\\t}\\n\\t\\treturn face;\\n\\t}\\n\\tvec2 getUV( vec3 direction, float face ) {\\n\\t\\tvec2 uv;\\n\\t\\tif ( face == 0.0 ) {\\n\\t\\t\\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\\n\\t\\t} else if ( face == 1.0 ) {\\n\\t\\t\\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\\n\\t\\t} else if ( face == 2.0 ) {\\n\\t\\t\\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\\n\\t\\t} else if ( face == 3.0 ) {\\n\\t\\t\\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\\n\\t\\t} else if ( face == 4.0 ) {\\n\\t\\t\\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\\n\\t\\t} else {\\n\\t\\t\\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\\n\\t\\t}\\n\\t\\treturn 0.5 * ( uv + 1.0 );\\n\\t}\\n\\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\\n\\t\\tfloat face = getFace( direction );\\n\\t\\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\\n\\t\\tmipInt = max( mipInt, cubeUV_minMipLevel );\\n\\t\\tfloat faceSize = exp2( mipInt );\\n\\t\\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\\n\\t\\tif ( face > 2.0 ) {\\n\\t\\t\\tuv.y += faceSize;\\n\\t\\t\\tface -= 3.0;\\n\\t\\t}\\n\\t\\tuv.x += face * faceSize;\\n\\t\\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\\n\\t\\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\\n\\t\\tuv.x *= CUBEUV_TEXEL_WIDTH;\\n\\t\\tuv.y *= CUBEUV_TEXEL_HEIGHT;\\n\\t\\t#ifdef texture2DGradEXT\\n\\t\\t\\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\\n\\t\\t#else\\n\\t\\t\\treturn texture2D( envMap, uv ).rgb;\\n\\t\\t#endif\\n\\t}\\n\\t#define cubeUV_r0 1.0\\n\\t#define cubeUV_v0 0.339\\n\\t#define cubeUV_m0 - 2.0\\n\\t#define cubeUV_r1 0.8\\n\\t#define cubeUV_v1 0.276\\n\\t#define cubeUV_m1 - 1.0\\n\\t#define cubeUV_r4 0.4\\n\\t#define cubeUV_v4 0.046\\n\\t#define cubeUV_m4 2.0\\n\\t#define cubeUV_r5 0.305\\n\\t#define cubeUV_v5 0.016\\n\\t#define cubeUV_m5 3.0\\n\\t#define cubeUV_r6 0.21\\n\\t#define cubeUV_v6 0.0038\\n\\t#define cubeUV_m6 4.0\\n\\tfloat roughnessToMip( float roughness ) {\\n\\t\\tfloat mip = 0.0;\\n\\t\\tif ( roughness >= cubeUV_r1 ) {\\n\\t\\t\\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\\n\\t\\t} else if ( roughness >= cubeUV_r4 ) {\\n\\t\\t\\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\\n\\t\\t} else if ( roughness >= cubeUV_r5 ) {\\n\\t\\t\\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\\n\\t\\t} else if ( roughness >= cubeUV_r6 ) {\\n\\t\\t\\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\\n\\t\\t} else {\\n\\t\\t\\tmip = - 2.0 * log2( 1.16 * roughness );\\t\\t}\\n\\t\\treturn mip;\\n\\t}\\n\\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\\n\\t\\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\\n\\t\\tfloat mipF = fract( mip );\\n\\t\\tfloat mipInt = floor( mip );\\n\\t\\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\\n\\t\\tif ( mipF == 0.0 ) {\\n\\t\\t\\treturn vec4( color0, 1.0 );\\n\\t\\t} else {\\n\\t\\t\\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\\n\\t\\t\\treturn vec4( mix( color0, color1, mipF ), 1.0 );\\n\\t\\t}\\n\\t}\\n#endif\";\n\nvar defaultnormal_vertex = \"vec3 transformedNormal = objectNormal;\\n#ifdef USE_INSTANCING\\n\\tmat3 m = mat3( instanceMatrix );\\n\\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\\n\\ttransformedNormal = m * transformedNormal;\\n#endif\\ntransformedNormal = normalMatrix * transformedNormal;\\n#ifdef FLIP_SIDED\\n\\ttransformedNormal = - transformedNormal;\\n#endif\\n#ifdef USE_TANGENT\\n\\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\\n\\t#ifdef FLIP_SIDED\\n\\t\\ttransformedTangent = - transformedTangent;\\n\\t#endif\\n#endif\";\n\nvar displacementmap_pars_vertex = \"#ifdef USE_DISPLACEMENTMAP\\n\\tuniform sampler2D displacementMap;\\n\\tuniform float displacementScale;\\n\\tuniform float displacementBias;\\n#endif\";\n\nvar displacementmap_vertex = \"#ifdef USE_DISPLACEMENTMAP\\n\\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\\n#endif\";\n\nvar emissivemap_fragment = \"#ifdef USE_EMISSIVEMAP\\n\\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\\n\\ttotalEmissiveRadiance *= emissiveColor.rgb;\\n#endif\";\n\nvar emissivemap_pars_fragment = \"#ifdef USE_EMISSIVEMAP\\n\\tuniform sampler2D emissiveMap;\\n#endif\";\n\nvar encodings_fragment = \"gl_FragColor = linearToOutputTexel( gl_FragColor );\";\n\nvar encodings_pars_fragment = \"vec4 LinearToLinear( in vec4 value ) {\\n\\treturn value;\\n}\\nvec4 LinearTosRGB( in vec4 value ) {\\n\\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\\n}\";\n\nvar envmap_fragment = \"#ifdef USE_ENVMAP\\n\\t#ifdef ENV_WORLDPOS\\n\\t\\tvec3 cameraToFrag;\\n\\t\\tif ( isOrthographic ) {\\n\\t\\t\\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\\n\\t\\t} else {\\n\\t\\t\\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\\n\\t\\t}\\n\\t\\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\\n\\t\\t#ifdef ENVMAP_MODE_REFLECTION\\n\\t\\t\\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\\n\\t\\t#else\\n\\t\\t\\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\\n\\t\\t#endif\\n\\t#else\\n\\t\\tvec3 reflectVec = vReflect;\\n\\t#endif\\n\\t#ifdef ENVMAP_TYPE_CUBE\\n\\t\\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\\n\\t#else\\n\\t\\tvec4 envColor = vec4( 0.0 );\\n\\t#endif\\n\\t#ifdef ENVMAP_BLENDING_MULTIPLY\\n\\t\\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\\n\\t#elif defined( ENVMAP_BLENDING_MIX )\\n\\t\\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\\n\\t#elif defined( ENVMAP_BLENDING_ADD )\\n\\t\\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\\n\\t#endif\\n#endif\";\n\nvar envmap_common_pars_fragment = \"#ifdef USE_ENVMAP\\n\\tuniform float envMapIntensity;\\n\\tuniform float flipEnvMap;\\n\\t#ifdef ENVMAP_TYPE_CUBE\\n\\t\\tuniform samplerCube envMap;\\n\\t#else\\n\\t\\tuniform sampler2D envMap;\\n\\t#endif\\n\\t\\n#endif\";\n\nvar envmap_pars_fragment = \"#ifdef USE_ENVMAP\\n\\tuniform float reflectivity;\\n\\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\\n\\t\\t#define ENV_WORLDPOS\\n\\t#endif\\n\\t#ifdef ENV_WORLDPOS\\n\\t\\tvarying vec3 vWorldPosition;\\n\\t\\tuniform float refractionRatio;\\n\\t#else\\n\\t\\tvarying vec3 vReflect;\\n\\t#endif\\n#endif\";\n\nvar envmap_pars_vertex = \"#ifdef USE_ENVMAP\\n\\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\\n\\t\\t#define ENV_WORLDPOS\\n\\t#endif\\n\\t#ifdef ENV_WORLDPOS\\n\\t\\t\\n\\t\\tvarying vec3 vWorldPosition;\\n\\t#else\\n\\t\\tvarying vec3 vReflect;\\n\\t\\tuniform float refractionRatio;\\n\\t#endif\\n#endif\";\n\nvar envmap_vertex = \"#ifdef USE_ENVMAP\\n\\t#ifdef ENV_WORLDPOS\\n\\t\\tvWorldPosition = worldPosition.xyz;\\n\\t#else\\n\\t\\tvec3 cameraToVertex;\\n\\t\\tif ( isOrthographic ) {\\n\\t\\t\\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\\n\\t\\t} else {\\n\\t\\t\\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\\n\\t\\t}\\n\\t\\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\\n\\t\\t#ifdef ENVMAP_MODE_REFLECTION\\n\\t\\t\\tvReflect = reflect( cameraToVertex, worldNormal );\\n\\t\\t#else\\n\\t\\t\\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\\n\\t\\t#endif\\n\\t#endif\\n#endif\";\n\nvar fog_vertex = \"#ifdef USE_FOG\\n\\tvFogDepth = - mvPosition.z;\\n#endif\";\n\nvar fog_pars_vertex = \"#ifdef USE_FOG\\n\\tvarying float vFogDepth;\\n#endif\";\n\nvar fog_fragment = \"#ifdef USE_FOG\\n\\t#ifdef FOG_EXP2\\n\\t\\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\\n\\t#else\\n\\t\\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\\n\\t#endif\\n\\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\\n#endif\";\n\nvar fog_pars_fragment = \"#ifdef USE_FOG\\n\\tuniform vec3 fogColor;\\n\\tvarying float vFogDepth;\\n\\t#ifdef FOG_EXP2\\n\\t\\tuniform float fogDensity;\\n\\t#else\\n\\t\\tuniform float fogNear;\\n\\t\\tuniform float fogFar;\\n\\t#endif\\n#endif\";\n\nvar gradientmap_pars_fragment = \"#ifdef USE_GRADIENTMAP\\n\\tuniform sampler2D gradientMap;\\n#endif\\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\\n\\tfloat dotNL = dot( normal, lightDirection );\\n\\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\\n\\t#ifdef USE_GRADIENTMAP\\n\\t\\treturn vec3( texture2D( gradientMap, coord ).r );\\n\\t#else\\n\\t\\tvec2 fw = fwidth( coord ) * 0.5;\\n\\t\\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\\n\\t#endif\\n}\";\n\nvar lightmap_fragment = \"#ifdef USE_LIGHTMAP\\n\\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\\n\\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\\n\\treflectedLight.indirectDiffuse += lightMapIrradiance;\\n#endif\";\n\nvar lightmap_pars_fragment = \"#ifdef USE_LIGHTMAP\\n\\tuniform sampler2D lightMap;\\n\\tuniform float lightMapIntensity;\\n#endif\";\n\nvar lights_lambert_fragment = \"LambertMaterial material;\\nmaterial.diffuseColor = diffuseColor.rgb;\\nmaterial.specularStrength = specularStrength;\";\n\nvar lights_lambert_pars_fragment = \"varying vec3 vViewPosition;\\nstruct LambertMaterial {\\n\\tvec3 diffuseColor;\\n\\tfloat specularStrength;\\n};\\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\\n\\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\\n\\tvec3 irradiance = dotNL * directLight.color;\\n\\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\\n}\\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\\n\\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\\n}\\n#define RE_Direct\\t\\t\\t\\tRE_Direct_Lambert\\n#define RE_IndirectDiffuse\\t\\tRE_IndirectDiffuse_Lambert\";\n\nvar lights_pars_begin = \"uniform bool receiveShadow;\\nuniform vec3 ambientLightColor;\\nuniform vec3 lightProbe[ 9 ];\\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\\n\\tfloat x = normal.x, y = normal.y, z = normal.z;\\n\\tvec3 result = shCoefficients[ 0 ] * 0.886227;\\n\\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\\n\\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\\n\\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\\n\\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\\n\\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\\n\\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\\n\\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\\n\\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\\n\\treturn result;\\n}\\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\\n\\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\\n\\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\\n\\treturn irradiance;\\n}\\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\\n\\tvec3 irradiance = ambientLightColor;\\n\\treturn irradiance;\\n}\\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\\n\\t#if defined ( LEGACY_LIGHTS )\\n\\t\\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\\n\\t\\t\\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\\n\\t\\t}\\n\\t\\treturn 1.0;\\n\\t#else\\n\\t\\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\\n\\t\\tif ( cutoffDistance > 0.0 ) {\\n\\t\\t\\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\\n\\t\\t}\\n\\t\\treturn distanceFalloff;\\n\\t#endif\\n}\\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\\n\\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\\n}\\n#if NUM_DIR_LIGHTS > 0\\n\\tstruct DirectionalLight {\\n\\t\\tvec3 direction;\\n\\t\\tvec3 color;\\n\\t};\\n\\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\\n\\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\\n\\t\\tlight.color = directionalLight.color;\\n\\t\\tlight.direction = directionalLight.direction;\\n\\t\\tlight.visible = true;\\n\\t}\\n#endif\\n#if NUM_POINT_LIGHTS > 0\\n\\tstruct PointLight {\\n\\t\\tvec3 position;\\n\\t\\tvec3 color;\\n\\t\\tfloat distance;\\n\\t\\tfloat decay;\\n\\t};\\n\\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\\n\\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\\n\\t\\tvec3 lVector = pointLight.position - geometry.position;\\n\\t\\tlight.direction = normalize( lVector );\\n\\t\\tfloat lightDistance = length( lVector );\\n\\t\\tlight.color = pointLight.color;\\n\\t\\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\\n\\t\\tlight.visible = ( light.color != vec3( 0.0 ) );\\n\\t}\\n#endif\\n#if NUM_SPOT_LIGHTS > 0\\n\\tstruct SpotLight {\\n\\t\\tvec3 position;\\n\\t\\tvec3 direction;\\n\\t\\tvec3 color;\\n\\t\\tfloat distance;\\n\\t\\tfloat decay;\\n\\t\\tfloat coneCos;\\n\\t\\tfloat penumbraCos;\\n\\t};\\n\\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\\n\\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\\n\\t\\tvec3 lVector = spotLight.position - geometry.position;\\n\\t\\tlight.direction = normalize( lVector );\\n\\t\\tfloat angleCos = dot( light.direction, spotLight.direction );\\n\\t\\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\\n\\t\\tif ( spotAttenuation > 0.0 ) {\\n\\t\\t\\tfloat lightDistance = length( lVector );\\n\\t\\t\\tlight.color = spotLight.color * spotAttenuation;\\n\\t\\t\\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\\n\\t\\t\\tlight.visible = ( light.color != vec3( 0.0 ) );\\n\\t\\t} else {\\n\\t\\t\\tlight.color = vec3( 0.0 );\\n\\t\\t\\tlight.visible = false;\\n\\t\\t}\\n\\t}\\n#endif\\n#if NUM_RECT_AREA_LIGHTS > 0\\n\\tstruct RectAreaLight {\\n\\t\\tvec3 color;\\n\\t\\tvec3 position;\\n\\t\\tvec3 halfWidth;\\n\\t\\tvec3 halfHeight;\\n\\t};\\n\\tuniform sampler2D ltc_1;\\tuniform sampler2D ltc_2;\\n\\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\\n#endif\\n#if NUM_HEMI_LIGHTS > 0\\n\\tstruct HemisphereLight {\\n\\t\\tvec3 direction;\\n\\t\\tvec3 skyColor;\\n\\t\\tvec3 groundColor;\\n\\t};\\n\\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\\n\\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\\n\\t\\tfloat dotNL = dot( normal, hemiLight.direction );\\n\\t\\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\\n\\t\\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\\n\\t\\treturn irradiance;\\n\\t}\\n#endif\";\n\nvar envmap_physical_pars_fragment = \"#if defined( USE_ENVMAP )\\n\\tvec3 getIBLIrradiance( const in vec3 normal ) {\\n\\t\\t#if defined( ENVMAP_TYPE_CUBE_UV )\\n\\t\\t\\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\\n\\t\\t\\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\\n\\t\\t\\treturn PI * envMapColor.rgb * envMapIntensity;\\n\\t\\t#else\\n\\t\\t\\treturn vec3( 0.0 );\\n\\t\\t#endif\\n\\t}\\n\\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\\n\\t\\t#if defined( ENVMAP_TYPE_CUBE_UV )\\n\\t\\t\\tvec3 reflectVec = reflect( - viewDir, normal );\\n\\t\\t\\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\\n\\t\\t\\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\\n\\t\\t\\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\\n\\t\\t\\treturn envMapColor.rgb * envMapIntensity;\\n\\t\\t#else\\n\\t\\t\\treturn vec3( 0.0 );\\n\\t\\t#endif\\n\\t}\\n#endif\";\n\nvar lights_toon_fragment = \"ToonMaterial material;\\nmaterial.diffuseColor = diffuseColor.rgb;\";\n\nvar lights_toon_pars_fragment = \"varying vec3 vViewPosition;\\nstruct ToonMaterial {\\n\\tvec3 diffuseColor;\\n};\\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\\n\\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\\n\\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\\n}\\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\\n\\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\\n}\\n#define RE_Direct\\t\\t\\t\\tRE_Direct_Toon\\n#define RE_IndirectDiffuse\\t\\tRE_IndirectDiffuse_Toon\";\n\nvar lights_phong_fragment = \"BlinnPhongMaterial material;\\nmaterial.diffuseColor = diffuseColor.rgb;\\nmaterial.specularColor = specular;\\nmaterial.specularShininess = shininess;\\nmaterial.specularStrength = specularStrength;\";\n\nvar lights_phong_pars_fragment = \"varying vec3 vViewPosition;\\nstruct BlinnPhongMaterial {\\n\\tvec3 diffuseColor;\\n\\tvec3 specularColor;\\n\\tfloat specularShininess;\\n\\tfloat specularStrength;\\n};\\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\\n\\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\\n\\tvec3 irradiance = dotNL * directLight.color;\\n\\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\\n\\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\\n}\\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\\n\\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\\n}\\n#define RE_Direct\\t\\t\\t\\tRE_Direct_BlinnPhong\\n#define RE_IndirectDiffuse\\t\\tRE_IndirectDiffuse_BlinnPhong\";\n\nvar lights_physical_fragment = \"PhysicalMaterial material;\\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\\nmaterial.roughness = min( material.roughness, 1.0 );\\n#ifdef IOR\\n\\tmaterial.ior = ior;\\n\\t#ifdef USE_SPECULAR\\n\\t\\tfloat specularIntensityFactor = specularIntensity;\\n\\t\\tvec3 specularColorFactor = specularColor;\\n\\t\\t#ifdef USE_SPECULAR_COLORMAP\\n\\t\\t\\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\\n\\t\\t#endif\\n\\t\\t#ifdef USE_SPECULAR_INTENSITYMAP\\n\\t\\t\\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\\n\\t\\t#endif\\n\\t\\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\\n\\t#else\\n\\t\\tfloat specularIntensityFactor = 1.0;\\n\\t\\tvec3 specularColorFactor = vec3( 1.0 );\\n\\t\\tmaterial.specularF90 = 1.0;\\n\\t#endif\\n\\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\\n#else\\n\\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\\n\\tmaterial.specularF90 = 1.0;\\n#endif\\n#ifdef USE_CLEARCOAT\\n\\tmaterial.clearcoat = clearcoat;\\n\\tmaterial.clearcoatRoughness = clearcoatRoughness;\\n\\tmaterial.clearcoatF0 = vec3( 0.04 );\\n\\tmaterial.clearcoatF90 = 1.0;\\n\\t#ifdef USE_CLEARCOATMAP\\n\\t\\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\\n\\t#endif\\n\\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\\n\\t\\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\\n\\t#endif\\n\\tmaterial.clearcoat = saturate( material.clearcoat );\\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\\n\\tmaterial.clearcoatRoughness += geometryRoughness;\\n\\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\\n#endif\\n#ifdef USE_IRIDESCENCE\\n\\tmaterial.iridescence = iridescence;\\n\\tmaterial.iridescenceIOR = iridescenceIOR;\\n\\t#ifdef USE_IRIDESCENCEMAP\\n\\t\\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\\n\\t#endif\\n\\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\\n\\t\\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\\n\\t#else\\n\\t\\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\\n\\t#endif\\n#endif\\n#ifdef USE_SHEEN\\n\\tmaterial.sheenColor = sheenColor;\\n\\t#ifdef USE_SHEEN_COLORMAP\\n\\t\\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\\n\\t#endif\\n\\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\\n\\t#ifdef USE_SHEEN_ROUGHNESSMAP\\n\\t\\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\\n\\t#endif\\n#endif\";\n\nvar lights_physical_pars_fragment = \"struct PhysicalMaterial {\\n\\tvec3 diffuseColor;\\n\\tfloat roughness;\\n\\tvec3 specularColor;\\n\\tfloat specularF90;\\n\\t#ifdef USE_CLEARCOAT\\n\\t\\tfloat clearcoat;\\n\\t\\tfloat clearcoatRoughness;\\n\\t\\tvec3 clearcoatF0;\\n\\t\\tfloat clearcoatF90;\\n\\t#endif\\n\\t#ifdef USE_IRIDESCENCE\\n\\t\\tfloat iridescence;\\n\\t\\tfloat iridescenceIOR;\\n\\t\\tfloat iridescenceThickness;\\n\\t\\tvec3 iridescenceFresnel;\\n\\t\\tvec3 iridescenceF0;\\n\\t#endif\\n\\t#ifdef USE_SHEEN\\n\\t\\tvec3 sheenColor;\\n\\t\\tfloat sheenRoughness;\\n\\t#endif\\n\\t#ifdef IOR\\n\\t\\tfloat ior;\\n\\t#endif\\n\\t#ifdef USE_TRANSMISSION\\n\\t\\tfloat transmission;\\n\\t\\tfloat transmissionAlpha;\\n\\t\\tfloat thickness;\\n\\t\\tfloat attenuationDistance;\\n\\t\\tvec3 attenuationColor;\\n\\t#endif\\n};\\nvec3 clearcoatSpecular = vec3( 0.0 );\\nvec3 sheenSpecular = vec3( 0.0 );\\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\\n float x2 = x * x;\\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\\n}\\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\\n\\tfloat a2 = pow2( alpha );\\n\\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\\n\\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\\n\\treturn 0.5 / max( gv + gl, EPSILON );\\n}\\nfloat D_GGX( const in float alpha, const in float dotNH ) {\\n\\tfloat a2 = pow2( alpha );\\n\\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\\n\\treturn RECIPROCAL_PI * a2 / pow2( denom );\\n}\\n#ifdef USE_CLEARCOAT\\n\\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\\n\\t\\tvec3 f0 = material.clearcoatF0;\\n\\t\\tfloat f90 = material.clearcoatF90;\\n\\t\\tfloat roughness = material.clearcoatRoughness;\\n\\t\\tfloat alpha = pow2( roughness );\\n\\t\\tvec3 halfDir = normalize( lightDir + viewDir );\\n\\t\\tfloat dotNL = saturate( dot( normal, lightDir ) );\\n\\t\\tfloat dotNV = saturate( dot( normal, viewDir ) );\\n\\t\\tfloat dotNH = saturate( dot( normal, halfDir ) );\\n\\t\\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\\n\\t\\tvec3 F = F_Schlick( f0, f90, dotVH );\\n\\t\\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\\n\\t\\tfloat D = D_GGX( alpha, dotNH );\\n\\t\\treturn F * ( V * D );\\n\\t}\\n#endif\\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\\n\\tvec3 f0 = material.specularColor;\\n\\tfloat f90 = material.specularF90;\\n\\tfloat roughness = material.roughness;\\n\\tfloat alpha = pow2( roughness );\\n\\tvec3 halfDir = normalize( lightDir + viewDir );\\n\\tfloat dotNL = saturate( dot( normal, lightDir ) );\\n\\tfloat dotNV = saturate( dot( normal, viewDir ) );\\n\\tfloat dotNH = saturate( dot( normal, halfDir ) );\\n\\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\\n\\tvec3 F = F_Schlick( f0, f90, dotVH );\\n\\t#ifdef USE_IRIDESCENCE\\n\\t\\tF = mix( F, material.iridescenceFresnel, material.iridescence );\\n\\t#endif\\n\\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\\n\\tfloat D = D_GGX( alpha, dotNH );\\n\\treturn F * ( V * D );\\n}\\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\\n\\tconst float LUT_SIZE = 64.0;\\n\\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\\n\\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\\n\\tfloat dotNV = saturate( dot( N, V ) );\\n\\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\\n\\tuv = uv * LUT_SCALE + LUT_BIAS;\\n\\treturn uv;\\n}\\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\\n\\tfloat l = length( f );\\n\\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\\n}\\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\\n\\tfloat x = dot( v1, v2 );\\n\\tfloat y = abs( x );\\n\\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\\n\\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\\n\\tfloat v = a / b;\\n\\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\\n\\treturn cross( v1, v2 ) * theta_sintheta;\\n}\\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\\n\\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\\n\\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\\n\\tvec3 lightNormal = cross( v1, v2 );\\n\\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\\n\\tvec3 T1, T2;\\n\\tT1 = normalize( V - N * dot( V, N ) );\\n\\tT2 = - cross( N, T1 );\\n\\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\\n\\tvec3 coords[ 4 ];\\n\\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\\n\\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\\n\\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\\n\\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\\n\\tcoords[ 0 ] = normalize( coords[ 0 ] );\\n\\tcoords[ 1 ] = normalize( coords[ 1 ] );\\n\\tcoords[ 2 ] = normalize( coords[ 2 ] );\\n\\tcoords[ 3 ] = normalize( coords[ 3 ] );\\n\\tvec3 vectorFormFactor = vec3( 0.0 );\\n\\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\\n\\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\\n\\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\\n\\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\\n\\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\\n\\treturn vec3( result );\\n}\\n#if defined( USE_SHEEN )\\nfloat D_Charlie( float roughness, float dotNH ) {\\n\\tfloat alpha = pow2( roughness );\\n\\tfloat invAlpha = 1.0 / alpha;\\n\\tfloat cos2h = dotNH * dotNH;\\n\\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\\n\\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\\n}\\nfloat V_Neubelt( float dotNV, float dotNL ) {\\n\\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\\n}\\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\\n\\tvec3 halfDir = normalize( lightDir + viewDir );\\n\\tfloat dotNL = saturate( dot( normal, lightDir ) );\\n\\tfloat dotNV = saturate( dot( normal, viewDir ) );\\n\\tfloat dotNH = saturate( dot( normal, halfDir ) );\\n\\tfloat D = D_Charlie( sheenRoughness, dotNH );\\n\\tfloat V = V_Neubelt( dotNV, dotNL );\\n\\treturn sheenColor * ( D * V );\\n}\\n#endif\\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\\n\\tfloat dotNV = saturate( dot( normal, viewDir ) );\\n\\tfloat r2 = roughness * roughness;\\n\\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\\n\\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\\n\\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\\n\\treturn saturate( DG * RECIPROCAL_PI );\\n}\\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\\n\\tfloat dotNV = saturate( dot( normal, viewDir ) );\\n\\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\\n\\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\\n\\tvec4 r = roughness * c0 + c1;\\n\\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\\n\\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\\n\\treturn fab;\\n}\\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\\n\\tvec2 fab = DFGApprox( normal, viewDir, roughness );\\n\\treturn specularColor * fab.x + specularF90 * fab.y;\\n}\\n#ifdef USE_IRIDESCENCE\\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\\n#else\\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\\n#endif\\n\\tvec2 fab = DFGApprox( normal, viewDir, roughness );\\n\\t#ifdef USE_IRIDESCENCE\\n\\t\\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\\n\\t#else\\n\\t\\tvec3 Fr = specularColor;\\n\\t#endif\\n\\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\\n\\tfloat Ess = fab.x + fab.y;\\n\\tfloat Ems = 1.0 - Ess;\\n\\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\\n\\tsingleScatter += FssEss;\\n\\tmultiScatter += Fms * Ems;\\n}\\n#if NUM_RECT_AREA_LIGHTS > 0\\n\\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\\n\\t\\tvec3 normal = geometry.normal;\\n\\t\\tvec3 viewDir = geometry.viewDir;\\n\\t\\tvec3 position = geometry.position;\\n\\t\\tvec3 lightPos = rectAreaLight.position;\\n\\t\\tvec3 halfWidth = rectAreaLight.halfWidth;\\n\\t\\tvec3 halfHeight = rectAreaLight.halfHeight;\\n\\t\\tvec3 lightColor = rectAreaLight.color;\\n\\t\\tfloat roughness = material.roughness;\\n\\t\\tvec3 rectCoords[ 4 ];\\n\\t\\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\\t\\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\\n\\t\\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\\n\\t\\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\\n\\t\\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\\n\\t\\tvec4 t1 = texture2D( ltc_1, uv );\\n\\t\\tvec4 t2 = texture2D( ltc_2, uv );\\n\\t\\tmat3 mInv = mat3(\\n\\t\\t\\tvec3( t1.x, 0, t1.y ),\\n\\t\\t\\tvec3( 0, 1, 0 ),\\n\\t\\t\\tvec3( t1.z, 0, t1.w )\\n\\t\\t);\\n\\t\\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\\n\\t\\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\\n\\t\\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\\n\\t}\\n#endif\\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\\n\\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\\n\\tvec3 irradiance = dotNL * directLight.color;\\n\\t#ifdef USE_CLEARCOAT\\n\\t\\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\\n\\t\\tvec3 ccIrradiance = dotNLcc * directLight.color;\\n\\t\\tclearcoatSpecular += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material );\\n\\t#endif\\n\\t#ifdef USE_SHEEN\\n\\t\\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\\n\\t#endif\\n\\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material );\\n\\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\\n}\\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\\n\\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\\n}\\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\\n\\t#ifdef USE_CLEARCOAT\\n\\t\\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\\n\\t#endif\\n\\t#ifdef USE_SHEEN\\n\\t\\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\\n\\t#endif\\n\\tvec3 singleScattering = vec3( 0.0 );\\n\\tvec3 multiScattering = vec3( 0.0 );\\n\\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\\n\\t#ifdef USE_IRIDESCENCE\\n\\t\\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\\n\\t#else\\n\\t\\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\\n\\t#endif\\n\\tvec3 totalScattering = singleScattering + multiScattering;\\n\\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\\n\\treflectedLight.indirectSpecular += radiance * singleScattering;\\n\\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\\n\\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\\n}\\n#define RE_Direct\\t\\t\\t\\tRE_Direct_Physical\\n#define RE_Direct_RectArea\\t\\tRE_Direct_RectArea_Physical\\n#define RE_IndirectDiffuse\\t\\tRE_IndirectDiffuse_Physical\\n#define RE_IndirectSpecular\\t\\tRE_IndirectSpecular_Physical\\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\\n\\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\\n}\";\n\nvar lights_fragment_begin = \"\\nGeometricContext geometry;\\ngeometry.position = - vViewPosition;\\ngeometry.normal = normal;\\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\\n#ifdef USE_CLEARCOAT\\n\\tgeometry.clearcoatNormal = clearcoatNormal;\\n#endif\\n#ifdef USE_IRIDESCENCE\\n\\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\\n\\tif ( material.iridescenceThickness == 0.0 ) {\\n\\t\\tmaterial.iridescence = 0.0;\\n\\t} else {\\n\\t\\tmaterial.iridescence = saturate( material.iridescence );\\n\\t}\\n\\tif ( material.iridescence > 0.0 ) {\\n\\t\\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\\n\\t\\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\\n\\t}\\n#endif\\nIncidentLight directLight;\\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\\n\\tPointLight pointLight;\\n\\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\\n\\tPointLightShadow pointLightShadow;\\n\\t#endif\\n\\t#pragma unroll_loop_start\\n\\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\\n\\t\\tpointLight = pointLights[ i ];\\n\\t\\tgetPointLightInfo( pointLight, geometry, directLight );\\n\\t\\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\\n\\t\\tpointLightShadow = pointLightShadows[ i ];\\n\\t\\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\\n\\t\\t#endif\\n\\t\\tRE_Direct( directLight, geometry, material, reflectedLight );\\n\\t}\\n\\t#pragma unroll_loop_end\\n#endif\\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\\n\\tSpotLight spotLight;\\n\\tvec4 spotColor;\\n\\tvec3 spotLightCoord;\\n\\tbool inSpotLightMap;\\n\\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\\n\\tSpotLightShadow spotLightShadow;\\n\\t#endif\\n\\t#pragma unroll_loop_start\\n\\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\\n\\t\\tspotLight = spotLights[ i ];\\n\\t\\tgetSpotLightInfo( spotLight, geometry, directLight );\\n\\t\\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\\n\\t\\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\\n\\t\\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\\n\\t\\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\\n\\t\\t#else\\n\\t\\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\\n\\t\\t#endif\\n\\t\\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\\n\\t\\t\\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\\n\\t\\t\\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\\n\\t\\t\\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\\n\\t\\t\\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\\n\\t\\t#endif\\n\\t\\t#undef SPOT_LIGHT_MAP_INDEX\\n\\t\\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\\n\\t\\tspotLightShadow = spotLightShadows[ i ];\\n\\t\\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\\n\\t\\t#endif\\n\\t\\tRE_Direct( directLight, geometry, material, reflectedLight );\\n\\t}\\n\\t#pragma unroll_loop_end\\n#endif\\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\\n\\tDirectionalLight directionalLight;\\n\\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\\n\\tDirectionalLightShadow directionalLightShadow;\\n\\t#endif\\n\\t#pragma unroll_loop_start\\n\\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\\n\\t\\tdirectionalLight = directionalLights[ i ];\\n\\t\\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\\n\\t\\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\\n\\t\\tdirectionalLightShadow = directionalLightShadows[ i ];\\n\\t\\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\\n\\t\\t#endif\\n\\t\\tRE_Direct( directLight, geometry, material, reflectedLight );\\n\\t}\\n\\t#pragma unroll_loop_end\\n#endif\\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\\n\\tRectAreaLight rectAreaLight;\\n\\t#pragma unroll_loop_start\\n\\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\\n\\t\\trectAreaLight = rectAreaLights[ i ];\\n\\t\\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\\n\\t}\\n\\t#pragma unroll_loop_end\\n#endif\\n#if defined( RE_IndirectDiffuse )\\n\\tvec3 iblIrradiance = vec3( 0.0 );\\n\\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\\n\\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\\n\\t#if ( NUM_HEMI_LIGHTS > 0 )\\n\\t\\t#pragma unroll_loop_start\\n\\t\\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\\n\\t\\t\\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\\n\\t\\t}\\n\\t\\t#pragma unroll_loop_end\\n\\t#endif\\n#endif\\n#if defined( RE_IndirectSpecular )\\n\\tvec3 radiance = vec3( 0.0 );\\n\\tvec3 clearcoatRadiance = vec3( 0.0 );\\n#endif\";\n\nvar lights_fragment_maps = \"#if defined( RE_IndirectDiffuse )\\n\\t#ifdef USE_LIGHTMAP\\n\\t\\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\\n\\t\\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\\n\\t\\tirradiance += lightMapIrradiance;\\n\\t#endif\\n\\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\\n\\t\\tiblIrradiance += getIBLIrradiance( geometry.normal );\\n\\t#endif\\n#endif\\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\\n\\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\\n\\t#ifdef USE_CLEARCOAT\\n\\t\\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\\n\\t#endif\\n#endif\";\n\nvar lights_fragment_end = \"#if defined( RE_IndirectDiffuse )\\n\\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\\n#endif\\n#if defined( RE_IndirectSpecular )\\n\\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\\n#endif\";\n\nvar logdepthbuf_fragment = \"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\\n\\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\\n#endif\";\n\nvar logdepthbuf_pars_fragment = \"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\\n\\tuniform float logDepthBufFC;\\n\\tvarying float vFragDepth;\\n\\tvarying float vIsPerspective;\\n#endif\";\n\nvar logdepthbuf_pars_vertex = \"#ifdef USE_LOGDEPTHBUF\\n\\t#ifdef USE_LOGDEPTHBUF_EXT\\n\\t\\tvarying float vFragDepth;\\n\\t\\tvarying float vIsPerspective;\\n\\t#else\\n\\t\\tuniform float logDepthBufFC;\\n\\t#endif\\n#endif\";\n\nvar logdepthbuf_vertex = \"#ifdef USE_LOGDEPTHBUF\\n\\t#ifdef USE_LOGDEPTHBUF_EXT\\n\\t\\tvFragDepth = 1.0 + gl_Position.w;\\n\\t\\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\\n\\t#else\\n\\t\\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\\n\\t\\t\\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\\n\\t\\t\\tgl_Position.z *= gl_Position.w;\\n\\t\\t}\\n\\t#endif\\n#endif\";\n\nvar map_fragment = \"#ifdef USE_MAP\\n\\tdiffuseColor *= texture2D( map, vMapUv );\\n#endif\";\n\nvar map_pars_fragment = \"#ifdef USE_MAP\\n\\tuniform sampler2D map;\\n#endif\";\n\nvar map_particle_fragment = \"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\\n\\t#if defined( USE_POINTS_UV )\\n\\t\\tvec2 uv = vUv;\\n\\t#else\\n\\t\\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\\n\\t#endif\\n#endif\\n#ifdef USE_MAP\\n\\tdiffuseColor *= texture2D( map, uv );\\n#endif\\n#ifdef USE_ALPHAMAP\\n\\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\\n#endif\";\n\nvar map_particle_pars_fragment = \"#if defined( USE_POINTS_UV )\\n\\tvarying vec2 vUv;\\n#else\\n\\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\\n\\t\\tuniform mat3 uvTransform;\\n\\t#endif\\n#endif\\n#ifdef USE_MAP\\n\\tuniform sampler2D map;\\n#endif\\n#ifdef USE_ALPHAMAP\\n\\tuniform sampler2D alphaMap;\\n#endif\";\n\nvar metalnessmap_fragment = \"float metalnessFactor = metalness;\\n#ifdef USE_METALNESSMAP\\n\\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\\n\\tmetalnessFactor *= texelMetalness.b;\\n#endif\";\n\nvar metalnessmap_pars_fragment = \"#ifdef USE_METALNESSMAP\\n\\tuniform sampler2D metalnessMap;\\n#endif\";\n\nvar morphcolor_vertex = \"#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\\n\\tvColor *= morphTargetBaseInfluence;\\n\\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\\n\\t\\t#if defined( USE_COLOR_ALPHA )\\n\\t\\t\\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\\n\\t\\t#elif defined( USE_COLOR )\\n\\t\\t\\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\\n\\t\\t#endif\\n\\t}\\n#endif\";\n\nvar morphnormal_vertex = \"#ifdef USE_MORPHNORMALS\\n\\tobjectNormal *= morphTargetBaseInfluence;\\n\\t#ifdef MORPHTARGETS_TEXTURE\\n\\t\\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\\n\\t\\t\\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\\n\\t\\t}\\n\\t#else\\n\\t\\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\\n\\t\\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\\n\\t\\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\\n\\t\\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\\n\\t#endif\\n#endif\";\n\nvar morphtarget_pars_vertex = \"#ifdef USE_MORPHTARGETS\\n\\tuniform float morphTargetBaseInfluence;\\n\\t#ifdef MORPHTARGETS_TEXTURE\\n\\t\\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\\n\\t\\tuniform sampler2DArray morphTargetsTexture;\\n\\t\\tuniform ivec2 morphTargetsTextureSize;\\n\\t\\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\\n\\t\\t\\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\\n\\t\\t\\tint y = texelIndex / morphTargetsTextureSize.x;\\n\\t\\t\\tint x = texelIndex - y * morphTargetsTextureSize.x;\\n\\t\\t\\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\\n\\t\\t\\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\\n\\t\\t}\\n\\t#else\\n\\t\\t#ifndef USE_MORPHNORMALS\\n\\t\\t\\tuniform float morphTargetInfluences[ 8 ];\\n\\t\\t#else\\n\\t\\t\\tuniform float morphTargetInfluences[ 4 ];\\n\\t\\t#endif\\n\\t#endif\\n#endif\";\n\nvar morphtarget_vertex = \"#ifdef USE_MORPHTARGETS\\n\\ttransformed *= morphTargetBaseInfluence;\\n\\t#ifdef MORPHTARGETS_TEXTURE\\n\\t\\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\\n\\t\\t\\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\\n\\t\\t}\\n\\t#else\\n\\t\\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\\n\\t\\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\\n\\t\\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\\n\\t\\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\\n\\t\\t#ifndef USE_MORPHNORMALS\\n\\t\\t\\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\\n\\t\\t\\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\\n\\t\\t\\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\\n\\t\\t\\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\\n\\t\\t#endif\\n\\t#endif\\n#endif\";\n\nvar normal_fragment_begin = \"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\\n#ifdef FLAT_SHADED\\n\\tvec3 fdx = dFdx( vViewPosition );\\n\\tvec3 fdy = dFdy( vViewPosition );\\n\\tvec3 normal = normalize( cross( fdx, fdy ) );\\n#else\\n\\tvec3 normal = normalize( vNormal );\\n\\t#ifdef DOUBLE_SIDED\\n\\t\\tnormal *= faceDirection;\\n\\t#endif\\n#endif\\n#ifdef USE_NORMALMAP_TANGENTSPACE\\n\\t#ifdef USE_TANGENT\\n\\t\\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\\n\\t#else\\n\\t\\tmat3 tbn = getTangentFrame( - vViewPosition, normal, vNormalMapUv );\\n\\t#endif\\n\\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\\n\\t\\ttbn[0] *= faceDirection;\\n\\t\\ttbn[1] *= faceDirection;\\n\\t#endif\\n#endif\\n#ifdef USE_CLEARCOAT_NORMALMAP\\n\\t#ifdef USE_TANGENT\\n\\t\\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\\n\\t#else\\n\\t\\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\\n\\t#endif\\n\\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\\n\\t\\ttbn2[0] *= faceDirection;\\n\\t\\ttbn2[1] *= faceDirection;\\n\\t#endif\\n#endif\\nvec3 geometryNormal = normal;\";\n\nvar normal_fragment_maps = \"#ifdef USE_NORMALMAP_OBJECTSPACE\\n\\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\\n\\t#ifdef FLIP_SIDED\\n\\t\\tnormal = - normal;\\n\\t#endif\\n\\t#ifdef DOUBLE_SIDED\\n\\t\\tnormal = normal * faceDirection;\\n\\t#endif\\n\\tnormal = normalize( normalMatrix * normal );\\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\\n\\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\\n\\tmapN.xy *= normalScale;\\n\\tnormal = normalize( tbn * mapN );\\n#elif defined( USE_BUMPMAP )\\n\\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\\n#endif\";\n\nvar normal_pars_fragment = \"#ifndef FLAT_SHADED\\n\\tvarying vec3 vNormal;\\n\\t#ifdef USE_TANGENT\\n\\t\\tvarying vec3 vTangent;\\n\\t\\tvarying vec3 vBitangent;\\n\\t#endif\\n#endif\";\n\nvar normal_pars_vertex = \"#ifndef FLAT_SHADED\\n\\tvarying vec3 vNormal;\\n\\t#ifdef USE_TANGENT\\n\\t\\tvarying vec3 vTangent;\\n\\t\\tvarying vec3 vBitangent;\\n\\t#endif\\n#endif\";\n\nvar normal_vertex = \"#ifndef FLAT_SHADED\\n\\tvNormal = normalize( transformedNormal );\\n\\t#ifdef USE_TANGENT\\n\\t\\tvTangent = normalize( transformedTangent );\\n\\t\\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\\n\\t#endif\\n#endif\";\n\nvar normalmap_pars_fragment = \"#ifdef USE_NORMALMAP\\n\\tuniform sampler2D normalMap;\\n\\tuniform vec2 normalScale;\\n#endif\\n#ifdef USE_NORMALMAP_OBJECTSPACE\\n\\tuniform mat3 normalMatrix;\\n#endif\\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\\n\\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\\n\\t\\tvec3 q0 = dFdx( eye_pos.xyz );\\n\\t\\tvec3 q1 = dFdy( eye_pos.xyz );\\n\\t\\tvec2 st0 = dFdx( uv.st );\\n\\t\\tvec2 st1 = dFdy( uv.st );\\n\\t\\tvec3 N = surf_norm;\\n\\t\\tvec3 q1perp = cross( q1, N );\\n\\t\\tvec3 q0perp = cross( N, q0 );\\n\\t\\tvec3 T = q1perp * st0.x + q0perp * st1.x;\\n\\t\\tvec3 B = q1perp * st0.y + q0perp * st1.y;\\n\\t\\tfloat det = max( dot( T, T ), dot( B, B ) );\\n\\t\\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\\n\\t\\treturn mat3( T * scale, B * scale, N );\\n\\t}\\n#endif\";\n\nvar clearcoat_normal_fragment_begin = \"#ifdef USE_CLEARCOAT\\n\\tvec3 clearcoatNormal = geometryNormal;\\n#endif\";\n\nvar clearcoat_normal_fragment_maps = \"#ifdef USE_CLEARCOAT_NORMALMAP\\n\\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\\n\\tclearcoatMapN.xy *= clearcoatNormalScale;\\n\\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\\n#endif\";\n\nvar clearcoat_pars_fragment = \"#ifdef USE_CLEARCOATMAP\\n\\tuniform sampler2D clearcoatMap;\\n#endif\\n#ifdef USE_CLEARCOAT_NORMALMAP\\n\\tuniform sampler2D clearcoatNormalMap;\\n\\tuniform vec2 clearcoatNormalScale;\\n#endif\\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\\n\\tuniform sampler2D clearcoatRoughnessMap;\\n#endif\";\n\nvar iridescence_pars_fragment = \"#ifdef USE_IRIDESCENCEMAP\\n\\tuniform sampler2D iridescenceMap;\\n#endif\\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\\n\\tuniform sampler2D iridescenceThicknessMap;\\n#endif\";\n\nvar output_fragment = \"#ifdef OPAQUE\\ndiffuseColor.a = 1.0;\\n#endif\\n#ifdef USE_TRANSMISSION\\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\\n#endif\\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );\";\n\nvar packing = \"vec3 packNormalToRGB( const in vec3 normal ) {\\n\\treturn normalize( normal ) * 0.5 + 0.5;\\n}\\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\\n\\treturn 2.0 * rgb.xyz - 1.0;\\n}\\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\\nconst float ShiftRight8 = 1. / 256.;\\nvec4 packDepthToRGBA( const in float v ) {\\n\\tvec4 r = vec4( fract( v * PackFactors ), v );\\n\\tr.yzw -= r.xyz * ShiftRight8;\\treturn r * PackUpscale;\\n}\\nfloat unpackRGBAToDepth( const in vec4 v ) {\\n\\treturn dot( v, UnpackFactors );\\n}\\nvec2 packDepthToRG( in highp float v ) {\\n\\treturn packDepthToRGBA( v ).yx;\\n}\\nfloat unpackRGToDepth( const in highp vec2 v ) {\\n\\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\\n}\\nvec4 pack2HalfToRGBA( vec2 v ) {\\n\\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\\n\\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\\n}\\nvec2 unpackRGBATo2Half( vec4 v ) {\\n\\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\\n}\\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\\n\\treturn ( viewZ + near ) / ( near - far );\\n}\\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\\n\\treturn depth * ( near - far ) - near;\\n}\\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\\n\\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\\n}\\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\\n\\treturn ( near * far ) / ( ( far - near ) * depth - far );\\n}\";\n\nvar premultiplied_alpha_fragment = \"#ifdef PREMULTIPLIED_ALPHA\\n\\tgl_FragColor.rgb *= gl_FragColor.a;\\n#endif\";\n\nvar project_vertex = \"vec4 mvPosition = vec4( transformed, 1.0 );\\n#ifdef USE_INSTANCING\\n\\tmvPosition = instanceMatrix * mvPosition;\\n#endif\\nmvPosition = modelViewMatrix * mvPosition;\\ngl_Position = projectionMatrix * mvPosition;\";\n\nvar dithering_fragment = \"#ifdef DITHERING\\n\\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\\n#endif\";\n\nvar dithering_pars_fragment = \"#ifdef DITHERING\\n\\tvec3 dithering( vec3 color ) {\\n\\t\\tfloat grid_position = rand( gl_FragCoord.xy );\\n\\t\\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\\n\\t\\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\\n\\t\\treturn color + dither_shift_RGB;\\n\\t}\\n#endif\";\n\nvar roughnessmap_fragment = \"float roughnessFactor = roughness;\\n#ifdef USE_ROUGHNESSMAP\\n\\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\\n\\troughnessFactor *= texelRoughness.g;\\n#endif\";\n\nvar roughnessmap_pars_fragment = \"#ifdef USE_ROUGHNESSMAP\\n\\tuniform sampler2D roughnessMap;\\n#endif\";\n\nvar shadowmap_pars_fragment = \"#if NUM_SPOT_LIGHT_COORDS > 0\\n\\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\\n#endif\\n#if NUM_SPOT_LIGHT_MAPS > 0\\n\\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\\n#endif\\n#ifdef USE_SHADOWMAP\\n\\t#if NUM_DIR_LIGHT_SHADOWS > 0\\n\\t\\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\\n\\t\\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\\n\\t\\tstruct DirectionalLightShadow {\\n\\t\\t\\tfloat shadowBias;\\n\\t\\t\\tfloat shadowNormalBias;\\n\\t\\t\\tfloat shadowRadius;\\n\\t\\t\\tvec2 shadowMapSize;\\n\\t\\t};\\n\\t\\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\\n\\t#endif\\n\\t#if NUM_SPOT_LIGHT_SHADOWS > 0\\n\\t\\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\\n\\t\\tstruct SpotLightShadow {\\n\\t\\t\\tfloat shadowBias;\\n\\t\\t\\tfloat shadowNormalBias;\\n\\t\\t\\tfloat shadowRadius;\\n\\t\\t\\tvec2 shadowMapSize;\\n\\t\\t};\\n\\t\\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\\n\\t#endif\\n\\t#if NUM_POINT_LIGHT_SHADOWS > 0\\n\\t\\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\\n\\t\\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\\n\\t\\tstruct PointLightShadow {\\n\\t\\t\\tfloat shadowBias;\\n\\t\\t\\tfloat shadowNormalBias;\\n\\t\\t\\tfloat shadowRadius;\\n\\t\\t\\tvec2 shadowMapSize;\\n\\t\\t\\tfloat shadowCameraNear;\\n\\t\\t\\tfloat shadowCameraFar;\\n\\t\\t};\\n\\t\\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\\n\\t#endif\\n\\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\\n\\t\\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\\n\\t}\\n\\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\\n\\t\\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\\n\\t}\\n\\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\\n\\t\\tfloat occlusion = 1.0;\\n\\t\\tvec2 distribution = texture2DDistribution( shadow, uv );\\n\\t\\tfloat hard_shadow = step( compare , distribution.x );\\n\\t\\tif (hard_shadow != 1.0 ) {\\n\\t\\t\\tfloat distance = compare - distribution.x ;\\n\\t\\t\\tfloat variance = max( 0.00000, distribution.y * distribution.y );\\n\\t\\t\\tfloat softness_probability = variance / (variance + distance * distance );\\t\\t\\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\\t\\t\\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\\n\\t\\t}\\n\\t\\treturn occlusion;\\n\\t}\\n\\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\\n\\t\\tfloat shadow = 1.0;\\n\\t\\tshadowCoord.xyz /= shadowCoord.w;\\n\\t\\tshadowCoord.z += shadowBias;\\n\\t\\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\\n\\t\\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\\n\\t\\tif ( frustumTest ) {\\n\\t\\t#if defined( SHADOWMAP_TYPE_PCF )\\n\\t\\t\\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\\n\\t\\t\\tfloat dx0 = - texelSize.x * shadowRadius;\\n\\t\\t\\tfloat dy0 = - texelSize.y * shadowRadius;\\n\\t\\t\\tfloat dx1 = + texelSize.x * shadowRadius;\\n\\t\\t\\tfloat dy1 = + texelSize.y * shadowRadius;\\n\\t\\t\\tfloat dx2 = dx0 / 2.0;\\n\\t\\t\\tfloat dy2 = dy0 / 2.0;\\n\\t\\t\\tfloat dx3 = dx1 / 2.0;\\n\\t\\t\\tfloat dy3 = dy1 / 2.0;\\n\\t\\t\\tshadow = (\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\\n\\t\\t\\t) * ( 1.0 / 17.0 );\\n\\t\\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\\n\\t\\t\\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\\n\\t\\t\\tfloat dx = texelSize.x;\\n\\t\\t\\tfloat dy = texelSize.y;\\n\\t\\t\\tvec2 uv = shadowCoord.xy;\\n\\t\\t\\tvec2 f = fract( uv * shadowMapSize + 0.5 );\\n\\t\\t\\tuv -= f * texelSize;\\n\\t\\t\\tshadow = (\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\\n\\t\\t\\t\\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\\n\\t\\t\\t\\t\\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\\n\\t\\t\\t\\t\\t f.x ) +\\n\\t\\t\\t\\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\\n\\t\\t\\t\\t\\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\\n\\t\\t\\t\\t\\t f.x ) +\\n\\t\\t\\t\\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\\n\\t\\t\\t\\t\\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\\n\\t\\t\\t\\t\\t f.y ) +\\n\\t\\t\\t\\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\\n\\t\\t\\t\\t\\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\\n\\t\\t\\t\\t\\t f.y ) +\\n\\t\\t\\t\\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\\n\\t\\t\\t\\t\\t\\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\\n\\t\\t\\t\\t\\t\\t f.x ),\\n\\t\\t\\t\\t\\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\\n\\t\\t\\t\\t\\t\\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\\n\\t\\t\\t\\t\\t\\t f.x ),\\n\\t\\t\\t\\t\\t f.y )\\n\\t\\t\\t) * ( 1.0 / 9.0 );\\n\\t\\t#elif defined( SHADOWMAP_TYPE_VSM )\\n\\t\\t\\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\\n\\t\\t#else\\n\\t\\t\\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\\n\\t\\t#endif\\n\\t\\t}\\n\\t\\treturn shadow;\\n\\t}\\n\\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\\n\\t\\tvec3 absV = abs( v );\\n\\t\\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\\n\\t\\tabsV *= scaleToCube;\\n\\t\\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\\n\\t\\tvec2 planar = v.xy;\\n\\t\\tfloat almostATexel = 1.5 * texelSizeY;\\n\\t\\tfloat almostOne = 1.0 - almostATexel;\\n\\t\\tif ( absV.z >= almostOne ) {\\n\\t\\t\\tif ( v.z > 0.0 )\\n\\t\\t\\t\\tplanar.x = 4.0 - v.x;\\n\\t\\t} else if ( absV.x >= almostOne ) {\\n\\t\\t\\tfloat signX = sign( v.x );\\n\\t\\t\\tplanar.x = v.z * signX + 2.0 * signX;\\n\\t\\t} else if ( absV.y >= almostOne ) {\\n\\t\\t\\tfloat signY = sign( v.y );\\n\\t\\t\\tplanar.x = v.x + 2.0 * signY + 2.0;\\n\\t\\t\\tplanar.y = v.z * signY - 2.0;\\n\\t\\t}\\n\\t\\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\\n\\t}\\n\\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\\n\\t\\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\\n\\t\\tvec3 lightToPosition = shadowCoord.xyz;\\n\\t\\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\\t\\tdp += shadowBias;\\n\\t\\tvec3 bd3D = normalize( lightToPosition );\\n\\t\\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\\n\\t\\t\\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\\n\\t\\t\\treturn (\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\\n\\t\\t\\t\\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\\n\\t\\t\\t) * ( 1.0 / 9.0 );\\n\\t\\t#else\\n\\t\\t\\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\\n\\t\\t#endif\\n\\t}\\n#endif\";\n\nvar shadowmap_pars_vertex = \"#if NUM_SPOT_LIGHT_COORDS > 0\\n\\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\\n\\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\\n#endif\\n#ifdef USE_SHADOWMAP\\n\\t#if NUM_DIR_LIGHT_SHADOWS > 0\\n\\t\\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\\n\\t\\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\\n\\t\\tstruct DirectionalLightShadow {\\n\\t\\t\\tfloat shadowBias;\\n\\t\\t\\tfloat shadowNormalBias;\\n\\t\\t\\tfloat shadowRadius;\\n\\t\\t\\tvec2 shadowMapSize;\\n\\t\\t};\\n\\t\\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\\n\\t#endif\\n\\t#if NUM_SPOT_LIGHT_SHADOWS > 0\\n\\t\\tstruct SpotLightShadow {\\n\\t\\t\\tfloat shadowBias;\\n\\t\\t\\tfloat shadowNormalBias;\\n\\t\\t\\tfloat shadowRadius;\\n\\t\\t\\tvec2 shadowMapSize;\\n\\t\\t};\\n\\t\\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\\n\\t#endif\\n\\t#if NUM_POINT_LIGHT_SHADOWS > 0\\n\\t\\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\\n\\t\\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\\n\\t\\tstruct PointLightShadow {\\n\\t\\t\\tfloat shadowBias;\\n\\t\\t\\tfloat shadowNormalBias;\\n\\t\\t\\tfloat shadowRadius;\\n\\t\\t\\tvec2 shadowMapSize;\\n\\t\\t\\tfloat shadowCameraNear;\\n\\t\\t\\tfloat shadowCameraFar;\\n\\t\\t};\\n\\t\\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\\n\\t#endif\\n#endif\";\n\nvar shadowmap_vertex = \"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\\n\\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\\n\\tvec4 shadowWorldPosition;\\n#endif\\n#if defined( USE_SHADOWMAP )\\n\\t#if NUM_DIR_LIGHT_SHADOWS > 0\\n\\t\\t#pragma unroll_loop_start\\n\\t\\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\\n\\t\\t\\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\\n\\t\\t\\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\\n\\t\\t}\\n\\t\\t#pragma unroll_loop_end\\n\\t#endif\\n\\t#if NUM_POINT_LIGHT_SHADOWS > 0\\n\\t\\t#pragma unroll_loop_start\\n\\t\\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\\n\\t\\t\\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\\n\\t\\t\\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\\n\\t\\t}\\n\\t\\t#pragma unroll_loop_end\\n\\t#endif\\n#endif\\n#if NUM_SPOT_LIGHT_COORDS > 0\\n\\t#pragma unroll_loop_start\\n\\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\\n\\t\\tshadowWorldPosition = worldPosition;\\n\\t\\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\\n\\t\\t\\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\\n\\t\\t#endif\\n\\t\\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\\n\\t}\\n\\t#pragma unroll_loop_end\\n#endif\";\n\nvar shadowmask_pars_fragment = \"float getShadowMask() {\\n\\tfloat shadow = 1.0;\\n\\t#ifdef USE_SHADOWMAP\\n\\t#if NUM_DIR_LIGHT_SHADOWS > 0\\n\\tDirectionalLightShadow directionalLight;\\n\\t#pragma unroll_loop_start\\n\\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\\n\\t\\tdirectionalLight = directionalLightShadows[ i ];\\n\\t\\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\\n\\t}\\n\\t#pragma unroll_loop_end\\n\\t#endif\\n\\t#if NUM_SPOT_LIGHT_SHADOWS > 0\\n\\tSpotLightShadow spotLight;\\n\\t#pragma unroll_loop_start\\n\\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\\n\\t\\tspotLight = spotLightShadows[ i ];\\n\\t\\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\\n\\t}\\n\\t#pragma unroll_loop_end\\n\\t#endif\\n\\t#if NUM_POINT_LIGHT_SHADOWS > 0\\n\\tPointLightShadow pointLight;\\n\\t#pragma unroll_loop_start\\n\\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\\n\\t\\tpointLight = pointLightShadows[ i ];\\n\\t\\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\\n\\t}\\n\\t#pragma unroll_loop_end\\n\\t#endif\\n\\t#endif\\n\\treturn shadow;\\n}\";\n\nvar skinbase_vertex = \"#ifdef USE_SKINNING\\n\\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\\n\\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\\n\\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\\n\\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\\n#endif\";\n\nvar skinning_pars_vertex = \"#ifdef USE_SKINNING\\n\\tuniform mat4 bindMatrix;\\n\\tuniform mat4 bindMatrixInverse;\\n\\tuniform highp sampler2D boneTexture;\\n\\tuniform int boneTextureSize;\\n\\tmat4 getBoneMatrix( const in float i ) {\\n\\t\\tfloat j = i * 4.0;\\n\\t\\tfloat x = mod( j, float( boneTextureSize ) );\\n\\t\\tfloat y = floor( j / float( boneTextureSize ) );\\n\\t\\tfloat dx = 1.0 / float( boneTextureSize );\\n\\t\\tfloat dy = 1.0 / float( boneTextureSize );\\n\\t\\ty = dy * ( y + 0.5 );\\n\\t\\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\\n\\t\\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\\n\\t\\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\\n\\t\\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\\n\\t\\tmat4 bone = mat4( v1, v2, v3, v4 );\\n\\t\\treturn bone;\\n\\t}\\n#endif\";\n\nvar skinning_vertex = \"#ifdef USE_SKINNING\\n\\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\\n\\tvec4 skinned = vec4( 0.0 );\\n\\tskinned += boneMatX * skinVertex * skinWeight.x;\\n\\tskinned += boneMatY * skinVertex * skinWeight.y;\\n\\tskinned += boneMatZ * skinVertex * skinWeight.z;\\n\\tskinned += boneMatW * skinVertex * skinWeight.w;\\n\\ttransformed = ( bindMatrixInverse * skinned ).xyz;\\n#endif\";\n\nvar skinnormal_vertex = \"#ifdef USE_SKINNING\\n\\tmat4 skinMatrix = mat4( 0.0 );\\n\\tskinMatrix += skinWeight.x * boneMatX;\\n\\tskinMatrix += skinWeight.y * boneMatY;\\n\\tskinMatrix += skinWeight.z * boneMatZ;\\n\\tskinMatrix += skinWeight.w * boneMatW;\\n\\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\\n\\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\\n\\t#ifdef USE_TANGENT\\n\\t\\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\\n\\t#endif\\n#endif\";\n\nvar specularmap_fragment = \"float specularStrength;\\n#ifdef USE_SPECULARMAP\\n\\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\\n\\tspecularStrength = texelSpecular.r;\\n#else\\n\\tspecularStrength = 1.0;\\n#endif\";\n\nvar specularmap_pars_fragment = \"#ifdef USE_SPECULARMAP\\n\\tuniform sampler2D specularMap;\\n#endif\";\n\nvar tonemapping_fragment = \"#if defined( TONE_MAPPING )\\n\\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\\n#endif\";\n\nvar tonemapping_pars_fragment = \"#ifndef saturate\\n#define saturate( a ) clamp( a, 0.0, 1.0 )\\n#endif\\nuniform float toneMappingExposure;\\nvec3 LinearToneMapping( vec3 color ) {\\n\\treturn toneMappingExposure * color;\\n}\\nvec3 ReinhardToneMapping( vec3 color ) {\\n\\tcolor *= toneMappingExposure;\\n\\treturn saturate( color / ( vec3( 1.0 ) + color ) );\\n}\\nvec3 OptimizedCineonToneMapping( vec3 color ) {\\n\\tcolor *= toneMappingExposure;\\n\\tcolor = max( vec3( 0.0 ), color - 0.004 );\\n\\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\\n}\\nvec3 RRTAndODTFit( vec3 v ) {\\n\\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\\n\\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\\n\\treturn a / b;\\n}\\nvec3 ACESFilmicToneMapping( vec3 color ) {\\n\\tconst mat3 ACESInputMat = mat3(\\n\\t\\tvec3( 0.59719, 0.07600, 0.02840 ),\\t\\tvec3( 0.35458, 0.90834, 0.13383 ),\\n\\t\\tvec3( 0.04823, 0.01566, 0.83777 )\\n\\t);\\n\\tconst mat3 ACESOutputMat = mat3(\\n\\t\\tvec3( 1.60475, -0.10208, -0.00327 ),\\t\\tvec3( -0.53108, 1.10813, -0.07276 ),\\n\\t\\tvec3( -0.07367, -0.00605, 1.07602 )\\n\\t);\\n\\tcolor *= toneMappingExposure / 0.6;\\n\\tcolor = ACESInputMat * color;\\n\\tcolor = RRTAndODTFit( color );\\n\\tcolor = ACESOutputMat * color;\\n\\treturn saturate( color );\\n}\\nvec3 CustomToneMapping( vec3 color ) { return color; }\";\n\nvar transmission_fragment = \"#ifdef USE_TRANSMISSION\\n\\tmaterial.transmission = transmission;\\n\\tmaterial.transmissionAlpha = 1.0;\\n\\tmaterial.thickness = thickness;\\n\\tmaterial.attenuationDistance = attenuationDistance;\\n\\tmaterial.attenuationColor = attenuationColor;\\n\\t#ifdef USE_TRANSMISSIONMAP\\n\\t\\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\\n\\t#endif\\n\\t#ifdef USE_THICKNESSMAP\\n\\t\\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\\n\\t#endif\\n\\tvec3 pos = vWorldPosition;\\n\\tvec3 v = normalize( cameraPosition - pos );\\n\\tvec3 n = inverseTransformDirection( normal, viewMatrix );\\n\\tvec4 transmission = getIBLVolumeRefraction(\\n\\t\\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\\n\\t\\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\\n\\t\\tmaterial.attenuationColor, material.attenuationDistance );\\n\\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\\n\\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\\n#endif\";\n\nvar transmission_pars_fragment = \"#ifdef USE_TRANSMISSION\\n\\tuniform float transmission;\\n\\tuniform float thickness;\\n\\tuniform float attenuationDistance;\\n\\tuniform vec3 attenuationColor;\\n\\t#ifdef USE_TRANSMISSIONMAP\\n\\t\\tuniform sampler2D transmissionMap;\\n\\t#endif\\n\\t#ifdef USE_THICKNESSMAP\\n\\t\\tuniform sampler2D thicknessMap;\\n\\t#endif\\n\\tuniform vec2 transmissionSamplerSize;\\n\\tuniform sampler2D transmissionSamplerMap;\\n\\tuniform mat4 modelMatrix;\\n\\tuniform mat4 projectionMatrix;\\n\\tvarying vec3 vWorldPosition;\\n\\tfloat w0( float a ) {\\n\\t\\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\\n\\t}\\n\\tfloat w1( float a ) {\\n\\t\\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\\n\\t}\\n\\tfloat w2( float a ){\\n\\t\\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\\n\\t}\\n\\tfloat w3( float a ) {\\n\\t\\treturn ( 1.0 / 6.0 ) * ( a * a * a );\\n\\t}\\n\\tfloat g0( float a ) {\\n\\t\\treturn w0( a ) + w1( a );\\n\\t}\\n\\tfloat g1( float a ) {\\n\\t\\treturn w2( a ) + w3( a );\\n\\t}\\n\\tfloat h0( float a ) {\\n\\t\\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\\n\\t}\\n\\tfloat h1( float a ) {\\n\\t\\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\\n\\t}\\n\\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\\n\\t\\tuv = uv * texelSize.zw + 0.5;\\n\\t\\tvec2 iuv = floor( uv );\\n\\t\\tvec2 fuv = fract( uv );\\n\\t\\tfloat g0x = g0( fuv.x );\\n\\t\\tfloat g1x = g1( fuv.x );\\n\\t\\tfloat h0x = h0( fuv.x );\\n\\t\\tfloat h1x = h1( fuv.x );\\n\\t\\tfloat h0y = h0( fuv.y );\\n\\t\\tfloat h1y = h1( fuv.y );\\n\\t\\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\\n\\t\\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\\n\\t\\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\\n\\t\\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\\n\\t\\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\\n\\t\\t\\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\\n\\t}\\n\\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\\n\\t\\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\\n\\t\\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\\n\\t\\tvec2 fLodSizeInv = 1.0 / fLodSize;\\n\\t\\tvec2 cLodSizeInv = 1.0 / cLodSize;\\n\\t\\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\\n\\t\\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\\n\\t\\treturn mix( fSample, cSample, fract( lod ) );\\n\\t}\\n\\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\\n\\t\\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\\n\\t\\tvec3 modelScale;\\n\\t\\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\\n\\t\\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\\n\\t\\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\\n\\t\\treturn normalize( refractionVector ) * thickness * modelScale;\\n\\t}\\n\\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\\n\\t\\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\\n\\t}\\n\\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\\n\\t\\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\\n\\t\\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\\n\\t}\\n\\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\\n\\t\\tif ( isinf( attenuationDistance ) ) {\\n\\t\\t\\treturn radiance;\\n\\t\\t} else {\\n\\t\\t\\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\\n\\t\\t\\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\\t\\t\\treturn transmittance * radiance;\\n\\t\\t}\\n\\t}\\n\\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\\n\\t\\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\\n\\t\\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\\n\\t\\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\\n\\t\\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\\n\\t\\tvec3 refractedRayExit = position + transmissionRay;\\n\\t\\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\\n\\t\\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\\n\\t\\trefractionCoords += 1.0;\\n\\t\\trefractionCoords /= 2.0;\\n\\t\\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\\n\\t\\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\\n\\t\\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\\n\\t\\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\\n\\t}\\n#endif\";\n\nvar uv_pars_fragment = \"#ifdef USE_UV\\n\\tvarying vec2 vUv;\\n#endif\\n#ifdef USE_MAP\\n\\tvarying vec2 vMapUv;\\n#endif\\n#ifdef USE_ALPHAMAP\\n\\tvarying vec2 vAlphaMapUv;\\n#endif\\n#ifdef USE_LIGHTMAP\\n\\tvarying vec2 vLightMapUv;\\n#endif\\n#ifdef USE_AOMAP\\n\\tvarying vec2 vAoMapUv;\\n#endif\\n#ifdef USE_BUMPMAP\\n\\tvarying vec2 vBumpMapUv;\\n#endif\\n#ifdef USE_NORMALMAP\\n\\tvarying vec2 vNormalMapUv;\\n#endif\\n#ifdef USE_EMISSIVEMAP\\n\\tvarying vec2 vEmissiveMapUv;\\n#endif\\n#ifdef USE_METALNESSMAP\\n\\tvarying vec2 vMetalnessMapUv;\\n#endif\\n#ifdef USE_ROUGHNESSMAP\\n\\tvarying vec2 vRoughnessMapUv;\\n#endif\\n#ifdef USE_CLEARCOATMAP\\n\\tvarying vec2 vClearcoatMapUv;\\n#endif\\n#ifdef USE_CLEARCOAT_NORMALMAP\\n\\tvarying vec2 vClearcoatNormalMapUv;\\n#endif\\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\\n\\tvarying vec2 vClearcoatRoughnessMapUv;\\n#endif\\n#ifdef USE_IRIDESCENCEMAP\\n\\tvarying vec2 vIridescenceMapUv;\\n#endif\\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\\n\\tvarying vec2 vIridescenceThicknessMapUv;\\n#endif\\n#ifdef USE_SHEEN_COLORMAP\\n\\tvarying vec2 vSheenColorMapUv;\\n#endif\\n#ifdef USE_SHEEN_ROUGHNESSMAP\\n\\tvarying vec2 vSheenRoughnessMapUv;\\n#endif\\n#ifdef USE_SPECULARMAP\\n\\tvarying vec2 vSpecularMapUv;\\n#endif\\n#ifdef USE_SPECULAR_COLORMAP\\n\\tvarying vec2 vSpecularColorMapUv;\\n#endif\\n#ifdef USE_SPECULAR_INTENSITYMAP\\n\\tvarying vec2 vSpecularIntensityMapUv;\\n#endif\\n#ifdef USE_TRANSMISSIONMAP\\n\\tuniform mat3 transmissionMapTransform;\\n\\tvarying vec2 vTransmissionMapUv;\\n#endif\\n#ifdef USE_THICKNESSMAP\\n\\tuniform mat3 thicknessMapTransform;\\n\\tvarying vec2 vThicknessMapUv;\\n#endif\";\n\nvar uv_pars_vertex = \"#ifdef USE_UV\\n\\tvarying vec2 vUv;\\n#endif\\n#ifdef USE_MAP\\n\\tuniform mat3 mapTransform;\\n\\tvarying vec2 vMapUv;\\n#endif\\n#ifdef USE_ALPHAMAP\\n\\tuniform mat3 alphaMapTransform;\\n\\tvarying vec2 vAlphaMapUv;\\n#endif\\n#ifdef USE_LIGHTMAP\\n\\tuniform mat3 lightMapTransform;\\n\\tvarying vec2 vLightMapUv;\\n#endif\\n#ifdef USE_AOMAP\\n\\tuniform mat3 aoMapTransform;\\n\\tvarying vec2 vAoMapUv;\\n#endif\\n#ifdef USE_BUMPMAP\\n\\tuniform mat3 bumpMapTransform;\\n\\tvarying vec2 vBumpMapUv;\\n#endif\\n#ifdef USE_NORMALMAP\\n\\tuniform mat3 normalMapTransform;\\n\\tvarying vec2 vNormalMapUv;\\n#endif\\n#ifdef USE_DISPLACEMENTMAP\\n\\tuniform mat3 displacementMapTransform;\\n\\tvarying vec2 vDisplacementMapUv;\\n#endif\\n#ifdef USE_EMISSIVEMAP\\n\\tuniform mat3 emissiveMapTransform;\\n\\tvarying vec2 vEmissiveMapUv;\\n#endif\\n#ifdef USE_METALNESSMAP\\n\\tuniform mat3 metalnessMapTransform;\\n\\tvarying vec2 vMetalnessMapUv;\\n#endif\\n#ifdef USE_ROUGHNESSMAP\\n\\tuniform mat3 roughnessMapTransform;\\n\\tvarying vec2 vRoughnessMapUv;\\n#endif\\n#ifdef USE_CLEARCOATMAP\\n\\tuniform mat3 clearcoatMapTransform;\\n\\tvarying vec2 vClearcoatMapUv;\\n#endif\\n#ifdef USE_CLEARCOAT_NORMALMAP\\n\\tuniform mat3 clearcoatNormalMapTransform;\\n\\tvarying vec2 vClearcoatNormalMapUv;\\n#endif\\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\\n\\tuniform mat3 clearcoatRoughnessMapTransform;\\n\\tvarying vec2 vClearcoatRoughnessMapUv;\\n#endif\\n#ifdef USE_SHEEN_COLORMAP\\n\\tuniform mat3 sheenColorMapTransform;\\n\\tvarying vec2 vSheenColorMapUv;\\n#endif\\n#ifdef USE_SHEEN_ROUGHNESSMAP\\n\\tuniform mat3 sheenRoughnessMapTransform;\\n\\tvarying vec2 vSheenRoughnessMapUv;\\n#endif\\n#ifdef USE_IRIDESCENCEMAP\\n\\tuniform mat3 iridescenceMapTransform;\\n\\tvarying vec2 vIridescenceMapUv;\\n#endif\\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\\n\\tuniform mat3 iridescenceThicknessMapTransform;\\n\\tvarying vec2 vIridescenceThicknessMapUv;\\n#endif\\n#ifdef USE_SPECULARMAP\\n\\tuniform mat3 specularMapTransform;\\n\\tvarying vec2 vSpecularMapUv;\\n#endif\\n#ifdef USE_SPECULAR_COLORMAP\\n\\tuniform mat3 specularColorMapTransform;\\n\\tvarying vec2 vSpecularColorMapUv;\\n#endif\\n#ifdef USE_SPECULAR_INTENSITYMAP\\n\\tuniform mat3 specularIntensityMapTransform;\\n\\tvarying vec2 vSpecularIntensityMapUv;\\n#endif\\n#ifdef USE_TRANSMISSIONMAP\\n\\tuniform mat3 transmissionMapTransform;\\n\\tvarying vec2 vTransmissionMapUv;\\n#endif\\n#ifdef USE_THICKNESSMAP\\n\\tuniform mat3 thicknessMapTransform;\\n\\tvarying vec2 vThicknessMapUv;\\n#endif\";\n\nvar uv_vertex = \"#ifdef USE_UV\\n\\tvUv = vec3( uv, 1 ).xy;\\n#endif\\n#ifdef USE_MAP\\n\\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_ALPHAMAP\\n\\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_LIGHTMAP\\n\\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_AOMAP\\n\\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_BUMPMAP\\n\\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_NORMALMAP\\n\\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_DISPLACEMENTMAP\\n\\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_EMISSIVEMAP\\n\\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_METALNESSMAP\\n\\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_ROUGHNESSMAP\\n\\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_CLEARCOATMAP\\n\\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_CLEARCOAT_NORMALMAP\\n\\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\\n\\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_IRIDESCENCEMAP\\n\\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\\n\\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_SHEEN_COLORMAP\\n\\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_SHEEN_ROUGHNESSMAP\\n\\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_SPECULARMAP\\n\\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_SPECULAR_COLORMAP\\n\\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_SPECULAR_INTENSITYMAP\\n\\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_TRANSMISSIONMAP\\n\\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\\n#endif\\n#ifdef USE_THICKNESSMAP\\n\\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\\n#endif\";\n\nvar worldpos_vertex = \"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\\n\\tvec4 worldPosition = vec4( transformed, 1.0 );\\n\\t#ifdef USE_INSTANCING\\n\\t\\tworldPosition = instanceMatrix * worldPosition;\\n\\t#endif\\n\\tworldPosition = modelMatrix * worldPosition;\\n#endif\";\n\nconst vertex$h = \"varying vec2 vUv;\\nuniform mat3 uvTransform;\\nvoid main() {\\n\\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\\n\\tgl_Position = vec4( position.xy, 1.0, 1.0 );\\n}\";\n\nconst fragment$h = \"uniform sampler2D t2D;\\nuniform float backgroundIntensity;\\nvarying vec2 vUv;\\nvoid main() {\\n\\tvec4 texColor = texture2D( t2D, vUv );\\n\\ttexColor.rgb *= backgroundIntensity;\\n\\tgl_FragColor = texColor;\\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$g = \"varying vec3 vWorldDirection;\\n#include \\nvoid main() {\\n\\tvWorldDirection = transformDirection( position, modelMatrix );\\n\\t#include \\n\\t#include \\n\\tgl_Position.z = gl_Position.w;\\n}\";\n\nconst fragment$g = \"#ifdef ENVMAP_TYPE_CUBE\\n\\tuniform samplerCube envMap;\\n#elif defined( ENVMAP_TYPE_CUBE_UV )\\n\\tuniform sampler2D envMap;\\n#endif\\nuniform float flipEnvMap;\\nuniform float backgroundBlurriness;\\nuniform float backgroundIntensity;\\nvarying vec3 vWorldDirection;\\n#include \\nvoid main() {\\n\\t#ifdef ENVMAP_TYPE_CUBE\\n\\t\\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\\n\\t#elif defined( ENVMAP_TYPE_CUBE_UV )\\n\\t\\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\\n\\t#else\\n\\t\\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\\n\\t#endif\\n\\ttexColor.rgb *= backgroundIntensity;\\n\\tgl_FragColor = texColor;\\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$f = \"varying vec3 vWorldDirection;\\n#include \\nvoid main() {\\n\\tvWorldDirection = transformDirection( position, modelMatrix );\\n\\t#include \\n\\t#include \\n\\tgl_Position.z = gl_Position.w;\\n}\";\n\nconst fragment$f = \"uniform samplerCube tCube;\\nuniform float tFlip;\\nuniform float opacity;\\nvarying vec3 vWorldDirection;\\nvoid main() {\\n\\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\\n\\tgl_FragColor = texColor;\\n\\tgl_FragColor.a *= opacity;\\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$e = \"#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvarying vec2 vHighPrecisionZW;\\nvoid main() {\\n\\t#include \\n\\t#include \\n\\t#ifdef USE_DISPLACEMENTMAP\\n\\t\\t#include \\n\\t\\t#include \\n\\t\\t#include \\n\\t#endif\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tvHighPrecisionZW = gl_Position.zw;\\n}\";\n\nconst fragment$e = \"#if DEPTH_PACKING == 3200\\n\\tuniform float opacity;\\n#endif\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvarying vec2 vHighPrecisionZW;\\nvoid main() {\\n\\t#include \\n\\tvec4 diffuseColor = vec4( 1.0 );\\n\\t#if DEPTH_PACKING == 3200\\n\\t\\tdiffuseColor.a = opacity;\\n\\t#endif\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\\n\\t#if DEPTH_PACKING == 3200\\n\\t\\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\\n\\t#elif DEPTH_PACKING == 3201\\n\\t\\tgl_FragColor = packDepthToRGBA( fragCoordZ );\\n\\t#endif\\n}\";\n\nconst vertex$d = \"#define DISTANCE\\nvarying vec3 vWorldPosition;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\t#include \\n\\t#ifdef USE_DISPLACEMENTMAP\\n\\t\\t#include \\n\\t\\t#include \\n\\t\\t#include \\n\\t#endif\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tvWorldPosition = worldPosition.xyz;\\n}\";\n\nconst fragment$d = \"#define DISTANCE\\nuniform vec3 referencePosition;\\nuniform float nearDistance;\\nuniform float farDistance;\\nvarying vec3 vWorldPosition;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main () {\\n\\t#include \\n\\tvec4 diffuseColor = vec4( 1.0 );\\n\\t#include \\n\\t#include \\n\\t#include \\n\\tfloat dist = length( vWorldPosition - referencePosition );\\n\\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\\n\\tdist = saturate( dist );\\n\\tgl_FragColor = packDepthToRGBA( dist );\\n}\";\n\nconst vertex$c = \"varying vec3 vWorldDirection;\\n#include \\nvoid main() {\\n\\tvWorldDirection = transformDirection( position, modelMatrix );\\n\\t#include \\n\\t#include \\n}\";\n\nconst fragment$c = \"uniform sampler2D tEquirect;\\nvarying vec3 vWorldDirection;\\n#include \\nvoid main() {\\n\\tvec3 direction = normalize( vWorldDirection );\\n\\tvec2 sampleUV = equirectUv( direction );\\n\\tgl_FragColor = texture2D( tEquirect, sampleUV );\\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$b = \"uniform float scale;\\nattribute float lineDistance;\\nvarying float vLineDistance;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\tvLineDistance = scale * lineDistance;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst fragment$b = \"uniform vec3 diffuse;\\nuniform float opacity;\\nuniform float dashSize;\\nuniform float totalSize;\\nvarying float vLineDistance;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\\n\\t\\tdiscard;\\n\\t}\\n\\tvec3 outgoingLight = vec3( 0.0 );\\n\\tvec4 diffuseColor = vec4( diffuse, opacity );\\n\\t#include \\n\\t#include \\n\\t#include \\n\\toutgoingLight = diffuseColor.rgb;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$a = \"#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\\n\\t\\t#include \\n\\t\\t#include \\n\\t\\t#include \\n\\t\\t#include \\n\\t\\t#include \\n\\t#endif\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst fragment$a = \"uniform vec3 diffuse;\\nuniform float opacity;\\n#ifndef FLAT_SHADED\\n\\tvarying vec3 vNormal;\\n#endif\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\tvec4 diffuseColor = vec4( diffuse, opacity );\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\\n\\t#ifdef USE_LIGHTMAP\\n\\t\\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\\n\\t\\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\\n\\t#else\\n\\t\\treflectedLight.indirectDiffuse += vec3( 1.0 );\\n\\t#endif\\n\\t#include \\n\\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\\n\\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$9 = \"#define LAMBERT\\nvarying vec3 vViewPosition;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tvViewPosition = - mvPosition.xyz;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst fragment$9 = \"#define LAMBERT\\nuniform vec3 diffuse;\\nuniform vec3 emissive;\\nuniform float opacity;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\tvec4 diffuseColor = vec4( diffuse, opacity );\\n\\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\\n\\tvec3 totalEmissiveRadiance = emissive;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$8 = \"#define MATCAP\\nvarying vec3 vViewPosition;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tvViewPosition = - mvPosition.xyz;\\n}\";\n\nconst fragment$8 = \"#define MATCAP\\nuniform vec3 diffuse;\\nuniform float opacity;\\nuniform sampler2D matcap;\\nvarying vec3 vViewPosition;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\tvec4 diffuseColor = vec4( diffuse, opacity );\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tvec3 viewDir = normalize( vViewPosition );\\n\\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\\n\\tvec3 y = cross( viewDir, x );\\n\\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\\n\\t#ifdef USE_MATCAP\\n\\t\\tvec4 matcapColor = texture2D( matcap, uv );\\n\\t#else\\n\\t\\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\\n\\t#endif\\n\\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$7 = \"#define NORMAL\\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\\n\\tvarying vec3 vViewPosition;\\n#endif\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\\n\\tvViewPosition = - mvPosition.xyz;\\n#endif\\n}\";\n\nconst fragment$7 = \"#define NORMAL\\nuniform float opacity;\\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\\n\\tvarying vec3 vViewPosition;\\n#endif\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\\n\\t#ifdef OPAQUE\\n\\t\\tgl_FragColor.a = 1.0;\\n\\t#endif\\n}\";\n\nconst vertex$6 = \"#define PHONG\\nvarying vec3 vViewPosition;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tvViewPosition = - mvPosition.xyz;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst fragment$6 = \"#define PHONG\\nuniform vec3 diffuse;\\nuniform vec3 emissive;\\nuniform vec3 specular;\\nuniform float shininess;\\nuniform float opacity;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\tvec4 diffuseColor = vec4( diffuse, opacity );\\n\\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\\n\\tvec3 totalEmissiveRadiance = emissive;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$5 = \"#define STANDARD\\nvarying vec3 vViewPosition;\\n#ifdef USE_TRANSMISSION\\n\\tvarying vec3 vWorldPosition;\\n#endif\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tvViewPosition = - mvPosition.xyz;\\n\\t#include \\n\\t#include \\n\\t#include \\n#ifdef USE_TRANSMISSION\\n\\tvWorldPosition = worldPosition.xyz;\\n#endif\\n}\";\n\nconst fragment$5 = \"#define STANDARD\\n#ifdef PHYSICAL\\n\\t#define IOR\\n\\t#define USE_SPECULAR\\n#endif\\nuniform vec3 diffuse;\\nuniform vec3 emissive;\\nuniform float roughness;\\nuniform float metalness;\\nuniform float opacity;\\n#ifdef IOR\\n\\tuniform float ior;\\n#endif\\n#ifdef USE_SPECULAR\\n\\tuniform float specularIntensity;\\n\\tuniform vec3 specularColor;\\n\\t#ifdef USE_SPECULAR_COLORMAP\\n\\t\\tuniform sampler2D specularColorMap;\\n\\t#endif\\n\\t#ifdef USE_SPECULAR_INTENSITYMAP\\n\\t\\tuniform sampler2D specularIntensityMap;\\n\\t#endif\\n#endif\\n#ifdef USE_CLEARCOAT\\n\\tuniform float clearcoat;\\n\\tuniform float clearcoatRoughness;\\n#endif\\n#ifdef USE_IRIDESCENCE\\n\\tuniform float iridescence;\\n\\tuniform float iridescenceIOR;\\n\\tuniform float iridescenceThicknessMinimum;\\n\\tuniform float iridescenceThicknessMaximum;\\n#endif\\n#ifdef USE_SHEEN\\n\\tuniform vec3 sheenColor;\\n\\tuniform float sheenRoughness;\\n\\t#ifdef USE_SHEEN_COLORMAP\\n\\t\\tuniform sampler2D sheenColorMap;\\n\\t#endif\\n\\t#ifdef USE_SHEEN_ROUGHNESSMAP\\n\\t\\tuniform sampler2D sheenRoughnessMap;\\n\\t#endif\\n#endif\\nvarying vec3 vViewPosition;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\tvec4 diffuseColor = vec4( diffuse, opacity );\\n\\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\\n\\tvec3 totalEmissiveRadiance = emissive;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\\n\\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\\n\\t#include \\n\\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\\n\\t#ifdef USE_SHEEN\\n\\t\\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\\n\\t\\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\\n\\t#endif\\n\\t#ifdef USE_CLEARCOAT\\n\\t\\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\\n\\t\\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\\n\\t\\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\\n\\t#endif\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$4 = \"#define TOON\\nvarying vec3 vViewPosition;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tvViewPosition = - mvPosition.xyz;\\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst fragment$4 = \"#define TOON\\nuniform vec3 diffuse;\\nuniform vec3 emissive;\\nuniform float opacity;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\tvec4 diffuseColor = vec4( diffuse, opacity );\\n\\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\\n\\tvec3 totalEmissiveRadiance = emissive;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$3 = \"uniform float size;\\nuniform float scale;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#ifdef USE_POINTS_UV\\n\\tvarying vec2 vUv;\\n\\tuniform mat3 uvTransform;\\n#endif\\nvoid main() {\\n\\t#ifdef USE_POINTS_UV\\n\\t\\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\\n\\t#endif\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\tgl_PointSize = size;\\n\\t#ifdef USE_SIZEATTENUATION\\n\\t\\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\\n\\t\\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\\n\\t#endif\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst fragment$3 = \"uniform vec3 diffuse;\\nuniform float opacity;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\tvec3 outgoingLight = vec3( 0.0 );\\n\\tvec4 diffuseColor = vec4( diffuse, opacity );\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\toutgoingLight = diffuseColor.rgb;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$2 = \"#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst fragment$2 = \"uniform vec3 color;\\nuniform float opacity;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst vertex$1 = \"uniform float rotation;\\nuniform vec2 center;\\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\\n\\tvec2 scale;\\n\\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\\n\\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\\n\\t#ifndef USE_SIZEATTENUATION\\n\\t\\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\\n\\t\\tif ( isPerspective ) scale *= - mvPosition.z;\\n\\t#endif\\n\\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\\n\\tvec2 rotatedPosition;\\n\\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\\n\\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\\n\\tmvPosition.xy += rotatedPosition;\\n\\tgl_Position = projectionMatrix * mvPosition;\\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst fragment$1 = \"uniform vec3 diffuse;\\nuniform float opacity;\\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\n#include \\nvoid main() {\\n\\t#include \\n\\tvec3 outgoingLight = vec3( 0.0 );\\n\\tvec4 diffuseColor = vec4( diffuse, opacity );\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n\\toutgoingLight = diffuseColor.rgb;\\n\\t#include \\n\\t#include \\n\\t#include \\n\\t#include \\n}\";\n\nconst ShaderChunk = {\n\talphamap_fragment: alphamap_fragment,\n\talphamap_pars_fragment: alphamap_pars_fragment,\n\talphatest_fragment: alphatest_fragment,\n\talphatest_pars_fragment: alphatest_pars_fragment,\n\taomap_fragment: aomap_fragment,\n\taomap_pars_fragment: aomap_pars_fragment,\n\tbegin_vertex: begin_vertex,\n\tbeginnormal_vertex: beginnormal_vertex,\n\tbsdfs: bsdfs,\n\tiridescence_fragment: iridescence_fragment,\n\tbumpmap_pars_fragment: bumpmap_pars_fragment,\n\tclipping_planes_fragment: clipping_planes_fragment,\n\tclipping_planes_pars_fragment: clipping_planes_pars_fragment,\n\tclipping_planes_pars_vertex: clipping_planes_pars_vertex,\n\tclipping_planes_vertex: clipping_planes_vertex,\n\tcolor_fragment: color_fragment,\n\tcolor_pars_fragment: color_pars_fragment,\n\tcolor_pars_vertex: color_pars_vertex,\n\tcolor_vertex: color_vertex,\n\tcommon: common,\n\tcube_uv_reflection_fragment: cube_uv_reflection_fragment,\n\tdefaultnormal_vertex: defaultnormal_vertex,\n\tdisplacementmap_pars_vertex: displacementmap_pars_vertex,\n\tdisplacementmap_vertex: displacementmap_vertex,\n\temissivemap_fragment: emissivemap_fragment,\n\temissivemap_pars_fragment: emissivemap_pars_fragment,\n\tencodings_fragment: encodings_fragment,\n\tencodings_pars_fragment: encodings_pars_fragment,\n\tenvmap_fragment: envmap_fragment,\n\tenvmap_common_pars_fragment: envmap_common_pars_fragment,\n\tenvmap_pars_fragment: envmap_pars_fragment,\n\tenvmap_pars_vertex: envmap_pars_vertex,\n\tenvmap_physical_pars_fragment: envmap_physical_pars_fragment,\n\tenvmap_vertex: envmap_vertex,\n\tfog_vertex: fog_vertex,\n\tfog_pars_vertex: fog_pars_vertex,\n\tfog_fragment: fog_fragment,\n\tfog_pars_fragment: fog_pars_fragment,\n\tgradientmap_pars_fragment: gradientmap_pars_fragment,\n\tlightmap_fragment: lightmap_fragment,\n\tlightmap_pars_fragment: lightmap_pars_fragment,\n\tlights_lambert_fragment: lights_lambert_fragment,\n\tlights_lambert_pars_fragment: lights_lambert_pars_fragment,\n\tlights_pars_begin: lights_pars_begin,\n\tlights_toon_fragment: lights_toon_fragment,\n\tlights_toon_pars_fragment: lights_toon_pars_fragment,\n\tlights_phong_fragment: lights_phong_fragment,\n\tlights_phong_pars_fragment: lights_phong_pars_fragment,\n\tlights_physical_fragment: lights_physical_fragment,\n\tlights_physical_pars_fragment: lights_physical_pars_fragment,\n\tlights_fragment_begin: lights_fragment_begin,\n\tlights_fragment_maps: lights_fragment_maps,\n\tlights_fragment_end: lights_fragment_end,\n\tlogdepthbuf_fragment: logdepthbuf_fragment,\n\tlogdepthbuf_pars_fragment: logdepthbuf_pars_fragment,\n\tlogdepthbuf_pars_vertex: logdepthbuf_pars_vertex,\n\tlogdepthbuf_vertex: logdepthbuf_vertex,\n\tmap_fragment: map_fragment,\n\tmap_pars_fragment: map_pars_fragment,\n\tmap_particle_fragment: map_particle_fragment,\n\tmap_particle_pars_fragment: map_particle_pars_fragment,\n\tmetalnessmap_fragment: metalnessmap_fragment,\n\tmetalnessmap_pars_fragment: metalnessmap_pars_fragment,\n\tmorphcolor_vertex: morphcolor_vertex,\n\tmorphnormal_vertex: morphnormal_vertex,\n\tmorphtarget_pars_vertex: morphtarget_pars_vertex,\n\tmorphtarget_vertex: morphtarget_vertex,\n\tnormal_fragment_begin: normal_fragment_begin,\n\tnormal_fragment_maps: normal_fragment_maps,\n\tnormal_pars_fragment: normal_pars_fragment,\n\tnormal_pars_vertex: normal_pars_vertex,\n\tnormal_vertex: normal_vertex,\n\tnormalmap_pars_fragment: normalmap_pars_fragment,\n\tclearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,\n\tclearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,\n\tclearcoat_pars_fragment: clearcoat_pars_fragment,\n\tiridescence_pars_fragment: iridescence_pars_fragment,\n\toutput_fragment: output_fragment,\n\tpacking: packing,\n\tpremultiplied_alpha_fragment: premultiplied_alpha_fragment,\n\tproject_vertex: project_vertex,\n\tdithering_fragment: dithering_fragment,\n\tdithering_pars_fragment: dithering_pars_fragment,\n\troughnessmap_fragment: roughnessmap_fragment,\n\troughnessmap_pars_fragment: roughnessmap_pars_fragment,\n\tshadowmap_pars_fragment: shadowmap_pars_fragment,\n\tshadowmap_pars_vertex: shadowmap_pars_vertex,\n\tshadowmap_vertex: shadowmap_vertex,\n\tshadowmask_pars_fragment: shadowmask_pars_fragment,\n\tskinbase_vertex: skinbase_vertex,\n\tskinning_pars_vertex: skinning_pars_vertex,\n\tskinning_vertex: skinning_vertex,\n\tskinnormal_vertex: skinnormal_vertex,\n\tspecularmap_fragment: specularmap_fragment,\n\tspecularmap_pars_fragment: specularmap_pars_fragment,\n\ttonemapping_fragment: tonemapping_fragment,\n\ttonemapping_pars_fragment: tonemapping_pars_fragment,\n\ttransmission_fragment: transmission_fragment,\n\ttransmission_pars_fragment: transmission_pars_fragment,\n\tuv_pars_fragment: uv_pars_fragment,\n\tuv_pars_vertex: uv_pars_vertex,\n\tuv_vertex: uv_vertex,\n\tworldpos_vertex: worldpos_vertex,\n\n\tbackground_vert: vertex$h,\n\tbackground_frag: fragment$h,\n\tbackgroundCube_vert: vertex$g,\n\tbackgroundCube_frag: fragment$g,\n\tcube_vert: vertex$f,\n\tcube_frag: fragment$f,\n\tdepth_vert: vertex$e,\n\tdepth_frag: fragment$e,\n\tdistanceRGBA_vert: vertex$d,\n\tdistanceRGBA_frag: fragment$d,\n\tequirect_vert: vertex$c,\n\tequirect_frag: fragment$c,\n\tlinedashed_vert: vertex$b,\n\tlinedashed_frag: fragment$b,\n\tmeshbasic_vert: vertex$a,\n\tmeshbasic_frag: fragment$a,\n\tmeshlambert_vert: vertex$9,\n\tmeshlambert_frag: fragment$9,\n\tmeshmatcap_vert: vertex$8,\n\tmeshmatcap_frag: fragment$8,\n\tmeshnormal_vert: vertex$7,\n\tmeshnormal_frag: fragment$7,\n\tmeshphong_vert: vertex$6,\n\tmeshphong_frag: fragment$6,\n\tmeshphysical_vert: vertex$5,\n\tmeshphysical_frag: fragment$5,\n\tmeshtoon_vert: vertex$4,\n\tmeshtoon_frag: fragment$4,\n\tpoints_vert: vertex$3,\n\tpoints_frag: fragment$3,\n\tshadow_vert: vertex$2,\n\tshadow_frag: fragment$2,\n\tsprite_vert: vertex$1,\n\tsprite_frag: fragment$1\n};\n\n/**\n * Uniforms library for shared webgl shaders\n */\n\nconst UniformsLib = {\n\n\tcommon: {\n\n\t\tdiffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },\n\t\topacity: { value: 1.0 },\n\n\t\tmap: { value: null },\n\t\tmapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\n\t\talphaMap: { value: null },\n\t\talphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\n\t\talphaTest: { value: 0 }\n\n\t},\n\n\tspecularmap: {\n\n\t\tspecularMap: { value: null },\n\t\tspecularMapTransform: { value: /*@__PURE__*/ new Matrix3() }\n\n\t},\n\n\tenvmap: {\n\n\t\tenvMap: { value: null },\n\t\tflipEnvMap: { value: - 1 },\n\t\treflectivity: { value: 1.0 }, // basic, lambert, phong\n\t\tior: { value: 1.5 }, // physical\n\t\trefractionRatio: { value: 0.98 }, // basic, lambert, phong\n\n\t},\n\n\taomap: {\n\n\t\taoMap: { value: null },\n\t\taoMapIntensity: { value: 1 },\n\t\taoMapTransform: { value: /*@__PURE__*/ new Matrix3() }\n\n\t},\n\n\tlightmap: {\n\n\t\tlightMap: { value: null },\n\t\tlightMapIntensity: { value: 1 },\n\t\tlightMapTransform: { value: /*@__PURE__*/ new Matrix3() }\n\n\t},\n\n\tbumpmap: {\n\n\t\tbumpMap: { value: null },\n\t\tbumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\tbumpScale: { value: 1 }\n\n\t},\n\n\tnormalmap: {\n\n\t\tnormalMap: { value: null },\n\t\tnormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\tnormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }\n\n\t},\n\n\tdisplacementmap: {\n\n\t\tdisplacementMap: { value: null },\n\t\tdisplacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\tdisplacementScale: { value: 1 },\n\t\tdisplacementBias: { value: 0 }\n\n\t},\n\n\temissivemap: {\n\n\t\temissiveMap: { value: null },\n\t\temissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }\n\n\t},\n\n\tmetalnessmap: {\n\n\t\tmetalnessMap: { value: null },\n\t\tmetalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }\n\n\t},\n\n\troughnessmap: {\n\n\t\troughnessMap: { value: null },\n\t\troughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }\n\n\t},\n\n\tgradientmap: {\n\n\t\tgradientMap: { value: null }\n\n\t},\n\n\tfog: {\n\n\t\tfogDensity: { value: 0.00025 },\n\t\tfogNear: { value: 1 },\n\t\tfogFar: { value: 2000 },\n\t\tfogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }\n\n\t},\n\n\tlights: {\n\n\t\tambientLightColor: { value: [] },\n\n\t\tlightProbe: { value: [] },\n\n\t\tdirectionalLights: { value: [], properties: {\n\t\t\tdirection: {},\n\t\t\tcolor: {}\n\t\t} },\n\n\t\tdirectionalLightShadows: { value: [], properties: {\n\t\t\tshadowBias: {},\n\t\t\tshadowNormalBias: {},\n\t\t\tshadowRadius: {},\n\t\t\tshadowMapSize: {}\n\t\t} },\n\n\t\tdirectionalShadowMap: { value: [] },\n\t\tdirectionalShadowMatrix: { value: [] },\n\n\t\tspotLights: { value: [], properties: {\n\t\t\tcolor: {},\n\t\t\tposition: {},\n\t\t\tdirection: {},\n\t\t\tdistance: {},\n\t\t\tconeCos: {},\n\t\t\tpenumbraCos: {},\n\t\t\tdecay: {}\n\t\t} },\n\n\t\tspotLightShadows: { value: [], properties: {\n\t\t\tshadowBias: {},\n\t\t\tshadowNormalBias: {},\n\t\t\tshadowRadius: {},\n\t\t\tshadowMapSize: {}\n\t\t} },\n\n\t\tspotLightMap: { value: [] },\n\t\tspotShadowMap: { value: [] },\n\t\tspotLightMatrix: { value: [] },\n\n\t\tpointLights: { value: [], properties: {\n\t\t\tcolor: {},\n\t\t\tposition: {},\n\t\t\tdecay: {},\n\t\t\tdistance: {}\n\t\t} },\n\n\t\tpointLightShadows: { value: [], properties: {\n\t\t\tshadowBias: {},\n\t\t\tshadowNormalBias: {},\n\t\t\tshadowRadius: {},\n\t\t\tshadowMapSize: {},\n\t\t\tshadowCameraNear: {},\n\t\t\tshadowCameraFar: {}\n\t\t} },\n\n\t\tpointShadowMap: { value: [] },\n\t\tpointShadowMatrix: { value: [] },\n\n\t\themisphereLights: { value: [], properties: {\n\t\t\tdirection: {},\n\t\t\tskyColor: {},\n\t\t\tgroundColor: {}\n\t\t} },\n\n\t\t// TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src\n\t\trectAreaLights: { value: [], properties: {\n\t\t\tcolor: {},\n\t\t\tposition: {},\n\t\t\twidth: {},\n\t\t\theight: {}\n\t\t} },\n\n\t\tltc_1: { value: null },\n\t\tltc_2: { value: null }\n\n\t},\n\n\tpoints: {\n\n\t\tdiffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },\n\t\topacity: { value: 1.0 },\n\t\tsize: { value: 1.0 },\n\t\tscale: { value: 1.0 },\n\t\tmap: { value: null },\n\t\talphaMap: { value: null },\n\t\talphaTest: { value: 0 },\n\t\tuvTransform: { value: /*@__PURE__*/ new Matrix3() }\n\n\t},\n\n\tsprite: {\n\n\t\tdiffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },\n\t\topacity: { value: 1.0 },\n\t\tcenter: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },\n\t\trotation: { value: 0.0 },\n\t\tmap: { value: null },\n\t\tmapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\talphaMap: { value: null },\n\t\talphaTest: { value: 0 }\n\n\t}\n\n};\n\nconst ShaderLib = {\n\n\tbasic: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.common,\n\t\t\tUniformsLib.specularmap,\n\t\t\tUniformsLib.envmap,\n\t\t\tUniformsLib.aomap,\n\t\t\tUniformsLib.lightmap,\n\t\t\tUniformsLib.fog\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.meshbasic_vert,\n\t\tfragmentShader: ShaderChunk.meshbasic_frag\n\n\t},\n\n\tlambert: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.common,\n\t\t\tUniformsLib.specularmap,\n\t\t\tUniformsLib.envmap,\n\t\t\tUniformsLib.aomap,\n\t\t\tUniformsLib.lightmap,\n\t\t\tUniformsLib.emissivemap,\n\t\t\tUniformsLib.bumpmap,\n\t\t\tUniformsLib.normalmap,\n\t\t\tUniformsLib.displacementmap,\n\t\t\tUniformsLib.fog,\n\t\t\tUniformsLib.lights,\n\t\t\t{\n\t\t\t\temissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }\n\t\t\t}\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.meshlambert_vert,\n\t\tfragmentShader: ShaderChunk.meshlambert_frag\n\n\t},\n\n\tphong: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.common,\n\t\t\tUniformsLib.specularmap,\n\t\t\tUniformsLib.envmap,\n\t\t\tUniformsLib.aomap,\n\t\t\tUniformsLib.lightmap,\n\t\t\tUniformsLib.emissivemap,\n\t\t\tUniformsLib.bumpmap,\n\t\t\tUniformsLib.normalmap,\n\t\t\tUniformsLib.displacementmap,\n\t\t\tUniformsLib.fog,\n\t\t\tUniformsLib.lights,\n\t\t\t{\n\t\t\t\temissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },\n\t\t\t\tspecular: { value: /*@__PURE__*/ new Color( 0x111111 ) },\n\t\t\t\tshininess: { value: 30 }\n\t\t\t}\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.meshphong_vert,\n\t\tfragmentShader: ShaderChunk.meshphong_frag\n\n\t},\n\n\tstandard: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.common,\n\t\t\tUniformsLib.envmap,\n\t\t\tUniformsLib.aomap,\n\t\t\tUniformsLib.lightmap,\n\t\t\tUniformsLib.emissivemap,\n\t\t\tUniformsLib.bumpmap,\n\t\t\tUniformsLib.normalmap,\n\t\t\tUniformsLib.displacementmap,\n\t\t\tUniformsLib.roughnessmap,\n\t\t\tUniformsLib.metalnessmap,\n\t\t\tUniformsLib.fog,\n\t\t\tUniformsLib.lights,\n\t\t\t{\n\t\t\t\temissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },\n\t\t\t\troughness: { value: 1.0 },\n\t\t\t\tmetalness: { value: 0.0 },\n\t\t\t\tenvMapIntensity: { value: 1 } // temporary\n\t\t\t}\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.meshphysical_vert,\n\t\tfragmentShader: ShaderChunk.meshphysical_frag\n\n\t},\n\n\ttoon: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.common,\n\t\t\tUniformsLib.aomap,\n\t\t\tUniformsLib.lightmap,\n\t\t\tUniformsLib.emissivemap,\n\t\t\tUniformsLib.bumpmap,\n\t\t\tUniformsLib.normalmap,\n\t\t\tUniformsLib.displacementmap,\n\t\t\tUniformsLib.gradientmap,\n\t\t\tUniformsLib.fog,\n\t\t\tUniformsLib.lights,\n\t\t\t{\n\t\t\t\temissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }\n\t\t\t}\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.meshtoon_vert,\n\t\tfragmentShader: ShaderChunk.meshtoon_frag\n\n\t},\n\n\tmatcap: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.common,\n\t\t\tUniformsLib.bumpmap,\n\t\t\tUniformsLib.normalmap,\n\t\t\tUniformsLib.displacementmap,\n\t\t\tUniformsLib.fog,\n\t\t\t{\n\t\t\t\tmatcap: { value: null }\n\t\t\t}\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.meshmatcap_vert,\n\t\tfragmentShader: ShaderChunk.meshmatcap_frag\n\n\t},\n\n\tpoints: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.points,\n\t\t\tUniformsLib.fog\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.points_vert,\n\t\tfragmentShader: ShaderChunk.points_frag\n\n\t},\n\n\tdashed: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.common,\n\t\t\tUniformsLib.fog,\n\t\t\t{\n\t\t\t\tscale: { value: 1 },\n\t\t\t\tdashSize: { value: 1 },\n\t\t\t\ttotalSize: { value: 2 }\n\t\t\t}\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.linedashed_vert,\n\t\tfragmentShader: ShaderChunk.linedashed_frag\n\n\t},\n\n\tdepth: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.common,\n\t\t\tUniformsLib.displacementmap\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.depth_vert,\n\t\tfragmentShader: ShaderChunk.depth_frag\n\n\t},\n\n\tnormal: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.common,\n\t\t\tUniformsLib.bumpmap,\n\t\t\tUniformsLib.normalmap,\n\t\t\tUniformsLib.displacementmap,\n\t\t\t{\n\t\t\t\topacity: { value: 1.0 }\n\t\t\t}\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.meshnormal_vert,\n\t\tfragmentShader: ShaderChunk.meshnormal_frag\n\n\t},\n\n\tsprite: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.sprite,\n\t\t\tUniformsLib.fog\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.sprite_vert,\n\t\tfragmentShader: ShaderChunk.sprite_frag\n\n\t},\n\n\tbackground: {\n\n\t\tuniforms: {\n\t\t\tuvTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\t\tt2D: { value: null },\n\t\t\tbackgroundIntensity: { value: 1 }\n\t\t},\n\n\t\tvertexShader: ShaderChunk.background_vert,\n\t\tfragmentShader: ShaderChunk.background_frag\n\n\t},\n\n\tbackgroundCube: {\n\n\t\tuniforms: {\n\t\t\tenvMap: { value: null },\n\t\t\tflipEnvMap: { value: - 1 },\n\t\t\tbackgroundBlurriness: { value: 0 },\n\t\t\tbackgroundIntensity: { value: 1 }\n\t\t},\n\n\t\tvertexShader: ShaderChunk.backgroundCube_vert,\n\t\tfragmentShader: ShaderChunk.backgroundCube_frag\n\n\t},\n\n\tcube: {\n\n\t\tuniforms: {\n\t\t\ttCube: { value: null },\n\t\t\ttFlip: { value: - 1 },\n\t\t\topacity: { value: 1.0 }\n\t\t},\n\n\t\tvertexShader: ShaderChunk.cube_vert,\n\t\tfragmentShader: ShaderChunk.cube_frag\n\n\t},\n\n\tequirect: {\n\n\t\tuniforms: {\n\t\t\ttEquirect: { value: null },\n\t\t},\n\n\t\tvertexShader: ShaderChunk.equirect_vert,\n\t\tfragmentShader: ShaderChunk.equirect_frag\n\n\t},\n\n\tdistanceRGBA: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.common,\n\t\t\tUniformsLib.displacementmap,\n\t\t\t{\n\t\t\t\treferencePosition: { value: /*@__PURE__*/ new Vector3() },\n\t\t\t\tnearDistance: { value: 1 },\n\t\t\t\tfarDistance: { value: 1000 }\n\t\t\t}\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.distanceRGBA_vert,\n\t\tfragmentShader: ShaderChunk.distanceRGBA_frag\n\n\t},\n\n\tshadow: {\n\n\t\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\t\tUniformsLib.lights,\n\t\t\tUniformsLib.fog,\n\t\t\t{\n\t\t\t\tcolor: { value: /*@__PURE__*/ new Color( 0x00000 ) },\n\t\t\t\topacity: { value: 1.0 }\n\t\t\t},\n\t\t] ),\n\n\t\tvertexShader: ShaderChunk.shadow_vert,\n\t\tfragmentShader: ShaderChunk.shadow_frag\n\n\t}\n\n};\n\nShaderLib.physical = {\n\n\tuniforms: /*@__PURE__*/ mergeUniforms( [\n\t\tShaderLib.standard.uniforms,\n\t\t{\n\t\t\tclearcoat: { value: 0 },\n\t\t\tclearcoatMap: { value: null },\n\t\t\tclearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\t\tclearcoatNormalMap: { value: null },\n\t\t\tclearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\t\tclearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },\n\t\t\tclearcoatRoughness: { value: 0 },\n\t\t\tclearcoatRoughnessMap: { value: null },\n\t\t\tclearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\t\tiridescence: { value: 0 },\n\t\t\tiridescenceMap: { value: null },\n\t\t\tiridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\t\tiridescenceIOR: { value: 1.3 },\n\t\t\tiridescenceThicknessMinimum: { value: 100 },\n\t\t\tiridescenceThicknessMaximum: { value: 400 },\n\t\t\tiridescenceThicknessMap: { value: null },\n\t\t\tiridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\t\tsheen: { value: 0 },\n\t\t\tsheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },\n\t\t\tsheenColorMap: { value: null },\n\t\t\tsheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\t\tsheenRoughness: { value: 1 },\n\t\t\tsheenRoughnessMap: { value: null },\n\t\t\tsheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\t\ttransmission: { value: 0 },\n\t\t\ttransmissionMap: { value: null },\n\t\t\ttransmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\t\ttransmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },\n\t\t\ttransmissionSamplerMap: { value: null },\n\t\t\tthickness: { value: 0 },\n\t\t\tthicknessMap: { value: null },\n\t\t\tthicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\t\tattenuationDistance: { value: 0 },\n\t\t\tattenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },\n\t\t\tspecularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },\n\t\t\tspecularColorMap: { value: null },\n\t\t\tspecularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },\n\t\t\tspecularIntensity: { value: 1 },\n\t\t\tspecularIntensityMap: { value: null },\n\t\t\tspecularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() }\n\t\t}\n\t] ),\n\n\tvertexShader: ShaderChunk.meshphysical_vert,\n\tfragmentShader: ShaderChunk.meshphysical_frag\n\n};\n\nconst _rgb = { r: 0, b: 0, g: 0 };\n\nfunction WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {\n\n\tconst clearColor = new Color( 0x000000 );\n\tlet clearAlpha = alpha === true ? 0 : 1;\n\n\tlet planeMesh;\n\tlet boxMesh;\n\n\tlet currentBackground = null;\n\tlet currentBackgroundVersion = 0;\n\tlet currentTonemapping = null;\n\n\tfunction render( renderList, scene ) {\n\n\t\tlet forceClear = false;\n\t\tlet background = scene.isScene === true ? scene.background : null;\n\n\t\tif ( background && background.isTexture ) {\n\n\t\t\tconst usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background\n\t\t\tbackground = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );\n\n\t\t}\n\n\t\tif ( background === null ) {\n\n\t\t\tsetClear( clearColor, clearAlpha );\n\n\t\t} else if ( background && background.isColor ) {\n\n\t\t\tsetClear( background, 1 );\n\t\t\tforceClear = true;\n\n\t\t}\n\n\t\tconst xr = renderer.xr;\n\t\tconst environmentBlendMode = xr.getEnvironmentBlendMode();\n\n\t\tswitch ( environmentBlendMode ) {\n\n\t\t\tcase 'opaque':\n\t\t\t\tforceClear = true;\n\t\t\t\tbreak;\n\n\t\t\tcase 'additive':\n\t\t\t\tstate.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );\n\t\t\t\tforceClear = true;\n\t\t\t\tbreak;\n\n\t\t\tcase 'alpha-blend':\n\t\t\t\tstate.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );\n\t\t\t\tforceClear = true;\n\t\t\t\tbreak;\n\n\t\t}\n\n\t\tif ( renderer.autoClear || forceClear ) {\n\n\t\t\trenderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );\n\n\t\t}\n\n\t\tif ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {\n\n\t\t\tif ( boxMesh === undefined ) {\n\n\t\t\t\tboxMesh = new Mesh(\n\t\t\t\t\tnew BoxGeometry( 1, 1, 1 ),\n\t\t\t\t\tnew ShaderMaterial( {\n\t\t\t\t\t\tname: 'BackgroundCubeMaterial',\n\t\t\t\t\t\tuniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),\n\t\t\t\t\t\tvertexShader: ShaderLib.backgroundCube.vertexShader,\n\t\t\t\t\t\tfragmentShader: ShaderLib.backgroundCube.fragmentShader,\n\t\t\t\t\t\tside: BackSide,\n\t\t\t\t\t\tdepthTest: false,\n\t\t\t\t\t\tdepthWrite: false,\n\t\t\t\t\t\tfog: false\n\t\t\t\t\t} )\n\t\t\t\t);\n\n\t\t\t\tboxMesh.geometry.deleteAttribute( 'normal' );\n\t\t\t\tboxMesh.geometry.deleteAttribute( 'uv' );\n\n\t\t\t\tboxMesh.onBeforeRender = function ( renderer, scene, camera ) {\n\n\t\t\t\t\tthis.matrixWorld.copyPosition( camera.matrixWorld );\n\n\t\t\t\t};\n\n\t\t\t\t// add \"envMap\" material property so the renderer can evaluate it like for built-in materials\n\t\t\t\tObject.defineProperty( boxMesh.material, 'envMap', {\n\n\t\t\t\t\tget: function () {\n\n\t\t\t\t\t\treturn this.uniforms.envMap.value;\n\n\t\t\t\t\t}\n\n\t\t\t\t} );\n\n\t\t\t\tobjects.update( boxMesh );\n\n\t\t\t}\n\n\t\t\tboxMesh.material.uniforms.envMap.value = background;\n\t\t\tboxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;\n\t\t\tboxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;\n\t\t\tboxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;\n\t\t\tboxMesh.material.toneMapped = ( background.colorSpace === SRGBColorSpace ) ? false : true;\n\n\t\t\tif ( currentBackground !== background ||\n\t\t\t\tcurrentBackgroundVersion !== background.version ||\n\t\t\t\tcurrentTonemapping !== renderer.toneMapping ) {\n\n\t\t\t\tboxMesh.material.needsUpdate = true;\n\n\t\t\t\tcurrentBackground = background;\n\t\t\t\tcurrentBackgroundVersion = background.version;\n\t\t\t\tcurrentTonemapping = renderer.toneMapping;\n\n\t\t\t}\n\n\t\t\tboxMesh.layers.enableAll();\n\n\t\t\t// push to the pre-sorted opaque render list\n\t\t\trenderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );\n\n\t\t} else if ( background && background.isTexture ) {\n\n\t\t\tif ( planeMesh === undefined ) {\n\n\t\t\t\tplaneMesh = new Mesh(\n\t\t\t\t\tnew PlaneGeometry( 2, 2 ),\n\t\t\t\t\tnew ShaderMaterial( {\n\t\t\t\t\t\tname: 'BackgroundMaterial',\n\t\t\t\t\t\tuniforms: cloneUniforms( ShaderLib.background.uniforms ),\n\t\t\t\t\t\tvertexShader: ShaderLib.background.vertexShader,\n\t\t\t\t\t\tfragmentShader: ShaderLib.background.fragmentShader,\n\t\t\t\t\t\tside: FrontSide,\n\t\t\t\t\t\tdepthTest: false,\n\t\t\t\t\t\tdepthWrite: false,\n\t\t\t\t\t\tfog: false\n\t\t\t\t\t} )\n\t\t\t\t);\n\n\t\t\t\tplaneMesh.geometry.deleteAttribute( 'normal' );\n\n\t\t\t\t// add \"map\" material property so the renderer can evaluate it like for built-in materials\n\t\t\t\tObject.defineProperty( planeMesh.material, 'map', {\n\n\t\t\t\t\tget: function () {\n\n\t\t\t\t\t\treturn this.uniforms.t2D.value;\n\n\t\t\t\t\t}\n\n\t\t\t\t} );\n\n\t\t\t\tobjects.update( planeMesh );\n\n\t\t\t}\n\n\t\t\tplaneMesh.material.uniforms.t2D.value = background;\n\t\t\tplaneMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;\n\t\t\tplaneMesh.material.toneMapped = ( background.colorSpace === SRGBColorSpace ) ? false : true;\n\n\t\t\tif ( background.matrixAutoUpdate === true ) {\n\n\t\t\t\tbackground.updateMatrix();\n\n\t\t\t}\n\n\t\t\tplaneMesh.material.uniforms.uvTransform.value.copy( background.matrix );\n\n\t\t\tif ( currentBackground !== background ||\n\t\t\t\tcurrentBackgroundVersion !== background.version ||\n\t\t\t\tcurrentTonemapping !== renderer.toneMapping ) {\n\n\t\t\t\tplaneMesh.material.needsUpdate = true;\n\n\t\t\t\tcurrentBackground = background;\n\t\t\t\tcurrentBackgroundVersion = background.version;\n\t\t\t\tcurrentTonemapping = renderer.toneMapping;\n\n\t\t\t}\n\n\t\t\tplaneMesh.layers.enableAll();\n\n\t\t\t// push to the pre-sorted opaque render list\n\t\t\trenderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );\n\n\t\t}\n\n\t}\n\n\tfunction setClear( color, alpha ) {\n\n\t\tcolor.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );\n\n\t\tstate.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );\n\n\t}\n\n\treturn {\n\n\t\tgetClearColor: function () {\n\n\t\t\treturn clearColor;\n\n\t\t},\n\t\tsetClearColor: function ( color, alpha = 1 ) {\n\n\t\t\tclearColor.set( color );\n\t\t\tclearAlpha = alpha;\n\t\t\tsetClear( clearColor, clearAlpha );\n\n\t\t},\n\t\tgetClearAlpha: function () {\n\n\t\t\treturn clearAlpha;\n\n\t\t},\n\t\tsetClearAlpha: function ( alpha ) {\n\n\t\t\tclearAlpha = alpha;\n\t\t\tsetClear( clearColor, clearAlpha );\n\n\t\t},\n\t\trender: render\n\n\t};\n\n}\n\nfunction WebGLBindingStates( gl, extensions, attributes, capabilities ) {\n\n\tconst maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );\n\n\tconst extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );\n\tconst vaoAvailable = capabilities.isWebGL2 || extension !== null;\n\n\tconst bindingStates = {};\n\n\tconst defaultState = createBindingState( null );\n\tlet currentState = defaultState;\n\tlet forceUpdate = false;\n\n\tfunction setup( object, material, program, geometry, index ) {\n\n\t\tlet updateBuffers = false;\n\n\t\tif ( vaoAvailable ) {\n\n\t\t\tconst state = getBindingState( geometry, program, material );\n\n\t\t\tif ( currentState !== state ) {\n\n\t\t\t\tcurrentState = state;\n\t\t\t\tbindVertexArrayObject( currentState.object );\n\n\t\t\t}\n\n\t\t\tupdateBuffers = needsUpdate( object, geometry, program, index );\n\n\t\t\tif ( updateBuffers ) saveCache( object, geometry, program, index );\n\n\t\t} else {\n\n\t\t\tconst wireframe = ( material.wireframe === true );\n\n\t\t\tif ( currentState.geometry !== geometry.id ||\n\t\t\t\tcurrentState.program !== program.id ||\n\t\t\t\tcurrentState.wireframe !== wireframe ) {\n\n\t\t\t\tcurrentState.geometry = geometry.id;\n\t\t\t\tcurrentState.program = program.id;\n\t\t\t\tcurrentState.wireframe = wireframe;\n\n\t\t\t\tupdateBuffers = true;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( index !== null ) {\n\n\t\t\tattributes.update( index, gl.ELEMENT_ARRAY_BUFFER );\n\n\t\t}\n\n\t\tif ( updateBuffers || forceUpdate ) {\n\n\t\t\tforceUpdate = false;\n\n\t\t\tsetupVertexAttributes( object, material, program, geometry );\n\n\t\t\tif ( index !== null ) {\n\n\t\t\t\tgl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tfunction createVertexArrayObject() {\n\n\t\tif ( capabilities.isWebGL2 ) return gl.createVertexArray();\n\n\t\treturn extension.createVertexArrayOES();\n\n\t}\n\n\tfunction bindVertexArrayObject( vao ) {\n\n\t\tif ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );\n\n\t\treturn extension.bindVertexArrayOES( vao );\n\n\t}\n\n\tfunction deleteVertexArrayObject( vao ) {\n\n\t\tif ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );\n\n\t\treturn extension.deleteVertexArrayOES( vao );\n\n\t}\n\n\tfunction getBindingState( geometry, program, material ) {\n\n\t\tconst wireframe = ( material.wireframe === true );\n\n\t\tlet programMap = bindingStates[ geometry.id ];\n\n\t\tif ( programMap === undefined ) {\n\n\t\t\tprogramMap = {};\n\t\t\tbindingStates[ geometry.id ] = programMap;\n\n\t\t}\n\n\t\tlet stateMap = programMap[ program.id ];\n\n\t\tif ( stateMap === undefined ) {\n\n\t\t\tstateMap = {};\n\t\t\tprogramMap[ program.id ] = stateMap;\n\n\t\t}\n\n\t\tlet state = stateMap[ wireframe ];\n\n\t\tif ( state === undefined ) {\n\n\t\t\tstate = createBindingState( createVertexArrayObject() );\n\t\t\tstateMap[ wireframe ] = state;\n\n\t\t}\n\n\t\treturn state;\n\n\t}\n\n\tfunction createBindingState( vao ) {\n\n\t\tconst newAttributes = [];\n\t\tconst enabledAttributes = [];\n\t\tconst attributeDivisors = [];\n\n\t\tfor ( let i = 0; i < maxVertexAttributes; i ++ ) {\n\n\t\t\tnewAttributes[ i ] = 0;\n\t\t\tenabledAttributes[ i ] = 0;\n\t\t\tattributeDivisors[ i ] = 0;\n\n\t\t}\n\n\t\treturn {\n\n\t\t\t// for backward compatibility on non-VAO support browser\n\t\t\tgeometry: null,\n\t\t\tprogram: null,\n\t\t\twireframe: false,\n\n\t\t\tnewAttributes: newAttributes,\n\t\t\tenabledAttributes: enabledAttributes,\n\t\t\tattributeDivisors: attributeDivisors,\n\t\t\tobject: vao,\n\t\t\tattributes: {},\n\t\t\tindex: null\n\n\t\t};\n\n\t}\n\n\tfunction needsUpdate( object, geometry, program, index ) {\n\n\t\tconst cachedAttributes = currentState.attributes;\n\t\tconst geometryAttributes = geometry.attributes;\n\n\t\tlet attributesNum = 0;\n\n\t\tconst programAttributes = program.getAttributes();\n\n\t\tfor ( const name in programAttributes ) {\n\n\t\t\tconst programAttribute = programAttributes[ name ];\n\n\t\t\tif ( programAttribute.location >= 0 ) {\n\n\t\t\t\tconst cachedAttribute = cachedAttributes[ name ];\n\t\t\t\tlet geometryAttribute = geometryAttributes[ name ];\n\n\t\t\t\tif ( geometryAttribute === undefined ) {\n\n\t\t\t\t\tif ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;\n\t\t\t\t\tif ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;\n\n\t\t\t\t}\n\n\t\t\t\tif ( cachedAttribute === undefined ) return true;\n\n\t\t\t\tif ( cachedAttribute.attribute !== geometryAttribute ) return true;\n\n\t\t\t\tif ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;\n\n\t\t\t\tattributesNum ++;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( currentState.attributesNum !== attributesNum ) return true;\n\n\t\tif ( currentState.index !== index ) return true;\n\n\t\treturn false;\n\n\t}\n\n\tfunction saveCache( object, geometry, program, index ) {\n\n\t\tconst cache = {};\n\t\tconst attributes = geometry.attributes;\n\t\tlet attributesNum = 0;\n\n\t\tconst programAttributes = program.getAttributes();\n\n\t\tfor ( const name in programAttributes ) {\n\n\t\t\tconst programAttribute = programAttributes[ name ];\n\n\t\t\tif ( programAttribute.location >= 0 ) {\n\n\t\t\t\tlet attribute = attributes[ name ];\n\n\t\t\t\tif ( attribute === undefined ) {\n\n\t\t\t\t\tif ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;\n\t\t\t\t\tif ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;\n\n\t\t\t\t}\n\n\t\t\t\tconst data = {};\n\t\t\t\tdata.attribute = attribute;\n\n\t\t\t\tif ( attribute && attribute.data ) {\n\n\t\t\t\t\tdata.data = attribute.data;\n\n\t\t\t\t}\n\n\t\t\t\tcache[ name ] = data;\n\n\t\t\t\tattributesNum ++;\n\n\t\t\t}\n\n\t\t}\n\n\t\tcurrentState.attributes = cache;\n\t\tcurrentState.attributesNum = attributesNum;\n\n\t\tcurrentState.index = index;\n\n\t}\n\n\tfunction initAttributes() {\n\n\t\tconst newAttributes = currentState.newAttributes;\n\n\t\tfor ( let i = 0, il = newAttributes.length; i < il; i ++ ) {\n\n\t\t\tnewAttributes[ i ] = 0;\n\n\t\t}\n\n\t}\n\n\tfunction enableAttribute( attribute ) {\n\n\t\tenableAttributeAndDivisor( attribute, 0 );\n\n\t}\n\n\tfunction enableAttributeAndDivisor( attribute, meshPerAttribute ) {\n\n\t\tconst newAttributes = currentState.newAttributes;\n\t\tconst enabledAttributes = currentState.enabledAttributes;\n\t\tconst attributeDivisors = currentState.attributeDivisors;\n\n\t\tnewAttributes[ attribute ] = 1;\n\n\t\tif ( enabledAttributes[ attribute ] === 0 ) {\n\n\t\t\tgl.enableVertexAttribArray( attribute );\n\t\t\tenabledAttributes[ attribute ] = 1;\n\n\t\t}\n\n\t\tif ( attributeDivisors[ attribute ] !== meshPerAttribute ) {\n\n\t\t\tconst extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );\n\n\t\t\textension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );\n\t\t\tattributeDivisors[ attribute ] = meshPerAttribute;\n\n\t\t}\n\n\t}\n\n\tfunction disableUnusedAttributes() {\n\n\t\tconst newAttributes = currentState.newAttributes;\n\t\tconst enabledAttributes = currentState.enabledAttributes;\n\n\t\tfor ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {\n\n\t\t\tif ( enabledAttributes[ i ] !== newAttributes[ i ] ) {\n\n\t\t\t\tgl.disableVertexAttribArray( i );\n\t\t\t\tenabledAttributes[ i ] = 0;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tfunction vertexAttribPointer( index, size, type, normalized, stride, offset ) {\n\n\t\tif ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT ) ) {\n\n\t\t\tgl.vertexAttribIPointer( index, size, type, stride, offset );\n\n\t\t} else {\n\n\t\t\tgl.vertexAttribPointer( index, size, type, normalized, stride, offset );\n\n\t\t}\n\n\t}\n\n\tfunction setupVertexAttributes( object, material, program, geometry ) {\n\n\t\tif ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {\n\n\t\t\tif ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;\n\n\t\t}\n\n\t\tinitAttributes();\n\n\t\tconst geometryAttributes = geometry.attributes;\n\n\t\tconst programAttributes = program.getAttributes();\n\n\t\tconst materialDefaultAttributeValues = material.defaultAttributeValues;\n\n\t\tfor ( const name in programAttributes ) {\n\n\t\t\tconst programAttribute = programAttributes[ name ];\n\n\t\t\tif ( programAttribute.location >= 0 ) {\n\n\t\t\t\tlet geometryAttribute = geometryAttributes[ name ];\n\n\t\t\t\tif ( geometryAttribute === undefined ) {\n\n\t\t\t\t\tif ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;\n\t\t\t\t\tif ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;\n\n\t\t\t\t}\n\n\t\t\t\tif ( geometryAttribute !== undefined ) {\n\n\t\t\t\t\tconst normalized = geometryAttribute.normalized;\n\t\t\t\t\tconst size = geometryAttribute.itemSize;\n\n\t\t\t\t\tconst attribute = attributes.get( geometryAttribute );\n\n\t\t\t\t\t// TODO Attribute may not be available on context restore\n\n\t\t\t\t\tif ( attribute === undefined ) continue;\n\n\t\t\t\t\tconst buffer = attribute.buffer;\n\t\t\t\t\tconst type = attribute.type;\n\t\t\t\t\tconst bytesPerElement = attribute.bytesPerElement;\n\n\t\t\t\t\tif ( geometryAttribute.isInterleavedBufferAttribute ) {\n\n\t\t\t\t\t\tconst data = geometryAttribute.data;\n\t\t\t\t\t\tconst stride = data.stride;\n\t\t\t\t\t\tconst offset = geometryAttribute.offset;\n\n\t\t\t\t\t\tif ( data.isInstancedInterleavedBuffer ) {\n\n\t\t\t\t\t\t\tfor ( let i = 0; i < programAttribute.locationSize; i ++ ) {\n\n\t\t\t\t\t\t\t\tenableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {\n\n\t\t\t\t\t\t\t\tgeometry._maxInstanceCount = data.meshPerAttribute * data.count;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tfor ( let i = 0; i < programAttribute.locationSize; i ++ ) {\n\n\t\t\t\t\t\t\t\tenableAttribute( programAttribute.location + i );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tgl.bindBuffer( gl.ARRAY_BUFFER, buffer );\n\n\t\t\t\t\t\tfor ( let i = 0; i < programAttribute.locationSize; i ++ ) {\n\n\t\t\t\t\t\t\tvertexAttribPointer(\n\t\t\t\t\t\t\t\tprogramAttribute.location + i,\n\t\t\t\t\t\t\t\tsize / programAttribute.locationSize,\n\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\tnormalized,\n\t\t\t\t\t\t\t\tstride * bytesPerElement,\n\t\t\t\t\t\t\t\t( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tif ( geometryAttribute.isInstancedBufferAttribute ) {\n\n\t\t\t\t\t\t\tfor ( let i = 0; i < programAttribute.locationSize; i ++ ) {\n\n\t\t\t\t\t\t\t\tenableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {\n\n\t\t\t\t\t\t\t\tgeometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tfor ( let i = 0; i < programAttribute.locationSize; i ++ ) {\n\n\t\t\t\t\t\t\t\tenableAttribute( programAttribute.location + i );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tgl.bindBuffer( gl.ARRAY_BUFFER, buffer );\n\n\t\t\t\t\t\tfor ( let i = 0; i < programAttribute.locationSize; i ++ ) {\n\n\t\t\t\t\t\t\tvertexAttribPointer(\n\t\t\t\t\t\t\t\tprogramAttribute.location + i,\n\t\t\t\t\t\t\t\tsize / programAttribute.locationSize,\n\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\tnormalized,\n\t\t\t\t\t\t\t\tsize * bytesPerElement,\n\t\t\t\t\t\t\t\t( size / programAttribute.locationSize ) * i * bytesPerElement\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if ( materialDefaultAttributeValues !== undefined ) {\n\n\t\t\t\t\tconst value = materialDefaultAttributeValues[ name ];\n\n\t\t\t\t\tif ( value !== undefined ) {\n\n\t\t\t\t\t\tswitch ( value.length ) {\n\n\t\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\t\tgl.vertexAttrib2fv( programAttribute.location, value );\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\t\tgl.vertexAttrib3fv( programAttribute.location, value );\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\t\tgl.vertexAttrib4fv( programAttribute.location, value );\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tgl.vertexAttrib1fv( programAttribute.location, value );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tdisableUnusedAttributes();\n\n\t}\n\n\tfunction dispose() {\n\n\t\treset();\n\n\t\tfor ( const geometryId in bindingStates ) {\n\n\t\t\tconst programMap = bindingStates[ geometryId ];\n\n\t\t\tfor ( const programId in programMap ) {\n\n\t\t\t\tconst stateMap = programMap[ programId ];\n\n\t\t\t\tfor ( const wireframe in stateMap ) {\n\n\t\t\t\t\tdeleteVertexArrayObject( stateMap[ wireframe ].object );\n\n\t\t\t\t\tdelete stateMap[ wireframe ];\n\n\t\t\t\t}\n\n\t\t\t\tdelete programMap[ programId ];\n\n\t\t\t}\n\n\t\t\tdelete bindingStates[ geometryId ];\n\n\t\t}\n\n\t}\n\n\tfunction releaseStatesOfGeometry( geometry ) {\n\n\t\tif ( bindingStates[ geometry.id ] === undefined ) return;\n\n\t\tconst programMap = bindingStates[ geometry.id ];\n\n\t\tfor ( const programId in programMap ) {\n\n\t\t\tconst stateMap = programMap[ programId ];\n\n\t\t\tfor ( const wireframe in stateMap ) {\n\n\t\t\t\tdeleteVertexArrayObject( stateMap[ wireframe ].object );\n\n\t\t\t\tdelete stateMap[ wireframe ];\n\n\t\t\t}\n\n\t\t\tdelete programMap[ programId ];\n\n\t\t}\n\n\t\tdelete bindingStates[ geometry.id ];\n\n\t}\n\n\tfunction releaseStatesOfProgram( program ) {\n\n\t\tfor ( const geometryId in bindingStates ) {\n\n\t\t\tconst programMap = bindingStates[ geometryId ];\n\n\t\t\tif ( programMap[ program.id ] === undefined ) continue;\n\n\t\t\tconst stateMap = programMap[ program.id ];\n\n\t\t\tfor ( const wireframe in stateMap ) {\n\n\t\t\t\tdeleteVertexArrayObject( stateMap[ wireframe ].object );\n\n\t\t\t\tdelete stateMap[ wireframe ];\n\n\t\t\t}\n\n\t\t\tdelete programMap[ program.id ];\n\n\t\t}\n\n\t}\n\n\tfunction reset() {\n\n\t\tresetDefaultState();\n\t\tforceUpdate = true;\n\n\t\tif ( currentState === defaultState ) return;\n\n\t\tcurrentState = defaultState;\n\t\tbindVertexArrayObject( currentState.object );\n\n\t}\n\n\t// for backward-compatibility\n\n\tfunction resetDefaultState() {\n\n\t\tdefaultState.geometry = null;\n\t\tdefaultState.program = null;\n\t\tdefaultState.wireframe = false;\n\n\t}\n\n\treturn {\n\n\t\tsetup: setup,\n\t\treset: reset,\n\t\tresetDefaultState: resetDefaultState,\n\t\tdispose: dispose,\n\t\treleaseStatesOfGeometry: releaseStatesOfGeometry,\n\t\treleaseStatesOfProgram: releaseStatesOfProgram,\n\n\t\tinitAttributes: initAttributes,\n\t\tenableAttribute: enableAttribute,\n\t\tdisableUnusedAttributes: disableUnusedAttributes\n\n\t};\n\n}\n\nfunction WebGLBufferRenderer( gl, extensions, info, capabilities ) {\n\n\tconst isWebGL2 = capabilities.isWebGL2;\n\n\tlet mode;\n\n\tfunction setMode( value ) {\n\n\t\tmode = value;\n\n\t}\n\n\tfunction render( start, count ) {\n\n\t\tgl.drawArrays( mode, start, count );\n\n\t\tinfo.update( count, mode, 1 );\n\n\t}\n\n\tfunction renderInstances( start, count, primcount ) {\n\n\t\tif ( primcount === 0 ) return;\n\n\t\tlet extension, methodName;\n\n\t\tif ( isWebGL2 ) {\n\n\t\t\textension = gl;\n\t\t\tmethodName = 'drawArraysInstanced';\n\n\t\t} else {\n\n\t\t\textension = extensions.get( 'ANGLE_instanced_arrays' );\n\t\t\tmethodName = 'drawArraysInstancedANGLE';\n\n\t\t\tif ( extension === null ) {\n\n\t\t\t\tconsole.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t}\n\n\t\textension[ methodName ]( mode, start, count, primcount );\n\n\t\tinfo.update( count, mode, primcount );\n\n\t}\n\n\t//\n\n\tthis.setMode = setMode;\n\tthis.render = render;\n\tthis.renderInstances = renderInstances;\n\n}\n\nfunction WebGLCapabilities( gl, extensions, parameters ) {\n\n\tlet maxAnisotropy;\n\n\tfunction getMaxAnisotropy() {\n\n\t\tif ( maxAnisotropy !== undefined ) return maxAnisotropy;\n\n\t\tif ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {\n\n\t\t\tconst extension = extensions.get( 'EXT_texture_filter_anisotropic' );\n\n\t\t\tmaxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );\n\n\t\t} else {\n\n\t\t\tmaxAnisotropy = 0;\n\n\t\t}\n\n\t\treturn maxAnisotropy;\n\n\t}\n\n\tfunction getMaxPrecision( precision ) {\n\n\t\tif ( precision === 'highp' ) {\n\n\t\t\tif ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&\n\t\t\t\tgl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {\n\n\t\t\t\treturn 'highp';\n\n\t\t\t}\n\n\t\t\tprecision = 'mediump';\n\n\t\t}\n\n\t\tif ( precision === 'mediump' ) {\n\n\t\t\tif ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&\n\t\t\t\tgl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {\n\n\t\t\t\treturn 'mediump';\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn 'lowp';\n\n\t}\n\n\tconst isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext';\n\n\tlet precision = parameters.precision !== undefined ? parameters.precision : 'highp';\n\tconst maxPrecision = getMaxPrecision( precision );\n\n\tif ( maxPrecision !== precision ) {\n\n\t\tconsole.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );\n\t\tprecision = maxPrecision;\n\n\t}\n\n\tconst drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );\n\n\tconst logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;\n\n\tconst maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );\n\tconst maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );\n\tconst maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );\n\tconst maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );\n\n\tconst maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );\n\tconst maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );\n\tconst maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );\n\tconst maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );\n\n\tconst vertexTextures = maxVertexTextures > 0;\n\tconst floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );\n\tconst floatVertexTextures = vertexTextures && floatFragmentTextures;\n\n\tconst maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;\n\n\treturn {\n\n\t\tisWebGL2: isWebGL2,\n\n\t\tdrawBuffers: drawBuffers,\n\n\t\tgetMaxAnisotropy: getMaxAnisotropy,\n\t\tgetMaxPrecision: getMaxPrecision,\n\n\t\tprecision: precision,\n\t\tlogarithmicDepthBuffer: logarithmicDepthBuffer,\n\n\t\tmaxTextures: maxTextures,\n\t\tmaxVertexTextures: maxVertexTextures,\n\t\tmaxTextureSize: maxTextureSize,\n\t\tmaxCubemapSize: maxCubemapSize,\n\n\t\tmaxAttributes: maxAttributes,\n\t\tmaxVertexUniforms: maxVertexUniforms,\n\t\tmaxVaryings: maxVaryings,\n\t\tmaxFragmentUniforms: maxFragmentUniforms,\n\n\t\tvertexTextures: vertexTextures,\n\t\tfloatFragmentTextures: floatFragmentTextures,\n\t\tfloatVertexTextures: floatVertexTextures,\n\n\t\tmaxSamples: maxSamples\n\n\t};\n\n}\n\nfunction WebGLClipping( properties ) {\n\n\tconst scope = this;\n\n\tlet globalState = null,\n\t\tnumGlobalPlanes = 0,\n\t\tlocalClippingEnabled = false,\n\t\trenderingShadows = false;\n\n\tconst plane = new Plane(),\n\t\tviewNormalMatrix = new Matrix3(),\n\n\t\tuniform = { value: null, needsUpdate: false };\n\n\tthis.uniform = uniform;\n\tthis.numPlanes = 0;\n\tthis.numIntersection = 0;\n\n\tthis.init = function ( planes, enableLocalClipping ) {\n\n\t\tconst enabled =\n\t\t\tplanes.length !== 0 ||\n\t\t\tenableLocalClipping ||\n\t\t\t// enable state of previous frame - the clipping code has to\n\t\t\t// run another frame in order to reset the state:\n\t\t\tnumGlobalPlanes !== 0 ||\n\t\t\tlocalClippingEnabled;\n\n\t\tlocalClippingEnabled = enableLocalClipping;\n\n\t\tnumGlobalPlanes = planes.length;\n\n\t\treturn enabled;\n\n\t};\n\n\tthis.beginShadows = function () {\n\n\t\trenderingShadows = true;\n\t\tprojectPlanes( null );\n\n\t};\n\n\tthis.endShadows = function () {\n\n\t\trenderingShadows = false;\n\n\t};\n\n\tthis.setGlobalState = function ( planes, camera ) {\n\n\t\tglobalState = projectPlanes( planes, camera, 0 );\n\n\t};\n\n\tthis.setState = function ( material, camera, useCache ) {\n\n\t\tconst planes = material.clippingPlanes,\n\t\t\tclipIntersection = material.clipIntersection,\n\t\t\tclipShadows = material.clipShadows;\n\n\t\tconst materialProperties = properties.get( material );\n\n\t\tif ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {\n\n\t\t\t// there's no local clipping\n\n\t\t\tif ( renderingShadows ) {\n\n\t\t\t\t// there's no global clipping\n\n\t\t\t\tprojectPlanes( null );\n\n\t\t\t} else {\n\n\t\t\t\tresetGlobalState();\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tconst nGlobal = renderingShadows ? 0 : numGlobalPlanes,\n\t\t\t\tlGlobal = nGlobal * 4;\n\n\t\t\tlet dstArray = materialProperties.clippingState || null;\n\n\t\t\tuniform.value = dstArray; // ensure unique state\n\n\t\t\tdstArray = projectPlanes( planes, camera, lGlobal, useCache );\n\n\t\t\tfor ( let i = 0; i !== lGlobal; ++ i ) {\n\n\t\t\t\tdstArray[ i ] = globalState[ i ];\n\n\t\t\t}\n\n\t\t\tmaterialProperties.clippingState = dstArray;\n\t\t\tthis.numIntersection = clipIntersection ? this.numPlanes : 0;\n\t\t\tthis.numPlanes += nGlobal;\n\n\t\t}\n\n\n\t};\n\n\tfunction resetGlobalState() {\n\n\t\tif ( uniform.value !== globalState ) {\n\n\t\t\tuniform.value = globalState;\n\t\t\tuniform.needsUpdate = numGlobalPlanes > 0;\n\n\t\t}\n\n\t\tscope.numPlanes = numGlobalPlanes;\n\t\tscope.numIntersection = 0;\n\n\t}\n\n\tfunction projectPlanes( planes, camera, dstOffset, skipTransform ) {\n\n\t\tconst nPlanes = planes !== null ? planes.length : 0;\n\t\tlet dstArray = null;\n\n\t\tif ( nPlanes !== 0 ) {\n\n\t\t\tdstArray = uniform.value;\n\n\t\t\tif ( skipTransform !== true || dstArray === null ) {\n\n\t\t\t\tconst flatSize = dstOffset + nPlanes * 4,\n\t\t\t\t\tviewMatrix = camera.matrixWorldInverse;\n\n\t\t\t\tviewNormalMatrix.getNormalMatrix( viewMatrix );\n\n\t\t\t\tif ( dstArray === null || dstArray.length < flatSize ) {\n\n\t\t\t\t\tdstArray = new Float32Array( flatSize );\n\n\t\t\t\t}\n\n\t\t\t\tfor ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {\n\n\t\t\t\t\tplane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );\n\n\t\t\t\t\tplane.normal.toArray( dstArray, i4 );\n\t\t\t\t\tdstArray[ i4 + 3 ] = plane.constant;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tuniform.value = dstArray;\n\t\t\tuniform.needsUpdate = true;\n\n\t\t}\n\n\t\tscope.numPlanes = nPlanes;\n\t\tscope.numIntersection = 0;\n\n\t\treturn dstArray;\n\n\t}\n\n}\n\nfunction WebGLCubeMaps( renderer ) {\n\n\tlet cubemaps = new WeakMap();\n\n\tfunction mapTextureMapping( texture, mapping ) {\n\n\t\tif ( mapping === EquirectangularReflectionMapping ) {\n\n\t\t\ttexture.mapping = CubeReflectionMapping;\n\n\t\t} else if ( mapping === EquirectangularRefractionMapping ) {\n\n\t\t\ttexture.mapping = CubeRefractionMapping;\n\n\t\t}\n\n\t\treturn texture;\n\n\t}\n\n\tfunction get( texture ) {\n\n\t\tif ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {\n\n\t\t\tconst mapping = texture.mapping;\n\n\t\t\tif ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {\n\n\t\t\t\tif ( cubemaps.has( texture ) ) {\n\n\t\t\t\t\tconst cubemap = cubemaps.get( texture ).texture;\n\t\t\t\t\treturn mapTextureMapping( cubemap, texture.mapping );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tconst image = texture.image;\n\n\t\t\t\t\tif ( image && image.height > 0 ) {\n\n\t\t\t\t\t\tconst renderTarget = new WebGLCubeRenderTarget( image.height / 2 );\n\t\t\t\t\t\trenderTarget.fromEquirectangularTexture( renderer, texture );\n\t\t\t\t\t\tcubemaps.set( texture, renderTarget );\n\n\t\t\t\t\t\ttexture.addEventListener( 'dispose', onTextureDispose );\n\n\t\t\t\t\t\treturn mapTextureMapping( renderTarget.texture, texture.mapping );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t// image not yet ready. try the conversion next frame\n\n\t\t\t\t\t\treturn null;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn texture;\n\n\t}\n\n\tfunction onTextureDispose( event ) {\n\n\t\tconst texture = event.target;\n\n\t\ttexture.removeEventListener( 'dispose', onTextureDispose );\n\n\t\tconst cubemap = cubemaps.get( texture );\n\n\t\tif ( cubemap !== undefined ) {\n\n\t\t\tcubemaps.delete( texture );\n\t\t\tcubemap.dispose();\n\n\t\t}\n\n\t}\n\n\tfunction dispose() {\n\n\t\tcubemaps = new WeakMap();\n\n\t}\n\n\treturn {\n\t\tget: get,\n\t\tdispose: dispose\n\t};\n\n}\n\nclass OrthographicCamera extends Camera {\n\n\tconstructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {\n\n\t\tsuper();\n\n\t\tthis.isOrthographicCamera = true;\n\n\t\tthis.type = 'OrthographicCamera';\n\n\t\tthis.zoom = 1;\n\t\tthis.view = null;\n\n\t\tthis.left = left;\n\t\tthis.right = right;\n\t\tthis.top = top;\n\t\tthis.bottom = bottom;\n\n\t\tthis.near = near;\n\t\tthis.far = far;\n\n\t\tthis.updateProjectionMatrix();\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tthis.left = source.left;\n\t\tthis.right = source.right;\n\t\tthis.top = source.top;\n\t\tthis.bottom = source.bottom;\n\t\tthis.near = source.near;\n\t\tthis.far = source.far;\n\n\t\tthis.zoom = source.zoom;\n\t\tthis.view = source.view === null ? null : Object.assign( {}, source.view );\n\n\t\treturn this;\n\n\t}\n\n\tsetViewOffset( fullWidth, fullHeight, x, y, width, height ) {\n\n\t\tif ( this.view === null ) {\n\n\t\t\tthis.view = {\n\t\t\t\tenabled: true,\n\t\t\t\tfullWidth: 1,\n\t\t\t\tfullHeight: 1,\n\t\t\t\toffsetX: 0,\n\t\t\t\toffsetY: 0,\n\t\t\t\twidth: 1,\n\t\t\t\theight: 1\n\t\t\t};\n\n\t\t}\n\n\t\tthis.view.enabled = true;\n\t\tthis.view.fullWidth = fullWidth;\n\t\tthis.view.fullHeight = fullHeight;\n\t\tthis.view.offsetX = x;\n\t\tthis.view.offsetY = y;\n\t\tthis.view.width = width;\n\t\tthis.view.height = height;\n\n\t\tthis.updateProjectionMatrix();\n\n\t}\n\n\tclearViewOffset() {\n\n\t\tif ( this.view !== null ) {\n\n\t\t\tthis.view.enabled = false;\n\n\t\t}\n\n\t\tthis.updateProjectionMatrix();\n\n\t}\n\n\tupdateProjectionMatrix() {\n\n\t\tconst dx = ( this.right - this.left ) / ( 2 * this.zoom );\n\t\tconst dy = ( this.top - this.bottom ) / ( 2 * this.zoom );\n\t\tconst cx = ( this.right + this.left ) / 2;\n\t\tconst cy = ( this.top + this.bottom ) / 2;\n\n\t\tlet left = cx - dx;\n\t\tlet right = cx + dx;\n\t\tlet top = cy + dy;\n\t\tlet bottom = cy - dy;\n\n\t\tif ( this.view !== null && this.view.enabled ) {\n\n\t\t\tconst scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;\n\t\t\tconst scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;\n\n\t\t\tleft += scaleW * this.view.offsetX;\n\t\t\tright = left + scaleW * this.view.width;\n\t\t\ttop -= scaleH * this.view.offsetY;\n\t\t\tbottom = top - scaleH * this.view.height;\n\n\t\t}\n\n\t\tthis.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );\n\n\t\tthis.projectionMatrixInverse.copy( this.projectionMatrix ).invert();\n\n\t}\n\n\ttoJSON( meta ) {\n\n\t\tconst data = super.toJSON( meta );\n\n\t\tdata.object.zoom = this.zoom;\n\t\tdata.object.left = this.left;\n\t\tdata.object.right = this.right;\n\t\tdata.object.top = this.top;\n\t\tdata.object.bottom = this.bottom;\n\t\tdata.object.near = this.near;\n\t\tdata.object.far = this.far;\n\n\t\tif ( this.view !== null ) data.object.view = Object.assign( {}, this.view );\n\n\t\treturn data;\n\n\t}\n\n}\n\nconst LOD_MIN = 4;\n\n// The standard deviations (radians) associated with the extra mips. These are\n// chosen to approximate a Trowbridge-Reitz distribution function times the\n// geometric shadowing function. These sigma values squared must match the\n// variance #defines in cube_uv_reflection_fragment.glsl.js.\nconst EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];\n\n// The maximum length of the blur for loop. Smaller sigmas will use fewer\n// samples and exit early, but not recompile the shader.\nconst MAX_SAMPLES = 20;\n\nconst _flatCamera = /*@__PURE__*/ new OrthographicCamera();\nconst _clearColor = /*@__PURE__*/ new Color();\nlet _oldTarget = null;\n\n// Golden Ratio\nconst PHI = ( 1 + Math.sqrt( 5 ) ) / 2;\nconst INV_PHI = 1 / PHI;\n\n// Vertices of a dodecahedron (except the opposites, which represent the\n// same axis), used as axis directions evenly spread on a sphere.\nconst _axisDirections = [\n\t/*@__PURE__*/ new Vector3( 1, 1, 1 ),\n\t/*@__PURE__*/ new Vector3( - 1, 1, 1 ),\n\t/*@__PURE__*/ new Vector3( 1, 1, - 1 ),\n\t/*@__PURE__*/ new Vector3( - 1, 1, - 1 ),\n\t/*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),\n\t/*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),\n\t/*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),\n\t/*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),\n\t/*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),\n\t/*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];\n\n/**\n * This class generates a Prefiltered, Mipmapped Radiance Environment Map\n * (PMREM) from a cubeMap environment texture. This allows different levels of\n * blur to be quickly accessed based on material roughness. It is packed into a\n * special CubeUV format that allows us to perform custom interpolation so that\n * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap\n * chain, it only goes down to the LOD_MIN level (above), and then creates extra\n * even more filtered 'mips' at the same LOD_MIN resolution, associated with\n * higher roughness levels. In this way we maintain resolution to smoothly\n * interpolate diffuse lighting while limiting sampling computation.\n *\n * Paper: Fast, Accurate Image-Based Lighting\n * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view\n*/\n\nclass PMREMGenerator {\n\n\tconstructor( renderer ) {\n\n\t\tthis._renderer = renderer;\n\t\tthis._pingPongRenderTarget = null;\n\n\t\tthis._lodMax = 0;\n\t\tthis._cubeSize = 0;\n\t\tthis._lodPlanes = [];\n\t\tthis._sizeLods = [];\n\t\tthis._sigmas = [];\n\n\t\tthis._blurMaterial = null;\n\t\tthis._cubemapMaterial = null;\n\t\tthis._equirectMaterial = null;\n\n\t\tthis._compileMaterial( this._blurMaterial );\n\n\t}\n\n\t/**\n\t * Generates a PMREM from a supplied Scene, which can be faster than using an\n\t * image if networking bandwidth is low. Optional sigma specifies a blur radius\n\t * in radians to be applied to the scene before PMREM generation. Optional near\n\t * and far planes ensure the scene is rendered in its entirety (the cubeCamera\n\t * is placed at the origin).\n\t */\n\tfromScene( scene, sigma = 0, near = 0.1, far = 100 ) {\n\n\t\t_oldTarget = this._renderer.getRenderTarget();\n\n\t\tthis._setSize( 256 );\n\n\t\tconst cubeUVRenderTarget = this._allocateTargets();\n\t\tcubeUVRenderTarget.depthBuffer = true;\n\n\t\tthis._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );\n\n\t\tif ( sigma > 0 ) {\n\n\t\t\tthis._blur( cubeUVRenderTarget, 0, 0, sigma );\n\n\t\t}\n\n\t\tthis._applyPMREM( cubeUVRenderTarget );\n\t\tthis._cleanup( cubeUVRenderTarget );\n\n\t\treturn cubeUVRenderTarget;\n\n\t}\n\n\t/**\n\t * Generates a PMREM from an equirectangular texture, which can be either LDR\n\t * or HDR. The ideal input image size is 1k (1024 x 512),\n\t * as this matches best with the 256 x 256 cubemap output.\n\t */\n\tfromEquirectangular( equirectangular, renderTarget = null ) {\n\n\t\treturn this._fromTexture( equirectangular, renderTarget );\n\n\t}\n\n\t/**\n\t * Generates a PMREM from an cubemap texture, which can be either LDR\n\t * or HDR. The ideal input cube size is 256 x 256,\n\t * as this matches best with the 256 x 256 cubemap output.\n\t */\n\tfromCubemap( cubemap, renderTarget = null ) {\n\n\t\treturn this._fromTexture( cubemap, renderTarget );\n\n\t}\n\n\t/**\n\t * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during\n\t * your texture's network fetch for increased concurrency.\n\t */\n\tcompileCubemapShader() {\n\n\t\tif ( this._cubemapMaterial === null ) {\n\n\t\t\tthis._cubemapMaterial = _getCubemapMaterial();\n\t\t\tthis._compileMaterial( this._cubemapMaterial );\n\n\t\t}\n\n\t}\n\n\t/**\n\t * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during\n\t * your texture's network fetch for increased concurrency.\n\t */\n\tcompileEquirectangularShader() {\n\n\t\tif ( this._equirectMaterial === null ) {\n\n\t\t\tthis._equirectMaterial = _getEquirectMaterial();\n\t\t\tthis._compileMaterial( this._equirectMaterial );\n\n\t\t}\n\n\t}\n\n\t/**\n\t * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,\n\t * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on\n\t * one of them will cause any others to also become unusable.\n\t */\n\tdispose() {\n\n\t\tthis._dispose();\n\n\t\tif ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();\n\t\tif ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();\n\n\t}\n\n\t// private interface\n\n\t_setSize( cubeSize ) {\n\n\t\tthis._lodMax = Math.floor( Math.log2( cubeSize ) );\n\t\tthis._cubeSize = Math.pow( 2, this._lodMax );\n\n\t}\n\n\t_dispose() {\n\n\t\tif ( this._blurMaterial !== null ) this._blurMaterial.dispose();\n\n\t\tif ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();\n\n\t\tfor ( let i = 0; i < this._lodPlanes.length; i ++ ) {\n\n\t\t\tthis._lodPlanes[ i ].dispose();\n\n\t\t}\n\n\t}\n\n\t_cleanup( outputTarget ) {\n\n\t\tthis._renderer.setRenderTarget( _oldTarget );\n\t\toutputTarget.scissorTest = false;\n\t\t_setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );\n\n\t}\n\n\t_fromTexture( texture, renderTarget ) {\n\n\t\tif ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {\n\n\t\t\tthis._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );\n\n\t\t} else { // Equirectangular\n\n\t\t\tthis._setSize( texture.image.width / 4 );\n\n\t\t}\n\n\t\t_oldTarget = this._renderer.getRenderTarget();\n\n\t\tconst cubeUVRenderTarget = renderTarget || this._allocateTargets();\n\t\tthis._textureToCubeUV( texture, cubeUVRenderTarget );\n\t\tthis._applyPMREM( cubeUVRenderTarget );\n\t\tthis._cleanup( cubeUVRenderTarget );\n\n\t\treturn cubeUVRenderTarget;\n\n\t}\n\n\t_allocateTargets() {\n\n\t\tconst width = 3 * Math.max( this._cubeSize, 16 * 7 );\n\t\tconst height = 4 * this._cubeSize;\n\n\t\tconst params = {\n\t\t\tmagFilter: LinearFilter,\n\t\t\tminFilter: LinearFilter,\n\t\t\tgenerateMipmaps: false,\n\t\t\ttype: HalfFloatType,\n\t\t\tformat: RGBAFormat,\n\t\t\tcolorSpace: LinearSRGBColorSpace,\n\t\t\tdepthBuffer: false\n\t\t};\n\n\t\tconst cubeUVRenderTarget = _createRenderTarget( width, height, params );\n\n\t\tif ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {\n\n\t\t\tif ( this._pingPongRenderTarget !== null ) {\n\n\t\t\t\tthis._dispose();\n\n\t\t\t}\n\n\t\t\tthis._pingPongRenderTarget = _createRenderTarget( width, height, params );\n\n\t\t\tconst { _lodMax } = this;\n\t\t\t( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );\n\n\t\t\tthis._blurMaterial = _getBlurShader( _lodMax, width, height );\n\n\t\t}\n\n\t\treturn cubeUVRenderTarget;\n\n\t}\n\n\t_compileMaterial( material ) {\n\n\t\tconst tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );\n\t\tthis._renderer.compile( tmpMesh, _flatCamera );\n\n\t}\n\n\t_sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {\n\n\t\tconst fov = 90;\n\t\tconst aspect = 1;\n\t\tconst cubeCamera = new PerspectiveCamera( fov, aspect, near, far );\n\t\tconst upSign = [ 1, - 1, 1, 1, 1, 1 ];\n\t\tconst forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];\n\t\tconst renderer = this._renderer;\n\n\t\tconst originalAutoClear = renderer.autoClear;\n\t\tconst toneMapping = renderer.toneMapping;\n\t\trenderer.getClearColor( _clearColor );\n\n\t\trenderer.toneMapping = NoToneMapping;\n\t\trenderer.autoClear = false;\n\n\t\tconst backgroundMaterial = new MeshBasicMaterial( {\n\t\t\tname: 'PMREM.Background',\n\t\t\tside: BackSide,\n\t\t\tdepthWrite: false,\n\t\t\tdepthTest: false,\n\t\t} );\n\n\t\tconst backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );\n\n\t\tlet useSolidColor = false;\n\t\tconst background = scene.background;\n\n\t\tif ( background ) {\n\n\t\t\tif ( background.isColor ) {\n\n\t\t\t\tbackgroundMaterial.color.copy( background );\n\t\t\t\tscene.background = null;\n\t\t\t\tuseSolidColor = true;\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tbackgroundMaterial.color.copy( _clearColor );\n\t\t\tuseSolidColor = true;\n\n\t\t}\n\n\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\tconst col = i % 3;\n\n\t\t\tif ( col === 0 ) {\n\n\t\t\t\tcubeCamera.up.set( 0, upSign[ i ], 0 );\n\t\t\t\tcubeCamera.lookAt( forwardSign[ i ], 0, 0 );\n\n\t\t\t} else if ( col === 1 ) {\n\n\t\t\t\tcubeCamera.up.set( 0, 0, upSign[ i ] );\n\t\t\t\tcubeCamera.lookAt( 0, forwardSign[ i ], 0 );\n\n\t\t\t} else {\n\n\t\t\t\tcubeCamera.up.set( 0, upSign[ i ], 0 );\n\t\t\t\tcubeCamera.lookAt( 0, 0, forwardSign[ i ] );\n\n\t\t\t}\n\n\t\t\tconst size = this._cubeSize;\n\n\t\t\t_setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );\n\n\t\t\trenderer.setRenderTarget( cubeUVRenderTarget );\n\n\t\t\tif ( useSolidColor ) {\n\n\t\t\t\trenderer.render( backgroundBox, cubeCamera );\n\n\t\t\t}\n\n\t\t\trenderer.render( scene, cubeCamera );\n\n\t\t}\n\n\t\tbackgroundBox.geometry.dispose();\n\t\tbackgroundBox.material.dispose();\n\n\t\trenderer.toneMapping = toneMapping;\n\t\trenderer.autoClear = originalAutoClear;\n\t\tscene.background = background;\n\n\t}\n\n\t_textureToCubeUV( texture, cubeUVRenderTarget ) {\n\n\t\tconst renderer = this._renderer;\n\n\t\tconst isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );\n\n\t\tif ( isCubeTexture ) {\n\n\t\t\tif ( this._cubemapMaterial === null ) {\n\n\t\t\t\tthis._cubemapMaterial = _getCubemapMaterial();\n\n\t\t\t}\n\n\t\t\tthis._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;\n\n\t\t} else {\n\n\t\t\tif ( this._equirectMaterial === null ) {\n\n\t\t\t\tthis._equirectMaterial = _getEquirectMaterial();\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;\n\t\tconst mesh = new Mesh( this._lodPlanes[ 0 ], material );\n\n\t\tconst uniforms = material.uniforms;\n\n\t\tuniforms[ 'envMap' ].value = texture;\n\n\t\tconst size = this._cubeSize;\n\n\t\t_setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );\n\n\t\trenderer.setRenderTarget( cubeUVRenderTarget );\n\t\trenderer.render( mesh, _flatCamera );\n\n\t}\n\n\t_applyPMREM( cubeUVRenderTarget ) {\n\n\t\tconst renderer = this._renderer;\n\t\tconst autoClear = renderer.autoClear;\n\t\trenderer.autoClear = false;\n\n\t\tfor ( let i = 1; i < this._lodPlanes.length; i ++ ) {\n\n\t\t\tconst sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );\n\n\t\t\tconst poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];\n\n\t\t\tthis._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );\n\n\t\t}\n\n\t\trenderer.autoClear = autoClear;\n\n\t}\n\n\t/**\n\t * This is a two-pass Gaussian blur for a cubemap. Normally this is done\n\t * vertically and horizontally, but this breaks down on a cube. Here we apply\n\t * the blur latitudinally (around the poles), and then longitudinally (towards\n\t * the poles) to approximate the orthogonally-separable blur. It is least\n\t * accurate at the poles, but still does a decent job.\n\t */\n\t_blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {\n\n\t\tconst pingPongRenderTarget = this._pingPongRenderTarget;\n\n\t\tthis._halfBlur(\n\t\t\tcubeUVRenderTarget,\n\t\t\tpingPongRenderTarget,\n\t\t\tlodIn,\n\t\t\tlodOut,\n\t\t\tsigma,\n\t\t\t'latitudinal',\n\t\t\tpoleAxis );\n\n\t\tthis._halfBlur(\n\t\t\tpingPongRenderTarget,\n\t\t\tcubeUVRenderTarget,\n\t\t\tlodOut,\n\t\t\tlodOut,\n\t\t\tsigma,\n\t\t\t'longitudinal',\n\t\t\tpoleAxis );\n\n\t}\n\n\t_halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {\n\n\t\tconst renderer = this._renderer;\n\t\tconst blurMaterial = this._blurMaterial;\n\n\t\tif ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {\n\n\t\t\tconsole.error(\n\t\t\t\t'blur direction must be either latitudinal or longitudinal!' );\n\n\t\t}\n\n\t\t// Number of standard deviations at which to cut off the discrete approximation.\n\t\tconst STANDARD_DEVIATIONS = 3;\n\n\t\tconst blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );\n\t\tconst blurUniforms = blurMaterial.uniforms;\n\n\t\tconst pixels = this._sizeLods[ lodIn ] - 1;\n\t\tconst radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );\n\t\tconst sigmaPixels = sigmaRadians / radiansPerPixel;\n\t\tconst samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;\n\n\t\tif ( samples > MAX_SAMPLES ) {\n\n\t\t\tconsole.warn( `sigmaRadians, ${\n\t\t\t\tsigmaRadians}, is too large and will clip, as it requested ${\n\t\t\t\tsamples} samples when the maximum is set to ${MAX_SAMPLES}` );\n\n\t\t}\n\n\t\tconst weights = [];\n\t\tlet sum = 0;\n\n\t\tfor ( let i = 0; i < MAX_SAMPLES; ++ i ) {\n\n\t\t\tconst x = i / sigmaPixels;\n\t\t\tconst weight = Math.exp( - x * x / 2 );\n\t\t\tweights.push( weight );\n\n\t\t\tif ( i === 0 ) {\n\n\t\t\t\tsum += weight;\n\n\t\t\t} else if ( i < samples ) {\n\n\t\t\t\tsum += 2 * weight;\n\n\t\t\t}\n\n\t\t}\n\n\t\tfor ( let i = 0; i < weights.length; i ++ ) {\n\n\t\t\tweights[ i ] = weights[ i ] / sum;\n\n\t\t}\n\n\t\tblurUniforms[ 'envMap' ].value = targetIn.texture;\n\t\tblurUniforms[ 'samples' ].value = samples;\n\t\tblurUniforms[ 'weights' ].value = weights;\n\t\tblurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';\n\n\t\tif ( poleAxis ) {\n\n\t\t\tblurUniforms[ 'poleAxis' ].value = poleAxis;\n\n\t\t}\n\n\t\tconst { _lodMax } = this;\n\t\tblurUniforms[ 'dTheta' ].value = radiansPerPixel;\n\t\tblurUniforms[ 'mipInt' ].value = _lodMax - lodIn;\n\n\t\tconst outputSize = this._sizeLods[ lodOut ];\n\t\tconst x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );\n\t\tconst y = 4 * ( this._cubeSize - outputSize );\n\n\t\t_setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );\n\t\trenderer.setRenderTarget( targetOut );\n\t\trenderer.render( blurMesh, _flatCamera );\n\n\t}\n\n}\n\n\n\nfunction _createPlanes( lodMax ) {\n\n\tconst lodPlanes = [];\n\tconst sizeLods = [];\n\tconst sigmas = [];\n\n\tlet lod = lodMax;\n\n\tconst totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;\n\n\tfor ( let i = 0; i < totalLods; i ++ ) {\n\n\t\tconst sizeLod = Math.pow( 2, lod );\n\t\tsizeLods.push( sizeLod );\n\t\tlet sigma = 1.0 / sizeLod;\n\n\t\tif ( i > lodMax - LOD_MIN ) {\n\n\t\t\tsigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];\n\n\t\t} else if ( i === 0 ) {\n\n\t\t\tsigma = 0;\n\n\t\t}\n\n\t\tsigmas.push( sigma );\n\n\t\tconst texelSize = 1.0 / ( sizeLod - 2 );\n\t\tconst min = - texelSize;\n\t\tconst max = 1 + texelSize;\n\t\tconst uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];\n\n\t\tconst cubeFaces = 6;\n\t\tconst vertices = 6;\n\t\tconst positionSize = 3;\n\t\tconst uvSize = 2;\n\t\tconst faceIndexSize = 1;\n\n\t\tconst position = new Float32Array( positionSize * vertices * cubeFaces );\n\t\tconst uv = new Float32Array( uvSize * vertices * cubeFaces );\n\t\tconst faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );\n\n\t\tfor ( let face = 0; face < cubeFaces; face ++ ) {\n\n\t\t\tconst x = ( face % 3 ) * 2 / 3 - 1;\n\t\t\tconst y = face > 2 ? 0 : - 1;\n\t\t\tconst coordinates = [\n\t\t\t\tx, y, 0,\n\t\t\t\tx + 2 / 3, y, 0,\n\t\t\t\tx + 2 / 3, y + 1, 0,\n\t\t\t\tx, y, 0,\n\t\t\t\tx + 2 / 3, y + 1, 0,\n\t\t\t\tx, y + 1, 0\n\t\t\t];\n\t\t\tposition.set( coordinates, positionSize * vertices * face );\n\t\t\tuv.set( uv1, uvSize * vertices * face );\n\t\t\tconst fill = [ face, face, face, face, face, face ];\n\t\t\tfaceIndex.set( fill, faceIndexSize * vertices * face );\n\n\t\t}\n\n\t\tconst planes = new BufferGeometry();\n\t\tplanes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );\n\t\tplanes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );\n\t\tplanes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );\n\t\tlodPlanes.push( planes );\n\n\t\tif ( lod > LOD_MIN ) {\n\n\t\t\tlod --;\n\n\t\t}\n\n\t}\n\n\treturn { lodPlanes, sizeLods, sigmas };\n\n}\n\nfunction _createRenderTarget( width, height, params ) {\n\n\tconst cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );\n\tcubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;\n\tcubeUVRenderTarget.texture.name = 'PMREM.cubeUv';\n\tcubeUVRenderTarget.scissorTest = true;\n\treturn cubeUVRenderTarget;\n\n}\n\nfunction _setViewport( target, x, y, width, height ) {\n\n\ttarget.viewport.set( x, y, width, height );\n\ttarget.scissor.set( x, y, width, height );\n\n}\n\nfunction _getBlurShader( lodMax, width, height ) {\n\n\tconst weights = new Float32Array( MAX_SAMPLES );\n\tconst poleAxis = new Vector3( 0, 1, 0 );\n\tconst shaderMaterial = new ShaderMaterial( {\n\n\t\tname: 'SphericalGaussianBlur',\n\n\t\tdefines: {\n\t\t\t'n': MAX_SAMPLES,\n\t\t\t'CUBEUV_TEXEL_WIDTH': 1.0 / width,\n\t\t\t'CUBEUV_TEXEL_HEIGHT': 1.0 / height,\n\t\t\t'CUBEUV_MAX_MIP': `${lodMax}.0`,\n\t\t},\n\n\t\tuniforms: {\n\t\t\t'envMap': { value: null },\n\t\t\t'samples': { value: 1 },\n\t\t\t'weights': { value: weights },\n\t\t\t'latitudinal': { value: false },\n\t\t\t'dTheta': { value: 0 },\n\t\t\t'mipInt': { value: 0 },\n\t\t\t'poleAxis': { value: poleAxis }\n\t\t},\n\n\t\tvertexShader: _getCommonVertexShader(),\n\n\t\tfragmentShader: /* glsl */`\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t`,\n\n\t\tblending: NoBlending,\n\t\tdepthTest: false,\n\t\tdepthWrite: false\n\n\t} );\n\n\treturn shaderMaterial;\n\n}\n\nfunction _getEquirectMaterial() {\n\n\treturn new ShaderMaterial( {\n\n\t\tname: 'EquirectangularToCubeUV',\n\n\t\tuniforms: {\n\t\t\t'envMap': { value: null }\n\t\t},\n\n\t\tvertexShader: _getCommonVertexShader(),\n\n\t\tfragmentShader: /* glsl */`\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t`,\n\n\t\tblending: NoBlending,\n\t\tdepthTest: false,\n\t\tdepthWrite: false\n\n\t} );\n\n}\n\nfunction _getCubemapMaterial() {\n\n\treturn new ShaderMaterial( {\n\n\t\tname: 'CubemapToCubeUV',\n\n\t\tuniforms: {\n\t\t\t'envMap': { value: null },\n\t\t\t'flipEnvMap': { value: - 1 }\n\t\t},\n\n\t\tvertexShader: _getCommonVertexShader(),\n\n\t\tfragmentShader: /* glsl */`\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t`,\n\n\t\tblending: NoBlending,\n\t\tdepthTest: false,\n\t\tdepthWrite: false\n\n\t} );\n\n}\n\nfunction _getCommonVertexShader() {\n\n\treturn /* glsl */`\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t`;\n\n}\n\nfunction WebGLCubeUVMaps( renderer ) {\n\n\tlet cubeUVmaps = new WeakMap();\n\n\tlet pmremGenerator = null;\n\n\tfunction get( texture ) {\n\n\t\tif ( texture && texture.isTexture ) {\n\n\t\t\tconst mapping = texture.mapping;\n\n\t\t\tconst isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );\n\t\t\tconst isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );\n\n\t\t\t// equirect/cube map to cubeUV conversion\n\n\t\t\tif ( isEquirectMap || isCubeMap ) {\n\n\t\t\t\tif ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {\n\n\t\t\t\t\ttexture.needsPMREMUpdate = false;\n\n\t\t\t\t\tlet renderTarget = cubeUVmaps.get( texture );\n\n\t\t\t\t\tif ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );\n\n\t\t\t\t\trenderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );\n\t\t\t\t\tcubeUVmaps.set( texture, renderTarget );\n\n\t\t\t\t\treturn renderTarget.texture;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tif ( cubeUVmaps.has( texture ) ) {\n\n\t\t\t\t\t\treturn cubeUVmaps.get( texture ).texture;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tconst image = texture.image;\n\n\t\t\t\t\t\tif ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {\n\n\t\t\t\t\t\t\tif ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );\n\n\t\t\t\t\t\t\tconst renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );\n\t\t\t\t\t\t\tcubeUVmaps.set( texture, renderTarget );\n\n\t\t\t\t\t\t\ttexture.addEventListener( 'dispose', onTextureDispose );\n\n\t\t\t\t\t\t\treturn renderTarget.texture;\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t// image not yet ready. try the conversion next frame\n\n\t\t\t\t\t\t\treturn null;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn texture;\n\n\t}\n\n\tfunction isCubeTextureComplete( image ) {\n\n\t\tlet count = 0;\n\t\tconst length = 6;\n\n\t\tfor ( let i = 0; i < length; i ++ ) {\n\n\t\t\tif ( image[ i ] !== undefined ) count ++;\n\n\t\t}\n\n\t\treturn count === length;\n\n\n\t}\n\n\tfunction onTextureDispose( event ) {\n\n\t\tconst texture = event.target;\n\n\t\ttexture.removeEventListener( 'dispose', onTextureDispose );\n\n\t\tconst cubemapUV = cubeUVmaps.get( texture );\n\n\t\tif ( cubemapUV !== undefined ) {\n\n\t\t\tcubeUVmaps.delete( texture );\n\t\t\tcubemapUV.dispose();\n\n\t\t}\n\n\t}\n\n\tfunction dispose() {\n\n\t\tcubeUVmaps = new WeakMap();\n\n\t\tif ( pmremGenerator !== null ) {\n\n\t\t\tpmremGenerator.dispose();\n\t\t\tpmremGenerator = null;\n\n\t\t}\n\n\t}\n\n\treturn {\n\t\tget: get,\n\t\tdispose: dispose\n\t};\n\n}\n\nfunction WebGLExtensions( gl ) {\n\n\tconst extensions = {};\n\n\tfunction getExtension( name ) {\n\n\t\tif ( extensions[ name ] !== undefined ) {\n\n\t\t\treturn extensions[ name ];\n\n\t\t}\n\n\t\tlet extension;\n\n\t\tswitch ( name ) {\n\n\t\t\tcase 'WEBGL_depth_texture':\n\t\t\t\textension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );\n\t\t\t\tbreak;\n\n\t\t\tcase 'EXT_texture_filter_anisotropic':\n\t\t\t\textension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );\n\t\t\t\tbreak;\n\n\t\t\tcase 'WEBGL_compressed_texture_s3tc':\n\t\t\t\textension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );\n\t\t\t\tbreak;\n\n\t\t\tcase 'WEBGL_compressed_texture_pvrtc':\n\t\t\t\textension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\textension = gl.getExtension( name );\n\n\t\t}\n\n\t\textensions[ name ] = extension;\n\n\t\treturn extension;\n\n\t}\n\n\treturn {\n\n\t\thas: function ( name ) {\n\n\t\t\treturn getExtension( name ) !== null;\n\n\t\t},\n\n\t\tinit: function ( capabilities ) {\n\n\t\t\tif ( capabilities.isWebGL2 ) {\n\n\t\t\t\tgetExtension( 'EXT_color_buffer_float' );\n\n\t\t\t} else {\n\n\t\t\t\tgetExtension( 'WEBGL_depth_texture' );\n\t\t\t\tgetExtension( 'OES_texture_float' );\n\t\t\t\tgetExtension( 'OES_texture_half_float' );\n\t\t\t\tgetExtension( 'OES_texture_half_float_linear' );\n\t\t\t\tgetExtension( 'OES_standard_derivatives' );\n\t\t\t\tgetExtension( 'OES_element_index_uint' );\n\t\t\t\tgetExtension( 'OES_vertex_array_object' );\n\t\t\t\tgetExtension( 'ANGLE_instanced_arrays' );\n\n\t\t\t}\n\n\t\t\tgetExtension( 'OES_texture_float_linear' );\n\t\t\tgetExtension( 'EXT_color_buffer_half_float' );\n\t\t\tgetExtension( 'WEBGL_multisampled_render_to_texture' );\n\n\t\t},\n\n\t\tget: function ( name ) {\n\n\t\t\tconst extension = getExtension( name );\n\n\t\t\tif ( extension === null ) {\n\n\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );\n\n\t\t\t}\n\n\t\t\treturn extension;\n\n\t\t}\n\n\t};\n\n}\n\nfunction WebGLGeometries( gl, attributes, info, bindingStates ) {\n\n\tconst geometries = {};\n\tconst wireframeAttributes = new WeakMap();\n\n\tfunction onGeometryDispose( event ) {\n\n\t\tconst geometry = event.target;\n\n\t\tif ( geometry.index !== null ) {\n\n\t\t\tattributes.remove( geometry.index );\n\n\t\t}\n\n\t\tfor ( const name in geometry.attributes ) {\n\n\t\t\tattributes.remove( geometry.attributes[ name ] );\n\n\t\t}\n\n\t\tgeometry.removeEventListener( 'dispose', onGeometryDispose );\n\n\t\tdelete geometries[ geometry.id ];\n\n\t\tconst attribute = wireframeAttributes.get( geometry );\n\n\t\tif ( attribute ) {\n\n\t\t\tattributes.remove( attribute );\n\t\t\twireframeAttributes.delete( geometry );\n\n\t\t}\n\n\t\tbindingStates.releaseStatesOfGeometry( geometry );\n\n\t\tif ( geometry.isInstancedBufferGeometry === true ) {\n\n\t\t\tdelete geometry._maxInstanceCount;\n\n\t\t}\n\n\t\t//\n\n\t\tinfo.memory.geometries --;\n\n\t}\n\n\tfunction get( object, geometry ) {\n\n\t\tif ( geometries[ geometry.id ] === true ) return geometry;\n\n\t\tgeometry.addEventListener( 'dispose', onGeometryDispose );\n\n\t\tgeometries[ geometry.id ] = true;\n\n\t\tinfo.memory.geometries ++;\n\n\t\treturn geometry;\n\n\t}\n\n\tfunction update( geometry ) {\n\n\t\tconst geometryAttributes = geometry.attributes;\n\n\t\t// Updating index buffer in VAO now. See WebGLBindingStates.\n\n\t\tfor ( const name in geometryAttributes ) {\n\n\t\t\tattributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );\n\n\t\t}\n\n\t\t// morph targets\n\n\t\tconst morphAttributes = geometry.morphAttributes;\n\n\t\tfor ( const name in morphAttributes ) {\n\n\t\t\tconst array = morphAttributes[ name ];\n\n\t\t\tfor ( let i = 0, l = array.length; i < l; i ++ ) {\n\n\t\t\t\tattributes.update( array[ i ], gl.ARRAY_BUFFER );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tfunction updateWireframeAttribute( geometry ) {\n\n\t\tconst indices = [];\n\n\t\tconst geometryIndex = geometry.index;\n\t\tconst geometryPosition = geometry.attributes.position;\n\t\tlet version = 0;\n\n\t\tif ( geometryIndex !== null ) {\n\n\t\t\tconst array = geometryIndex.array;\n\t\t\tversion = geometryIndex.version;\n\n\t\t\tfor ( let i = 0, l = array.length; i < l; i += 3 ) {\n\n\t\t\t\tconst a = array[ i + 0 ];\n\t\t\t\tconst b = array[ i + 1 ];\n\t\t\t\tconst c = array[ i + 2 ];\n\n\t\t\t\tindices.push( a, b, b, c, c, a );\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tconst array = geometryPosition.array;\n\t\t\tversion = geometryPosition.version;\n\n\t\t\tfor ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {\n\n\t\t\t\tconst a = i + 0;\n\t\t\t\tconst b = i + 1;\n\t\t\t\tconst c = i + 2;\n\n\t\t\t\tindices.push( a, b, b, c, c, a );\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );\n\t\tattribute.version = version;\n\n\t\t// Updating index buffer in VAO now. See WebGLBindingStates\n\n\t\t//\n\n\t\tconst previousAttribute = wireframeAttributes.get( geometry );\n\n\t\tif ( previousAttribute ) attributes.remove( previousAttribute );\n\n\t\t//\n\n\t\twireframeAttributes.set( geometry, attribute );\n\n\t}\n\n\tfunction getWireframeAttribute( geometry ) {\n\n\t\tconst currentAttribute = wireframeAttributes.get( geometry );\n\n\t\tif ( currentAttribute ) {\n\n\t\t\tconst geometryIndex = geometry.index;\n\n\t\t\tif ( geometryIndex !== null ) {\n\n\t\t\t\t// if the attribute is obsolete, create a new one\n\n\t\t\t\tif ( currentAttribute.version < geometryIndex.version ) {\n\n\t\t\t\t\tupdateWireframeAttribute( geometry );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tupdateWireframeAttribute( geometry );\n\n\t\t}\n\n\t\treturn wireframeAttributes.get( geometry );\n\n\t}\n\n\treturn {\n\n\t\tget: get,\n\t\tupdate: update,\n\n\t\tgetWireframeAttribute: getWireframeAttribute\n\n\t};\n\n}\n\nfunction WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {\n\n\tconst isWebGL2 = capabilities.isWebGL2;\n\n\tlet mode;\n\n\tfunction setMode( value ) {\n\n\t\tmode = value;\n\n\t}\n\n\tlet type, bytesPerElement;\n\n\tfunction setIndex( value ) {\n\n\t\ttype = value.type;\n\t\tbytesPerElement = value.bytesPerElement;\n\n\t}\n\n\tfunction render( start, count ) {\n\n\t\tgl.drawElements( mode, count, type, start * bytesPerElement );\n\n\t\tinfo.update( count, mode, 1 );\n\n\t}\n\n\tfunction renderInstances( start, count, primcount ) {\n\n\t\tif ( primcount === 0 ) return;\n\n\t\tlet extension, methodName;\n\n\t\tif ( isWebGL2 ) {\n\n\t\t\textension = gl;\n\t\t\tmethodName = 'drawElementsInstanced';\n\n\t\t} else {\n\n\t\t\textension = extensions.get( 'ANGLE_instanced_arrays' );\n\t\t\tmethodName = 'drawElementsInstancedANGLE';\n\n\t\t\tif ( extension === null ) {\n\n\t\t\t\tconsole.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t}\n\n\t\textension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );\n\n\t\tinfo.update( count, mode, primcount );\n\n\t}\n\n\t//\n\n\tthis.setMode = setMode;\n\tthis.setIndex = setIndex;\n\tthis.render = render;\n\tthis.renderInstances = renderInstances;\n\n}\n\nfunction WebGLInfo( gl ) {\n\n\tconst memory = {\n\t\tgeometries: 0,\n\t\ttextures: 0\n\t};\n\n\tconst render = {\n\t\tframe: 0,\n\t\tcalls: 0,\n\t\ttriangles: 0,\n\t\tpoints: 0,\n\t\tlines: 0\n\t};\n\n\tfunction update( count, mode, instanceCount ) {\n\n\t\trender.calls ++;\n\n\t\tswitch ( mode ) {\n\n\t\t\tcase gl.TRIANGLES:\n\t\t\t\trender.triangles += instanceCount * ( count / 3 );\n\t\t\t\tbreak;\n\n\t\t\tcase gl.LINES:\n\t\t\t\trender.lines += instanceCount * ( count / 2 );\n\t\t\t\tbreak;\n\n\t\t\tcase gl.LINE_STRIP:\n\t\t\t\trender.lines += instanceCount * ( count - 1 );\n\t\t\t\tbreak;\n\n\t\t\tcase gl.LINE_LOOP:\n\t\t\t\trender.lines += instanceCount * count;\n\t\t\t\tbreak;\n\n\t\t\tcase gl.POINTS:\n\t\t\t\trender.points += instanceCount * count;\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tconsole.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );\n\t\t\t\tbreak;\n\n\t\t}\n\n\t}\n\n\tfunction reset() {\n\n\t\trender.frame ++;\n\t\trender.calls = 0;\n\t\trender.triangles = 0;\n\t\trender.points = 0;\n\t\trender.lines = 0;\n\n\t}\n\n\treturn {\n\t\tmemory: memory,\n\t\trender: render,\n\t\tprograms: null,\n\t\tautoReset: true,\n\t\treset: reset,\n\t\tupdate: update\n\t};\n\n}\n\nfunction numericalSort( a, b ) {\n\n\treturn a[ 0 ] - b[ 0 ];\n\n}\n\nfunction absNumericalSort( a, b ) {\n\n\treturn Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );\n\n}\n\nfunction WebGLMorphtargets( gl, capabilities, textures ) {\n\n\tconst influencesList = {};\n\tconst morphInfluences = new Float32Array( 8 );\n\tconst morphTextures = new WeakMap();\n\tconst morph = new Vector4();\n\n\tconst workInfluences = [];\n\n\tfor ( let i = 0; i < 8; i ++ ) {\n\n\t\tworkInfluences[ i ] = [ i, 0 ];\n\n\t}\n\n\tfunction update( object, geometry, program ) {\n\n\t\tconst objectInfluences = object.morphTargetInfluences;\n\n\t\tif ( capabilities.isWebGL2 === true ) {\n\n\t\t\t// instead of using attributes, the WebGL 2 code path encodes morph targets\n\t\t\t// into an array of data textures. Each layer represents a single morph target.\n\n\t\t\tconst morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;\n\t\t\tconst morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;\n\n\t\t\tlet entry = morphTextures.get( geometry );\n\n\t\t\tif ( entry === undefined || entry.count !== morphTargetsCount ) {\n\n\t\t\t\tif ( entry !== undefined ) entry.texture.dispose();\n\n\t\t\t\tconst hasMorphPosition = geometry.morphAttributes.position !== undefined;\n\t\t\t\tconst hasMorphNormals = geometry.morphAttributes.normal !== undefined;\n\t\t\t\tconst hasMorphColors = geometry.morphAttributes.color !== undefined;\n\n\t\t\t\tconst morphTargets = geometry.morphAttributes.position || [];\n\t\t\t\tconst morphNormals = geometry.morphAttributes.normal || [];\n\t\t\t\tconst morphColors = geometry.morphAttributes.color || [];\n\n\t\t\t\tlet vertexDataCount = 0;\n\n\t\t\t\tif ( hasMorphPosition === true ) vertexDataCount = 1;\n\t\t\t\tif ( hasMorphNormals === true ) vertexDataCount = 2;\n\t\t\t\tif ( hasMorphColors === true ) vertexDataCount = 3;\n\n\t\t\t\tlet width = geometry.attributes.position.count * vertexDataCount;\n\t\t\t\tlet height = 1;\n\n\t\t\t\tif ( width > capabilities.maxTextureSize ) {\n\n\t\t\t\t\theight = Math.ceil( width / capabilities.maxTextureSize );\n\t\t\t\t\twidth = capabilities.maxTextureSize;\n\n\t\t\t\t}\n\n\t\t\t\tconst buffer = new Float32Array( width * height * 4 * morphTargetsCount );\n\n\t\t\t\tconst texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );\n\t\t\t\ttexture.type = FloatType;\n\t\t\t\ttexture.needsUpdate = true;\n\n\t\t\t\t// fill buffer\n\n\t\t\t\tconst vertexDataStride = vertexDataCount * 4;\n\n\t\t\t\tfor ( let i = 0; i < morphTargetsCount; i ++ ) {\n\n\t\t\t\t\tconst morphTarget = morphTargets[ i ];\n\t\t\t\t\tconst morphNormal = morphNormals[ i ];\n\t\t\t\t\tconst morphColor = morphColors[ i ];\n\n\t\t\t\t\tconst offset = width * height * 4 * i;\n\n\t\t\t\t\tfor ( let j = 0; j < morphTarget.count; j ++ ) {\n\n\t\t\t\t\t\tconst stride = j * vertexDataStride;\n\n\t\t\t\t\t\tif ( hasMorphPosition === true ) {\n\n\t\t\t\t\t\t\tmorph.fromBufferAttribute( morphTarget, j );\n\n\t\t\t\t\t\t\tbuffer[ offset + stride + 0 ] = morph.x;\n\t\t\t\t\t\t\tbuffer[ offset + stride + 1 ] = morph.y;\n\t\t\t\t\t\t\tbuffer[ offset + stride + 2 ] = morph.z;\n\t\t\t\t\t\t\tbuffer[ offset + stride + 3 ] = 0;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ( hasMorphNormals === true ) {\n\n\t\t\t\t\t\t\tmorph.fromBufferAttribute( morphNormal, j );\n\n\t\t\t\t\t\t\tbuffer[ offset + stride + 4 ] = morph.x;\n\t\t\t\t\t\t\tbuffer[ offset + stride + 5 ] = morph.y;\n\t\t\t\t\t\t\tbuffer[ offset + stride + 6 ] = morph.z;\n\t\t\t\t\t\t\tbuffer[ offset + stride + 7 ] = 0;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ( hasMorphColors === true ) {\n\n\t\t\t\t\t\t\tmorph.fromBufferAttribute( morphColor, j );\n\n\t\t\t\t\t\t\tbuffer[ offset + stride + 8 ] = morph.x;\n\t\t\t\t\t\t\tbuffer[ offset + stride + 9 ] = morph.y;\n\t\t\t\t\t\t\tbuffer[ offset + stride + 10 ] = morph.z;\n\t\t\t\t\t\t\tbuffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tentry = {\n\t\t\t\t\tcount: morphTargetsCount,\n\t\t\t\t\ttexture: texture,\n\t\t\t\t\tsize: new Vector2( width, height )\n\t\t\t\t};\n\n\t\t\t\tmorphTextures.set( geometry, entry );\n\n\t\t\t\tfunction disposeTexture() {\n\n\t\t\t\t\ttexture.dispose();\n\n\t\t\t\t\tmorphTextures.delete( geometry );\n\n\t\t\t\t\tgeometry.removeEventListener( 'dispose', disposeTexture );\n\n\t\t\t\t}\n\n\t\t\t\tgeometry.addEventListener( 'dispose', disposeTexture );\n\n\t\t\t}\n\n\t\t\t//\n\n\t\t\tlet morphInfluencesSum = 0;\n\n\t\t\tfor ( let i = 0; i < objectInfluences.length; i ++ ) {\n\n\t\t\t\tmorphInfluencesSum += objectInfluences[ i ];\n\n\t\t\t}\n\n\t\t\tconst morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;\n\n\t\t\tprogram.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );\n\t\t\tprogram.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );\n\n\t\t\tprogram.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );\n\t\t\tprogram.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );\n\n\n\t\t} else {\n\n\t\t\t// When object doesn't have morph target influences defined, we treat it as a 0-length array\n\t\t\t// This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences\n\n\t\t\tconst length = objectInfluences === undefined ? 0 : objectInfluences.length;\n\n\t\t\tlet influences = influencesList[ geometry.id ];\n\n\t\t\tif ( influences === undefined || influences.length !== length ) {\n\n\t\t\t\t// initialise list\n\n\t\t\t\tinfluences = [];\n\n\t\t\t\tfor ( let i = 0; i < length; i ++ ) {\n\n\t\t\t\t\tinfluences[ i ] = [ i, 0 ];\n\n\t\t\t\t}\n\n\t\t\t\tinfluencesList[ geometry.id ] = influences;\n\n\t\t\t}\n\n\t\t\t// Collect influences\n\n\t\t\tfor ( let i = 0; i < length; i ++ ) {\n\n\t\t\t\tconst influence = influences[ i ];\n\n\t\t\t\tinfluence[ 0 ] = i;\n\t\t\t\tinfluence[ 1 ] = objectInfluences[ i ];\n\n\t\t\t}\n\n\t\t\tinfluences.sort( absNumericalSort );\n\n\t\t\tfor ( let i = 0; i < 8; i ++ ) {\n\n\t\t\t\tif ( i < length && influences[ i ][ 1 ] ) {\n\n\t\t\t\t\tworkInfluences[ i ][ 0 ] = influences[ i ][ 0 ];\n\t\t\t\t\tworkInfluences[ i ][ 1 ] = influences[ i ][ 1 ];\n\n\t\t\t\t} else {\n\n\t\t\t\t\tworkInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;\n\t\t\t\t\tworkInfluences[ i ][ 1 ] = 0;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tworkInfluences.sort( numericalSort );\n\n\t\t\tconst morphTargets = geometry.morphAttributes.position;\n\t\t\tconst morphNormals = geometry.morphAttributes.normal;\n\n\t\t\tlet morphInfluencesSum = 0;\n\n\t\t\tfor ( let i = 0; i < 8; i ++ ) {\n\n\t\t\t\tconst influence = workInfluences[ i ];\n\t\t\t\tconst index = influence[ 0 ];\n\t\t\t\tconst value = influence[ 1 ];\n\n\t\t\t\tif ( index !== Number.MAX_SAFE_INTEGER && value ) {\n\n\t\t\t\t\tif ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {\n\n\t\t\t\t\t\tgeometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {\n\n\t\t\t\t\t\tgeometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tmorphInfluences[ i ] = value;\n\t\t\t\t\tmorphInfluencesSum += value;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tif ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {\n\n\t\t\t\t\t\tgeometry.deleteAttribute( 'morphTarget' + i );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {\n\n\t\t\t\t\t\tgeometry.deleteAttribute( 'morphNormal' + i );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tmorphInfluences[ i ] = 0;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// GLSL shader uses formula baseinfluence * base + sum(target * influence)\n\t\t\t// This allows us to switch between absolute morphs and relative morphs without changing shader code\n\t\t\t// When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)\n\t\t\tconst morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;\n\n\t\t\tprogram.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );\n\t\t\tprogram.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );\n\n\t\t}\n\n\t}\n\n\treturn {\n\n\t\tupdate: update\n\n\t};\n\n}\n\nfunction WebGLObjects( gl, geometries, attributes, info ) {\n\n\tlet updateMap = new WeakMap();\n\n\tfunction update( object ) {\n\n\t\tconst frame = info.render.frame;\n\n\t\tconst geometry = object.geometry;\n\t\tconst buffergeometry = geometries.get( object, geometry );\n\n\t\t// Update once per frame\n\n\t\tif ( updateMap.get( buffergeometry ) !== frame ) {\n\n\t\t\tgeometries.update( buffergeometry );\n\n\t\t\tupdateMap.set( buffergeometry, frame );\n\n\t\t}\n\n\t\tif ( object.isInstancedMesh ) {\n\n\t\t\tif ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {\n\n\t\t\t\tobject.addEventListener( 'dispose', onInstancedMeshDispose );\n\n\t\t\t}\n\n\t\t\tattributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );\n\n\t\t\tif ( object.instanceColor !== null ) {\n\n\t\t\t\tattributes.update( object.instanceColor, gl.ARRAY_BUFFER );\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn buffergeometry;\n\n\t}\n\n\tfunction dispose() {\n\n\t\tupdateMap = new WeakMap();\n\n\t}\n\n\tfunction onInstancedMeshDispose( event ) {\n\n\t\tconst instancedMesh = event.target;\n\n\t\tinstancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );\n\n\t\tattributes.remove( instancedMesh.instanceMatrix );\n\n\t\tif ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );\n\n\t}\n\n\treturn {\n\n\t\tupdate: update,\n\t\tdispose: dispose\n\n\t};\n\n}\n\n/**\n * Uniforms of a program.\n * Those form a tree structure with a special top-level container for the root,\n * which you get by calling 'new WebGLUniforms( gl, program )'.\n *\n *\n * Properties of inner nodes including the top-level container:\n *\n * .seq - array of nested uniforms\n * .map - nested uniforms by name\n *\n *\n * Methods of all nodes except the top-level container:\n *\n * .setValue( gl, value, [textures] )\n *\n * \t\tuploads a uniform value(s)\n * \tthe 'textures' parameter is needed for sampler uniforms\n *\n *\n * Static methods of the top-level container (textures factorizations):\n *\n * .upload( gl, seq, values, textures )\n *\n * \t\tsets uniforms in 'seq' to 'values[id].value'\n *\n * .seqWithValue( seq, values ) : filteredSeq\n *\n * \t\tfilters 'seq' entries with corresponding entry in values\n *\n *\n * Methods of the top-level container (textures factorizations):\n *\n * .setValue( gl, name, value, textures )\n *\n * \t\tsets uniform with name 'name' to 'value'\n *\n * .setOptional( gl, obj, prop )\n *\n * \t\tlike .set for an optional property of the object\n *\n */\n\nconst emptyTexture = /*@__PURE__*/ new Texture();\nconst emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();\nconst empty3dTexture = /*@__PURE__*/ new Data3DTexture();\nconst emptyCubeTexture = /*@__PURE__*/ new CubeTexture();\n\n// --- Utilities ---\n\n// Array Caches (provide typed arrays for temporary by size)\n\nconst arrayCacheF32 = [];\nconst arrayCacheI32 = [];\n\n// Float32Array caches used for uploading Matrix uniforms\n\nconst mat4array = new Float32Array( 16 );\nconst mat3array = new Float32Array( 9 );\nconst mat2array = new Float32Array( 4 );\n\n// Flattening for arrays of vectors and matrices\n\nfunction flatten( array, nBlocks, blockSize ) {\n\n\tconst firstElem = array[ 0 ];\n\n\tif ( firstElem <= 0 || firstElem > 0 ) return array;\n\t// unoptimized: ! isNaN( firstElem )\n\t// see http://jacksondunstan.com/articles/983\n\n\tconst n = nBlocks * blockSize;\n\tlet r = arrayCacheF32[ n ];\n\n\tif ( r === undefined ) {\n\n\t\tr = new Float32Array( n );\n\t\tarrayCacheF32[ n ] = r;\n\n\t}\n\n\tif ( nBlocks !== 0 ) {\n\n\t\tfirstElem.toArray( r, 0 );\n\n\t\tfor ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {\n\n\t\t\toffset += blockSize;\n\t\t\tarray[ i ].toArray( r, offset );\n\n\t\t}\n\n\t}\n\n\treturn r;\n\n}\n\nfunction arraysEqual( a, b ) {\n\n\tif ( a.length !== b.length ) return false;\n\n\tfor ( let i = 0, l = a.length; i < l; i ++ ) {\n\n\t\tif ( a[ i ] !== b[ i ] ) return false;\n\n\t}\n\n\treturn true;\n\n}\n\nfunction copyArray( a, b ) {\n\n\tfor ( let i = 0, l = b.length; i < l; i ++ ) {\n\n\t\ta[ i ] = b[ i ];\n\n\t}\n\n}\n\n// Texture unit allocation\n\nfunction allocTexUnits( textures, n ) {\n\n\tlet r = arrayCacheI32[ n ];\n\n\tif ( r === undefined ) {\n\n\t\tr = new Int32Array( n );\n\t\tarrayCacheI32[ n ] = r;\n\n\t}\n\n\tfor ( let i = 0; i !== n; ++ i ) {\n\n\t\tr[ i ] = textures.allocateTextureUnit();\n\n\t}\n\n\treturn r;\n\n}\n\n// --- Setters ---\n\n// Note: Defining these methods externally, because they come in a bunch\n// and this way their names minify.\n\n// Single scalar\n\nfunction setValueV1f( gl, v ) {\n\n\tconst cache = this.cache;\n\n\tif ( cache[ 0 ] === v ) return;\n\n\tgl.uniform1f( this.addr, v );\n\n\tcache[ 0 ] = v;\n\n}\n\n// Single float vector (from flat array or THREE.VectorN)\n\nfunction setValueV2f( gl, v ) {\n\n\tconst cache = this.cache;\n\n\tif ( v.x !== undefined ) {\n\n\t\tif ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {\n\n\t\t\tgl.uniform2f( this.addr, v.x, v.y );\n\n\t\t\tcache[ 0 ] = v.x;\n\t\t\tcache[ 1 ] = v.y;\n\n\t\t}\n\n\t} else {\n\n\t\tif ( arraysEqual( cache, v ) ) return;\n\n\t\tgl.uniform2fv( this.addr, v );\n\n\t\tcopyArray( cache, v );\n\n\t}\n\n}\n\nfunction setValueV3f( gl, v ) {\n\n\tconst cache = this.cache;\n\n\tif ( v.x !== undefined ) {\n\n\t\tif ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {\n\n\t\t\tgl.uniform3f( this.addr, v.x, v.y, v.z );\n\n\t\t\tcache[ 0 ] = v.x;\n\t\t\tcache[ 1 ] = v.y;\n\t\t\tcache[ 2 ] = v.z;\n\n\t\t}\n\n\t} else if ( v.r !== undefined ) {\n\n\t\tif ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {\n\n\t\t\tgl.uniform3f( this.addr, v.r, v.g, v.b );\n\n\t\t\tcache[ 0 ] = v.r;\n\t\t\tcache[ 1 ] = v.g;\n\t\t\tcache[ 2 ] = v.b;\n\n\t\t}\n\n\t} else {\n\n\t\tif ( arraysEqual( cache, v ) ) return;\n\n\t\tgl.uniform3fv( this.addr, v );\n\n\t\tcopyArray( cache, v );\n\n\t}\n\n}\n\nfunction setValueV4f( gl, v ) {\n\n\tconst cache = this.cache;\n\n\tif ( v.x !== undefined ) {\n\n\t\tif ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {\n\n\t\t\tgl.uniform4f( this.addr, v.x, v.y, v.z, v.w );\n\n\t\t\tcache[ 0 ] = v.x;\n\t\t\tcache[ 1 ] = v.y;\n\t\t\tcache[ 2 ] = v.z;\n\t\t\tcache[ 3 ] = v.w;\n\n\t\t}\n\n\t} else {\n\n\t\tif ( arraysEqual( cache, v ) ) return;\n\n\t\tgl.uniform4fv( this.addr, v );\n\n\t\tcopyArray( cache, v );\n\n\t}\n\n}\n\n// Single matrix (from flat array or THREE.MatrixN)\n\nfunction setValueM2( gl, v ) {\n\n\tconst cache = this.cache;\n\tconst elements = v.elements;\n\n\tif ( elements === undefined ) {\n\n\t\tif ( arraysEqual( cache, v ) ) return;\n\n\t\tgl.uniformMatrix2fv( this.addr, false, v );\n\n\t\tcopyArray( cache, v );\n\n\t} else {\n\n\t\tif ( arraysEqual( cache, elements ) ) return;\n\n\t\tmat2array.set( elements );\n\n\t\tgl.uniformMatrix2fv( this.addr, false, mat2array );\n\n\t\tcopyArray( cache, elements );\n\n\t}\n\n}\n\nfunction setValueM3( gl, v ) {\n\n\tconst cache = this.cache;\n\tconst elements = v.elements;\n\n\tif ( elements === undefined ) {\n\n\t\tif ( arraysEqual( cache, v ) ) return;\n\n\t\tgl.uniformMatrix3fv( this.addr, false, v );\n\n\t\tcopyArray( cache, v );\n\n\t} else {\n\n\t\tif ( arraysEqual( cache, elements ) ) return;\n\n\t\tmat3array.set( elements );\n\n\t\tgl.uniformMatrix3fv( this.addr, false, mat3array );\n\n\t\tcopyArray( cache, elements );\n\n\t}\n\n}\n\nfunction setValueM4( gl, v ) {\n\n\tconst cache = this.cache;\n\tconst elements = v.elements;\n\n\tif ( elements === undefined ) {\n\n\t\tif ( arraysEqual( cache, v ) ) return;\n\n\t\tgl.uniformMatrix4fv( this.addr, false, v );\n\n\t\tcopyArray( cache, v );\n\n\t} else {\n\n\t\tif ( arraysEqual( cache, elements ) ) return;\n\n\t\tmat4array.set( elements );\n\n\t\tgl.uniformMatrix4fv( this.addr, false, mat4array );\n\n\t\tcopyArray( cache, elements );\n\n\t}\n\n}\n\n// Single integer / boolean\n\nfunction setValueV1i( gl, v ) {\n\n\tconst cache = this.cache;\n\n\tif ( cache[ 0 ] === v ) return;\n\n\tgl.uniform1i( this.addr, v );\n\n\tcache[ 0 ] = v;\n\n}\n\n// Single integer / boolean vector (from flat array or THREE.VectorN)\n\nfunction setValueV2i( gl, v ) {\n\n\tconst cache = this.cache;\n\n\tif ( v.x !== undefined ) {\n\n\t\tif ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {\n\n\t\t\tgl.uniform2i( this.addr, v.x, v.y );\n\n\t\t\tcache[ 0 ] = v.x;\n\t\t\tcache[ 1 ] = v.y;\n\n\t\t}\n\n\t} else {\n\n\t\tif ( arraysEqual( cache, v ) ) return;\n\n\t\tgl.uniform2iv( this.addr, v );\n\n\t\tcopyArray( cache, v );\n\n\t}\n\n}\n\nfunction setValueV3i( gl, v ) {\n\n\tconst cache = this.cache;\n\n\tif ( v.x !== undefined ) {\n\n\t\tif ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {\n\n\t\t\tgl.uniform3i( this.addr, v.x, v.y, v.z );\n\n\t\t\tcache[ 0 ] = v.x;\n\t\t\tcache[ 1 ] = v.y;\n\t\t\tcache[ 2 ] = v.z;\n\n\t\t}\n\n\t} else {\n\n\t\tif ( arraysEqual( cache, v ) ) return;\n\n\t\tgl.uniform3iv( this.addr, v );\n\n\t\tcopyArray( cache, v );\n\n\t}\n\n}\n\nfunction setValueV4i( gl, v ) {\n\n\tconst cache = this.cache;\n\n\tif ( v.x !== undefined ) {\n\n\t\tif ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {\n\n\t\t\tgl.uniform4i( this.addr, v.x, v.y, v.z, v.w );\n\n\t\t\tcache[ 0 ] = v.x;\n\t\t\tcache[ 1 ] = v.y;\n\t\t\tcache[ 2 ] = v.z;\n\t\t\tcache[ 3 ] = v.w;\n\n\t\t}\n\n\t} else {\n\n\t\tif ( arraysEqual( cache, v ) ) return;\n\n\t\tgl.uniform4iv( this.addr, v );\n\n\t\tcopyArray( cache, v );\n\n\t}\n\n}\n\n// Single unsigned integer\n\nfunction setValueV1ui( gl, v ) {\n\n\tconst cache = this.cache;\n\n\tif ( cache[ 0 ] === v ) return;\n\n\tgl.uniform1ui( this.addr, v );\n\n\tcache[ 0 ] = v;\n\n}\n\n// Single unsigned integer vector (from flat array or THREE.VectorN)\n\nfunction setValueV2ui( gl, v ) {\n\n\tconst cache = this.cache;\n\n\tif ( v.x !== undefined ) {\n\n\t\tif ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {\n\n\t\t\tgl.uniform2ui( this.addr, v.x, v.y );\n\n\t\t\tcache[ 0 ] = v.x;\n\t\t\tcache[ 1 ] = v.y;\n\n\t\t}\n\n\t} else {\n\n\t\tif ( arraysEqual( cache, v ) ) return;\n\n\t\tgl.uniform2uiv( this.addr, v );\n\n\t\tcopyArray( cache, v );\n\n\t}\n\n}\n\nfunction setValueV3ui( gl, v ) {\n\n\tconst cache = this.cache;\n\n\tif ( v.x !== undefined ) {\n\n\t\tif ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {\n\n\t\t\tgl.uniform3ui( this.addr, v.x, v.y, v.z );\n\n\t\t\tcache[ 0 ] = v.x;\n\t\t\tcache[ 1 ] = v.y;\n\t\t\tcache[ 2 ] = v.z;\n\n\t\t}\n\n\t} else {\n\n\t\tif ( arraysEqual( cache, v ) ) return;\n\n\t\tgl.uniform3uiv( this.addr, v );\n\n\t\tcopyArray( cache, v );\n\n\t}\n\n}\n\nfunction setValueV4ui( gl, v ) {\n\n\tconst cache = this.cache;\n\n\tif ( v.x !== undefined ) {\n\n\t\tif ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {\n\n\t\t\tgl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );\n\n\t\t\tcache[ 0 ] = v.x;\n\t\t\tcache[ 1 ] = v.y;\n\t\t\tcache[ 2 ] = v.z;\n\t\t\tcache[ 3 ] = v.w;\n\n\t\t}\n\n\t} else {\n\n\t\tif ( arraysEqual( cache, v ) ) return;\n\n\t\tgl.uniform4uiv( this.addr, v );\n\n\t\tcopyArray( cache, v );\n\n\t}\n\n}\n\n\n// Single texture (2D / Cube)\n\nfunction setValueT1( gl, v, textures ) {\n\n\tconst cache = this.cache;\n\tconst unit = textures.allocateTextureUnit();\n\n\tif ( cache[ 0 ] !== unit ) {\n\n\t\tgl.uniform1i( this.addr, unit );\n\t\tcache[ 0 ] = unit;\n\n\t}\n\n\ttextures.setTexture2D( v || emptyTexture, unit );\n\n}\n\nfunction setValueT3D1( gl, v, textures ) {\n\n\tconst cache = this.cache;\n\tconst unit = textures.allocateTextureUnit();\n\n\tif ( cache[ 0 ] !== unit ) {\n\n\t\tgl.uniform1i( this.addr, unit );\n\t\tcache[ 0 ] = unit;\n\n\t}\n\n\ttextures.setTexture3D( v || empty3dTexture, unit );\n\n}\n\nfunction setValueT6( gl, v, textures ) {\n\n\tconst cache = this.cache;\n\tconst unit = textures.allocateTextureUnit();\n\n\tif ( cache[ 0 ] !== unit ) {\n\n\t\tgl.uniform1i( this.addr, unit );\n\t\tcache[ 0 ] = unit;\n\n\t}\n\n\ttextures.setTextureCube( v || emptyCubeTexture, unit );\n\n}\n\nfunction setValueT2DArray1( gl, v, textures ) {\n\n\tconst cache = this.cache;\n\tconst unit = textures.allocateTextureUnit();\n\n\tif ( cache[ 0 ] !== unit ) {\n\n\t\tgl.uniform1i( this.addr, unit );\n\t\tcache[ 0 ] = unit;\n\n\t}\n\n\ttextures.setTexture2DArray( v || emptyArrayTexture, unit );\n\n}\n\n// Helper to pick the right setter for the singular case\n\nfunction getSingularSetter( type ) {\n\n\tswitch ( type ) {\n\n\t\tcase 0x1406: return setValueV1f; // FLOAT\n\t\tcase 0x8b50: return setValueV2f; // _VEC2\n\t\tcase 0x8b51: return setValueV3f; // _VEC3\n\t\tcase 0x8b52: return setValueV4f; // _VEC4\n\n\t\tcase 0x8b5a: return setValueM2; // _MAT2\n\t\tcase 0x8b5b: return setValueM3; // _MAT3\n\t\tcase 0x8b5c: return setValueM4; // _MAT4\n\n\t\tcase 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL\n\t\tcase 0x8b53: case 0x8b57: return setValueV2i; // _VEC2\n\t\tcase 0x8b54: case 0x8b58: return setValueV3i; // _VEC3\n\t\tcase 0x8b55: case 0x8b59: return setValueV4i; // _VEC4\n\n\t\tcase 0x1405: return setValueV1ui; // UINT\n\t\tcase 0x8dc6: return setValueV2ui; // _VEC2\n\t\tcase 0x8dc7: return setValueV3ui; // _VEC3\n\t\tcase 0x8dc8: return setValueV4ui; // _VEC4\n\n\t\tcase 0x8b5e: // SAMPLER_2D\n\t\tcase 0x8d66: // SAMPLER_EXTERNAL_OES\n\t\tcase 0x8dca: // INT_SAMPLER_2D\n\t\tcase 0x8dd2: // UNSIGNED_INT_SAMPLER_2D\n\t\tcase 0x8b62: // SAMPLER_2D_SHADOW\n\t\t\treturn setValueT1;\n\n\t\tcase 0x8b5f: // SAMPLER_3D\n\t\tcase 0x8dcb: // INT_SAMPLER_3D\n\t\tcase 0x8dd3: // UNSIGNED_INT_SAMPLER_3D\n\t\t\treturn setValueT3D1;\n\n\t\tcase 0x8b60: // SAMPLER_CUBE\n\t\tcase 0x8dcc: // INT_SAMPLER_CUBE\n\t\tcase 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE\n\t\tcase 0x8dc5: // SAMPLER_CUBE_SHADOW\n\t\t\treturn setValueT6;\n\n\t\tcase 0x8dc1: // SAMPLER_2D_ARRAY\n\t\tcase 0x8dcf: // INT_SAMPLER_2D_ARRAY\n\t\tcase 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY\n\t\tcase 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW\n\t\t\treturn setValueT2DArray1;\n\n\t}\n\n}\n\n\n// Array of scalars\n\nfunction setValueV1fArray( gl, v ) {\n\n\tgl.uniform1fv( this.addr, v );\n\n}\n\n// Array of vectors (from flat array or array of THREE.VectorN)\n\nfunction setValueV2fArray( gl, v ) {\n\n\tconst data = flatten( v, this.size, 2 );\n\n\tgl.uniform2fv( this.addr, data );\n\n}\n\nfunction setValueV3fArray( gl, v ) {\n\n\tconst data = flatten( v, this.size, 3 );\n\n\tgl.uniform3fv( this.addr, data );\n\n}\n\nfunction setValueV4fArray( gl, v ) {\n\n\tconst data = flatten( v, this.size, 4 );\n\n\tgl.uniform4fv( this.addr, data );\n\n}\n\n// Array of matrices (from flat array or array of THREE.MatrixN)\n\nfunction setValueM2Array( gl, v ) {\n\n\tconst data = flatten( v, this.size, 4 );\n\n\tgl.uniformMatrix2fv( this.addr, false, data );\n\n}\n\nfunction setValueM3Array( gl, v ) {\n\n\tconst data = flatten( v, this.size, 9 );\n\n\tgl.uniformMatrix3fv( this.addr, false, data );\n\n}\n\nfunction setValueM4Array( gl, v ) {\n\n\tconst data = flatten( v, this.size, 16 );\n\n\tgl.uniformMatrix4fv( this.addr, false, data );\n\n}\n\n// Array of integer / boolean\n\nfunction setValueV1iArray( gl, v ) {\n\n\tgl.uniform1iv( this.addr, v );\n\n}\n\n// Array of integer / boolean vectors (from flat array)\n\nfunction setValueV2iArray( gl, v ) {\n\n\tgl.uniform2iv( this.addr, v );\n\n}\n\nfunction setValueV3iArray( gl, v ) {\n\n\tgl.uniform3iv( this.addr, v );\n\n}\n\nfunction setValueV4iArray( gl, v ) {\n\n\tgl.uniform4iv( this.addr, v );\n\n}\n\n// Array of unsigned integer\n\nfunction setValueV1uiArray( gl, v ) {\n\n\tgl.uniform1uiv( this.addr, v );\n\n}\n\n// Array of unsigned integer vectors (from flat array)\n\nfunction setValueV2uiArray( gl, v ) {\n\n\tgl.uniform2uiv( this.addr, v );\n\n}\n\nfunction setValueV3uiArray( gl, v ) {\n\n\tgl.uniform3uiv( this.addr, v );\n\n}\n\nfunction setValueV4uiArray( gl, v ) {\n\n\tgl.uniform4uiv( this.addr, v );\n\n}\n\n\n// Array of textures (2D / 3D / Cube / 2DArray)\n\nfunction setValueT1Array( gl, v, textures ) {\n\n\tconst cache = this.cache;\n\n\tconst n = v.length;\n\n\tconst units = allocTexUnits( textures, n );\n\n\tif ( ! arraysEqual( cache, units ) ) {\n\n\t\tgl.uniform1iv( this.addr, units );\n\n\t\tcopyArray( cache, units );\n\n\t}\n\n\tfor ( let i = 0; i !== n; ++ i ) {\n\n\t\ttextures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );\n\n\t}\n\n}\n\nfunction setValueT3DArray( gl, v, textures ) {\n\n\tconst cache = this.cache;\n\n\tconst n = v.length;\n\n\tconst units = allocTexUnits( textures, n );\n\n\tif ( ! arraysEqual( cache, units ) ) {\n\n\t\tgl.uniform1iv( this.addr, units );\n\n\t\tcopyArray( cache, units );\n\n\t}\n\n\tfor ( let i = 0; i !== n; ++ i ) {\n\n\t\ttextures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );\n\n\t}\n\n}\n\nfunction setValueT6Array( gl, v, textures ) {\n\n\tconst cache = this.cache;\n\n\tconst n = v.length;\n\n\tconst units = allocTexUnits( textures, n );\n\n\tif ( ! arraysEqual( cache, units ) ) {\n\n\t\tgl.uniform1iv( this.addr, units );\n\n\t\tcopyArray( cache, units );\n\n\t}\n\n\tfor ( let i = 0; i !== n; ++ i ) {\n\n\t\ttextures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );\n\n\t}\n\n}\n\nfunction setValueT2DArrayArray( gl, v, textures ) {\n\n\tconst cache = this.cache;\n\n\tconst n = v.length;\n\n\tconst units = allocTexUnits( textures, n );\n\n\tif ( ! arraysEqual( cache, units ) ) {\n\n\t\tgl.uniform1iv( this.addr, units );\n\n\t\tcopyArray( cache, units );\n\n\t}\n\n\tfor ( let i = 0; i !== n; ++ i ) {\n\n\t\ttextures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );\n\n\t}\n\n}\n\n\n// Helper to pick the right setter for a pure (bottom-level) array\n\nfunction getPureArraySetter( type ) {\n\n\tswitch ( type ) {\n\n\t\tcase 0x1406: return setValueV1fArray; // FLOAT\n\t\tcase 0x8b50: return setValueV2fArray; // _VEC2\n\t\tcase 0x8b51: return setValueV3fArray; // _VEC3\n\t\tcase 0x8b52: return setValueV4fArray; // _VEC4\n\n\t\tcase 0x8b5a: return setValueM2Array; // _MAT2\n\t\tcase 0x8b5b: return setValueM3Array; // _MAT3\n\t\tcase 0x8b5c: return setValueM4Array; // _MAT4\n\n\t\tcase 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL\n\t\tcase 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2\n\t\tcase 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3\n\t\tcase 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4\n\n\t\tcase 0x1405: return setValueV1uiArray; // UINT\n\t\tcase 0x8dc6: return setValueV2uiArray; // _VEC2\n\t\tcase 0x8dc7: return setValueV3uiArray; // _VEC3\n\t\tcase 0x8dc8: return setValueV4uiArray; // _VEC4\n\n\t\tcase 0x8b5e: // SAMPLER_2D\n\t\tcase 0x8d66: // SAMPLER_EXTERNAL_OES\n\t\tcase 0x8dca: // INT_SAMPLER_2D\n\t\tcase 0x8dd2: // UNSIGNED_INT_SAMPLER_2D\n\t\tcase 0x8b62: // SAMPLER_2D_SHADOW\n\t\t\treturn setValueT1Array;\n\n\t\tcase 0x8b5f: // SAMPLER_3D\n\t\tcase 0x8dcb: // INT_SAMPLER_3D\n\t\tcase 0x8dd3: // UNSIGNED_INT_SAMPLER_3D\n\t\t\treturn setValueT3DArray;\n\n\t\tcase 0x8b60: // SAMPLER_CUBE\n\t\tcase 0x8dcc: // INT_SAMPLER_CUBE\n\t\tcase 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE\n\t\tcase 0x8dc5: // SAMPLER_CUBE_SHADOW\n\t\t\treturn setValueT6Array;\n\n\t\tcase 0x8dc1: // SAMPLER_2D_ARRAY\n\t\tcase 0x8dcf: // INT_SAMPLER_2D_ARRAY\n\t\tcase 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY\n\t\tcase 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW\n\t\t\treturn setValueT2DArrayArray;\n\n\t}\n\n}\n\n// --- Uniform Classes ---\n\nclass SingleUniform {\n\n\tconstructor( id, activeInfo, addr ) {\n\n\t\tthis.id = id;\n\t\tthis.addr = addr;\n\t\tthis.cache = [];\n\t\tthis.setValue = getSingularSetter( activeInfo.type );\n\n\t\t// this.path = activeInfo.name; // DEBUG\n\n\t}\n\n}\n\nclass PureArrayUniform {\n\n\tconstructor( id, activeInfo, addr ) {\n\n\t\tthis.id = id;\n\t\tthis.addr = addr;\n\t\tthis.cache = [];\n\t\tthis.size = activeInfo.size;\n\t\tthis.setValue = getPureArraySetter( activeInfo.type );\n\n\t\t// this.path = activeInfo.name; // DEBUG\n\n\t}\n\n}\n\nclass StructuredUniform {\n\n\tconstructor( id ) {\n\n\t\tthis.id = id;\n\n\t\tthis.seq = [];\n\t\tthis.map = {};\n\n\t}\n\n\tsetValue( gl, value, textures ) {\n\n\t\tconst seq = this.seq;\n\n\t\tfor ( let i = 0, n = seq.length; i !== n; ++ i ) {\n\n\t\t\tconst u = seq[ i ];\n\t\t\tu.setValue( gl, value[ u.id ], textures );\n\n\t\t}\n\n\t}\n\n}\n\n// --- Top-level ---\n\n// Parser - builds up the property tree from the path strings\n\nconst RePathPart = /(\\w+)(\\])?(\\[|\\.)?/g;\n\n// extracts\n// \t- the identifier (member name or array index)\n// - followed by an optional right bracket (found when array index)\n// - followed by an optional left bracket or dot (type of subscript)\n//\n// Note: These portions can be read in a non-overlapping fashion and\n// allow straightforward parsing of the hierarchy that WebGL encodes\n// in the uniform names.\n\nfunction addUniform( container, uniformObject ) {\n\n\tcontainer.seq.push( uniformObject );\n\tcontainer.map[ uniformObject.id ] = uniformObject;\n\n}\n\nfunction parseUniform( activeInfo, addr, container ) {\n\n\tconst path = activeInfo.name,\n\t\tpathLength = path.length;\n\n\t// reset RegExp object, because of the early exit of a previous run\n\tRePathPart.lastIndex = 0;\n\n\twhile ( true ) {\n\n\t\tconst match = RePathPart.exec( path ),\n\t\t\tmatchEnd = RePathPart.lastIndex;\n\n\t\tlet id = match[ 1 ];\n\t\tconst idIsIndex = match[ 2 ] === ']',\n\t\t\tsubscript = match[ 3 ];\n\n\t\tif ( idIsIndex ) id = id | 0; // convert to integer\n\n\t\tif ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {\n\n\t\t\t// bare name or \"pure\" bottom-level array \"[0]\" suffix\n\n\t\t\taddUniform( container, subscript === undefined ?\n\t\t\t\tnew SingleUniform( id, activeInfo, addr ) :\n\t\t\t\tnew PureArrayUniform( id, activeInfo, addr ) );\n\n\t\t\tbreak;\n\n\t\t} else {\n\n\t\t\t// step into inner node / create it in case it doesn't exist\n\n\t\t\tconst map = container.map;\n\t\t\tlet next = map[ id ];\n\n\t\t\tif ( next === undefined ) {\n\n\t\t\t\tnext = new StructuredUniform( id );\n\t\t\t\taddUniform( container, next );\n\n\t\t\t}\n\n\t\t\tcontainer = next;\n\n\t\t}\n\n\t}\n\n}\n\n// Root Container\n\nclass WebGLUniforms {\n\n\tconstructor( gl, program ) {\n\n\t\tthis.seq = [];\n\t\tthis.map = {};\n\n\t\tconst n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );\n\n\t\tfor ( let i = 0; i < n; ++ i ) {\n\n\t\t\tconst info = gl.getActiveUniform( program, i ),\n\t\t\t\taddr = gl.getUniformLocation( program, info.name );\n\n\t\t\tparseUniform( info, addr, this );\n\n\t\t}\n\n\t}\n\n\tsetValue( gl, name, value, textures ) {\n\n\t\tconst u = this.map[ name ];\n\n\t\tif ( u !== undefined ) u.setValue( gl, value, textures );\n\n\t}\n\n\tsetOptional( gl, object, name ) {\n\n\t\tconst v = object[ name ];\n\n\t\tif ( v !== undefined ) this.setValue( gl, name, v );\n\n\t}\n\n\tstatic upload( gl, seq, values, textures ) {\n\n\t\tfor ( let i = 0, n = seq.length; i !== n; ++ i ) {\n\n\t\t\tconst u = seq[ i ],\n\t\t\t\tv = values[ u.id ];\n\n\t\t\tif ( v.needsUpdate !== false ) {\n\n\t\t\t\t// note: always updating when .needsUpdate is undefined\n\t\t\t\tu.setValue( gl, v.value, textures );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tstatic seqWithValue( seq, values ) {\n\n\t\tconst r = [];\n\n\t\tfor ( let i = 0, n = seq.length; i !== n; ++ i ) {\n\n\t\t\tconst u = seq[ i ];\n\t\t\tif ( u.id in values ) r.push( u );\n\n\t\t}\n\n\t\treturn r;\n\n\t}\n\n}\n\nfunction WebGLShader( gl, type, string ) {\n\n\tconst shader = gl.createShader( type );\n\n\tgl.shaderSource( shader, string );\n\tgl.compileShader( shader );\n\n\treturn shader;\n\n}\n\nlet programIdCount = 0;\n\nfunction handleSource( string, errorLine ) {\n\n\tconst lines = string.split( '\\n' );\n\tconst lines2 = [];\n\n\tconst from = Math.max( errorLine - 6, 0 );\n\tconst to = Math.min( errorLine + 6, lines.length );\n\n\tfor ( let i = from; i < to; i ++ ) {\n\n\t\tconst line = i + 1;\n\t\tlines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );\n\n\t}\n\n\treturn lines2.join( '\\n' );\n\n}\n\nfunction getEncodingComponents( colorSpace ) {\n\n\tswitch ( colorSpace ) {\n\n\t\tcase LinearSRGBColorSpace:\n\t\t\treturn [ 'Linear', '( value )' ];\n\t\tcase SRGBColorSpace:\n\t\t\treturn [ 'sRGB', '( value )' ];\n\t\tdefault:\n\t\t\tconsole.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace );\n\t\t\treturn [ 'Linear', '( value )' ];\n\n\t}\n\n}\n\nfunction getShaderErrors( gl, shader, type ) {\n\n\tconst status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );\n\tconst errors = gl.getShaderInfoLog( shader ).trim();\n\n\tif ( status && errors === '' ) return '';\n\n\tconst errorMatches = /ERROR: 0:(\\d+)/.exec( errors );\n\tif ( errorMatches ) {\n\n\t\t// --enable-privileged-webgl-extension\n\t\t// console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );\n\n\t\tconst errorLine = parseInt( errorMatches[ 1 ] );\n\t\treturn type.toUpperCase() + '\\n\\n' + errors + '\\n\\n' + handleSource( gl.getShaderSource( shader ), errorLine );\n\n\t} else {\n\n\t\treturn errors;\n\n\t}\n\n}\n\nfunction getTexelEncodingFunction( functionName, colorSpace ) {\n\n\tconst components = getEncodingComponents( colorSpace );\n\treturn 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';\n\n}\n\nfunction getToneMappingFunction( functionName, toneMapping ) {\n\n\tlet toneMappingName;\n\n\tswitch ( toneMapping ) {\n\n\t\tcase LinearToneMapping:\n\t\t\ttoneMappingName = 'Linear';\n\t\t\tbreak;\n\n\t\tcase ReinhardToneMapping:\n\t\t\ttoneMappingName = 'Reinhard';\n\t\t\tbreak;\n\n\t\tcase CineonToneMapping:\n\t\t\ttoneMappingName = 'OptimizedCineon';\n\t\t\tbreak;\n\n\t\tcase ACESFilmicToneMapping:\n\t\t\ttoneMappingName = 'ACESFilmic';\n\t\t\tbreak;\n\n\t\tcase CustomToneMapping:\n\t\t\ttoneMappingName = 'Custom';\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tconsole.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );\n\t\t\ttoneMappingName = 'Linear';\n\n\t}\n\n\treturn 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';\n\n}\n\nfunction generateExtensions( parameters ) {\n\n\tconst chunks = [\n\t\t( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',\n\t\t( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',\n\t\t( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',\n\t\t( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''\n\t];\n\n\treturn chunks.filter( filterEmptyLine ).join( '\\n' );\n\n}\n\nfunction generateDefines( defines ) {\n\n\tconst chunks = [];\n\n\tfor ( const name in defines ) {\n\n\t\tconst value = defines[ name ];\n\n\t\tif ( value === false ) continue;\n\n\t\tchunks.push( '#define ' + name + ' ' + value );\n\n\t}\n\n\treturn chunks.join( '\\n' );\n\n}\n\nfunction fetchAttributeLocations( gl, program ) {\n\n\tconst attributes = {};\n\n\tconst n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );\n\n\tfor ( let i = 0; i < n; i ++ ) {\n\n\t\tconst info = gl.getActiveAttrib( program, i );\n\t\tconst name = info.name;\n\n\t\tlet locationSize = 1;\n\t\tif ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;\n\t\tif ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;\n\t\tif ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;\n\n\t\t// console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );\n\n\t\tattributes[ name ] = {\n\t\t\ttype: info.type,\n\t\t\tlocation: gl.getAttribLocation( program, name ),\n\t\t\tlocationSize: locationSize\n\t\t};\n\n\t}\n\n\treturn attributes;\n\n}\n\nfunction filterEmptyLine( string ) {\n\n\treturn string !== '';\n\n}\n\nfunction replaceLightNums( string, parameters ) {\n\n\tconst numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;\n\n\treturn string\n\t\t.replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )\n\t\t.replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )\n\t\t.replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )\n\t\t.replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )\n\t\t.replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )\n\t\t.replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )\n\t\t.replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )\n\t\t.replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )\n\t\t.replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )\n\t\t.replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )\n\t\t.replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );\n\n}\n\nfunction replaceClippingPlaneNums( string, parameters ) {\n\n\treturn string\n\t\t.replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )\n\t\t.replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );\n\n}\n\n// Resolve Includes\n\nconst includePattern = /^[ \\t]*#include +<([\\w\\d./]+)>/gm;\n\nfunction resolveIncludes( string ) {\n\n\treturn string.replace( includePattern, includeReplacer );\n\n}\n\nfunction includeReplacer( match, include ) {\n\n\tconst string = ShaderChunk[ include ];\n\n\tif ( string === undefined ) {\n\n\t\tthrow new Error( 'Can not resolve #include <' + include + '>' );\n\n\t}\n\n\treturn resolveIncludes( string );\n\n}\n\n// Unroll Loops\n\nconst unrollLoopPattern = /#pragma unroll_loop_start\\s+for\\s*\\(\\s*int\\s+i\\s*=\\s*(\\d+)\\s*;\\s*i\\s*<\\s*(\\d+)\\s*;\\s*i\\s*\\+\\+\\s*\\)\\s*{([\\s\\S]+?)}\\s+#pragma unroll_loop_end/g;\n\nfunction unrollLoops( string ) {\n\n\treturn string.replace( unrollLoopPattern, loopReplacer );\n\n}\n\nfunction loopReplacer( match, start, end, snippet ) {\n\n\tlet string = '';\n\n\tfor ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {\n\n\t\tstring += snippet\n\t\t\t.replace( /\\[\\s*i\\s*\\]/g, '[ ' + i + ' ]' )\n\t\t\t.replace( /UNROLLED_LOOP_INDEX/g, i );\n\n\t}\n\n\treturn string;\n\n}\n\n//\n\nfunction generatePrecision( parameters ) {\n\n\tlet precisionstring = 'precision ' + parameters.precision + ' float;\\nprecision ' + parameters.precision + ' int;';\n\n\tif ( parameters.precision === 'highp' ) {\n\n\t\tprecisionstring += '\\n#define HIGH_PRECISION';\n\n\t} else if ( parameters.precision === 'mediump' ) {\n\n\t\tprecisionstring += '\\n#define MEDIUM_PRECISION';\n\n\t} else if ( parameters.precision === 'lowp' ) {\n\n\t\tprecisionstring += '\\n#define LOW_PRECISION';\n\n\t}\n\n\treturn precisionstring;\n\n}\n\nfunction generateShadowMapTypeDefine( parameters ) {\n\n\tlet shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';\n\n\tif ( parameters.shadowMapType === PCFShadowMap ) {\n\n\t\tshadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';\n\n\t} else if ( parameters.shadowMapType === PCFSoftShadowMap ) {\n\n\t\tshadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';\n\n\t} else if ( parameters.shadowMapType === VSMShadowMap ) {\n\n\t\tshadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';\n\n\t}\n\n\treturn shadowMapTypeDefine;\n\n}\n\nfunction generateEnvMapTypeDefine( parameters ) {\n\n\tlet envMapTypeDefine = 'ENVMAP_TYPE_CUBE';\n\n\tif ( parameters.envMap ) {\n\n\t\tswitch ( parameters.envMapMode ) {\n\n\t\t\tcase CubeReflectionMapping:\n\t\t\tcase CubeRefractionMapping:\n\t\t\t\tenvMapTypeDefine = 'ENVMAP_TYPE_CUBE';\n\t\t\t\tbreak;\n\n\t\t\tcase CubeUVReflectionMapping:\n\t\t\t\tenvMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';\n\t\t\t\tbreak;\n\n\t\t}\n\n\t}\n\n\treturn envMapTypeDefine;\n\n}\n\nfunction generateEnvMapModeDefine( parameters ) {\n\n\tlet envMapModeDefine = 'ENVMAP_MODE_REFLECTION';\n\n\tif ( parameters.envMap ) {\n\n\t\tswitch ( parameters.envMapMode ) {\n\n\t\t\tcase CubeRefractionMapping:\n\n\t\t\t\tenvMapModeDefine = 'ENVMAP_MODE_REFRACTION';\n\t\t\t\tbreak;\n\n\t\t}\n\n\t}\n\n\treturn envMapModeDefine;\n\n}\n\nfunction generateEnvMapBlendingDefine( parameters ) {\n\n\tlet envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';\n\n\tif ( parameters.envMap ) {\n\n\t\tswitch ( parameters.combine ) {\n\n\t\t\tcase MultiplyOperation:\n\t\t\t\tenvMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';\n\t\t\t\tbreak;\n\n\t\t\tcase MixOperation:\n\t\t\t\tenvMapBlendingDefine = 'ENVMAP_BLENDING_MIX';\n\t\t\t\tbreak;\n\n\t\t\tcase AddOperation:\n\t\t\t\tenvMapBlendingDefine = 'ENVMAP_BLENDING_ADD';\n\t\t\t\tbreak;\n\n\t\t}\n\n\t}\n\n\treturn envMapBlendingDefine;\n\n}\n\nfunction generateCubeUVSize( parameters ) {\n\n\tconst imageHeight = parameters.envMapCubeUVHeight;\n\n\tif ( imageHeight === null ) return null;\n\n\tconst maxMip = Math.log2( imageHeight ) - 2;\n\n\tconst texelHeight = 1.0 / imageHeight;\n\n\tconst texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );\n\n\treturn { texelWidth, texelHeight, maxMip };\n\n}\n\nfunction WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {\n\n\t// TODO Send this event to Three.js DevTools\n\t// console.log( 'WebGLProgram', cacheKey );\n\n\tconst gl = renderer.getContext();\n\n\tconst defines = parameters.defines;\n\n\tlet vertexShader = parameters.vertexShader;\n\tlet fragmentShader = parameters.fragmentShader;\n\n\tconst shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );\n\tconst envMapTypeDefine = generateEnvMapTypeDefine( parameters );\n\tconst envMapModeDefine = generateEnvMapModeDefine( parameters );\n\tconst envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );\n\tconst envMapCubeUVSize = generateCubeUVSize( parameters );\n\n\tconst customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );\n\n\tconst customDefines = generateDefines( defines );\n\n\tconst program = gl.createProgram();\n\n\tlet prefixVertex, prefixFragment;\n\tlet versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\\n' : '';\n\n\tif ( parameters.isRawShaderMaterial ) {\n\n\t\tprefixVertex = [\n\n\t\t\tcustomDefines\n\n\t\t].filter( filterEmptyLine ).join( '\\n' );\n\n\t\tif ( prefixVertex.length > 0 ) {\n\n\t\t\tprefixVertex += '\\n';\n\n\t\t}\n\n\t\tprefixFragment = [\n\n\t\t\tcustomExtensions,\n\t\t\tcustomDefines\n\n\t\t].filter( filterEmptyLine ).join( '\\n' );\n\n\t\tif ( prefixFragment.length > 0 ) {\n\n\t\t\tprefixFragment += '\\n';\n\n\t\t}\n\n\t} else {\n\n\t\tprefixVertex = [\n\n\t\t\tgeneratePrecision( parameters ),\n\n\t\t\t'#define SHADER_NAME ' + parameters.shaderName,\n\n\t\t\tcustomDefines,\n\n\t\t\tparameters.instancing ? '#define USE_INSTANCING' : '',\n\t\t\tparameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',\n\n\t\t\tparameters.useFog && parameters.fog ? '#define USE_FOG' : '',\n\t\t\tparameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',\n\n\t\t\tparameters.map ? '#define USE_MAP' : '',\n\t\t\tparameters.envMap ? '#define USE_ENVMAP' : '',\n\t\t\tparameters.envMap ? '#define ' + envMapModeDefine : '',\n\t\t\tparameters.lightMap ? '#define USE_LIGHTMAP' : '',\n\t\t\tparameters.aoMap ? '#define USE_AOMAP' : '',\n\t\t\tparameters.bumpMap ? '#define USE_BUMPMAP' : '',\n\t\t\tparameters.normalMap ? '#define USE_NORMALMAP' : '',\n\t\t\tparameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',\n\t\t\tparameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',\n\t\t\tparameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',\n\t\t\tparameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',\n\n\t\t\tparameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',\n\t\t\tparameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',\n\t\t\tparameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',\n\n\t\t\tparameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',\n\t\t\tparameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',\n\n\t\t\tparameters.specularMap ? '#define USE_SPECULARMAP' : '',\n\t\t\tparameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',\n\t\t\tparameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',\n\n\t\t\tparameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',\n\t\t\tparameters.metalnessMap ? '#define USE_METALNESSMAP' : '',\n\t\t\tparameters.alphaMap ? '#define USE_ALPHAMAP' : '',\n\n\t\t\tparameters.transmission ? '#define USE_TRANSMISSION' : '',\n\t\t\tparameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',\n\t\t\tparameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',\n\n\t\t\tparameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',\n\t\t\tparameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',\n\n\t\t\t//\n\n\t\t\tparameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',\n\t\t\tparameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',\n\t\t\tparameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',\n\t\t\tparameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',\n\t\t\tparameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',\n\t\t\tparameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',\n\t\t\tparameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',\n\t\t\tparameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',\n\n\t\t\tparameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',\n\t\t\tparameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',\n\n\t\t\tparameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',\n\t\t\tparameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',\n\t\t\tparameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',\n\n\t\t\tparameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',\n\t\t\tparameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',\n\n\t\t\tparameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',\n\t\t\tparameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',\n\n\t\t\tparameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',\n\t\t\tparameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',\n\t\t\tparameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',\n\n\t\t\tparameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',\n\t\t\tparameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',\n\n\t\t\t//\n\n\t\t\tparameters.vertexTangents ? '#define USE_TANGENT' : '',\n\t\t\tparameters.vertexColors ? '#define USE_COLOR' : '',\n\t\t\tparameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',\n\t\t\tparameters.vertexUv1s ? '#define USE_UV1' : '',\n\t\t\tparameters.vertexUv2s ? '#define USE_UV2' : '',\n\t\t\tparameters.vertexUv3s ? '#define USE_UV3' : '',\n\n\t\t\tparameters.pointsUvs ? '#define USE_POINTS_UV' : '',\n\n\t\t\tparameters.flatShading ? '#define FLAT_SHADED' : '',\n\n\t\t\tparameters.skinning ? '#define USE_SKINNING' : '',\n\n\t\t\tparameters.morphTargets ? '#define USE_MORPHTARGETS' : '',\n\t\t\tparameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',\n\t\t\t( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',\n\t\t\t( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',\n\t\t\t( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',\n\t\t\t( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',\n\t\t\tparameters.doubleSided ? '#define DOUBLE_SIDED' : '',\n\t\t\tparameters.flipSided ? '#define FLIP_SIDED' : '',\n\n\t\t\tparameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',\n\t\t\tparameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',\n\n\t\t\tparameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',\n\n\t\t\tparameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',\n\t\t\t( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',\n\n\t\t\t'uniform mat4 modelMatrix;',\n\t\t\t'uniform mat4 modelViewMatrix;',\n\t\t\t'uniform mat4 projectionMatrix;',\n\t\t\t'uniform mat4 viewMatrix;',\n\t\t\t'uniform mat3 normalMatrix;',\n\t\t\t'uniform vec3 cameraPosition;',\n\t\t\t'uniform bool isOrthographic;',\n\n\t\t\t'#ifdef USE_INSTANCING',\n\n\t\t\t'\tattribute mat4 instanceMatrix;',\n\n\t\t\t'#endif',\n\n\t\t\t'#ifdef USE_INSTANCING_COLOR',\n\n\t\t\t'\tattribute vec3 instanceColor;',\n\n\t\t\t'#endif',\n\n\t\t\t'attribute vec3 position;',\n\t\t\t'attribute vec3 normal;',\n\t\t\t'attribute vec2 uv;',\n\n\t\t\t'#ifdef USE_UV1',\n\n\t\t\t'\tattribute vec2 uv1;',\n\n\t\t\t'#endif',\n\n\t\t\t'#ifdef USE_UV2',\n\n\t\t\t'\tattribute vec2 uv2;',\n\n\t\t\t'#endif',\n\n\t\t\t'#ifdef USE_UV3',\n\n\t\t\t'\tattribute vec2 uv3;',\n\n\t\t\t'#endif',\n\n\t\t\t'#ifdef USE_TANGENT',\n\n\t\t\t'\tattribute vec4 tangent;',\n\n\t\t\t'#endif',\n\n\t\t\t'#if defined( USE_COLOR_ALPHA )',\n\n\t\t\t'\tattribute vec4 color;',\n\n\t\t\t'#elif defined( USE_COLOR )',\n\n\t\t\t'\tattribute vec3 color;',\n\n\t\t\t'#endif',\n\n\t\t\t'#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',\n\n\t\t\t'\tattribute vec3 morphTarget0;',\n\t\t\t'\tattribute vec3 morphTarget1;',\n\t\t\t'\tattribute vec3 morphTarget2;',\n\t\t\t'\tattribute vec3 morphTarget3;',\n\n\t\t\t'\t#ifdef USE_MORPHNORMALS',\n\n\t\t\t'\t\tattribute vec3 morphNormal0;',\n\t\t\t'\t\tattribute vec3 morphNormal1;',\n\t\t\t'\t\tattribute vec3 morphNormal2;',\n\t\t\t'\t\tattribute vec3 morphNormal3;',\n\n\t\t\t'\t#else',\n\n\t\t\t'\t\tattribute vec3 morphTarget4;',\n\t\t\t'\t\tattribute vec3 morphTarget5;',\n\t\t\t'\t\tattribute vec3 morphTarget6;',\n\t\t\t'\t\tattribute vec3 morphTarget7;',\n\n\t\t\t'\t#endif',\n\n\t\t\t'#endif',\n\n\t\t\t'#ifdef USE_SKINNING',\n\n\t\t\t'\tattribute vec4 skinIndex;',\n\t\t\t'\tattribute vec4 skinWeight;',\n\n\t\t\t'#endif',\n\n\t\t\t'\\n'\n\n\t\t].filter( filterEmptyLine ).join( '\\n' );\n\n\t\tprefixFragment = [\n\n\t\t\tcustomExtensions,\n\n\t\t\tgeneratePrecision( parameters ),\n\n\t\t\t'#define SHADER_NAME ' + parameters.shaderName,\n\n\t\t\tcustomDefines,\n\n\t\t\tparameters.useFog && parameters.fog ? '#define USE_FOG' : '',\n\t\t\tparameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',\n\n\t\t\tparameters.map ? '#define USE_MAP' : '',\n\t\t\tparameters.matcap ? '#define USE_MATCAP' : '',\n\t\t\tparameters.envMap ? '#define USE_ENVMAP' : '',\n\t\t\tparameters.envMap ? '#define ' + envMapTypeDefine : '',\n\t\t\tparameters.envMap ? '#define ' + envMapModeDefine : '',\n\t\t\tparameters.envMap ? '#define ' + envMapBlendingDefine : '',\n\t\t\tenvMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',\n\t\t\tenvMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',\n\t\t\tenvMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',\n\t\t\tparameters.lightMap ? '#define USE_LIGHTMAP' : '',\n\t\t\tparameters.aoMap ? '#define USE_AOMAP' : '',\n\t\t\tparameters.bumpMap ? '#define USE_BUMPMAP' : '',\n\t\t\tparameters.normalMap ? '#define USE_NORMALMAP' : '',\n\t\t\tparameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',\n\t\t\tparameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',\n\t\t\tparameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',\n\n\t\t\tparameters.clearcoat ? '#define USE_CLEARCOAT' : '',\n\t\t\tparameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',\n\t\t\tparameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',\n\t\t\tparameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',\n\n\t\t\tparameters.iridescence ? '#define USE_IRIDESCENCE' : '',\n\t\t\tparameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',\n\t\t\tparameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',\n\n\t\t\tparameters.specularMap ? '#define USE_SPECULARMAP' : '',\n\t\t\tparameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',\n\t\t\tparameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',\n\n\t\t\tparameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',\n\t\t\tparameters.metalnessMap ? '#define USE_METALNESSMAP' : '',\n\n\t\t\tparameters.alphaMap ? '#define USE_ALPHAMAP' : '',\n\t\t\tparameters.alphaTest ? '#define USE_ALPHATEST' : '',\n\n\t\t\tparameters.sheen ? '#define USE_SHEEN' : '',\n\t\t\tparameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',\n\t\t\tparameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',\n\n\t\t\tparameters.transmission ? '#define USE_TRANSMISSION' : '',\n\t\t\tparameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',\n\t\t\tparameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',\n\n\t\t\tparameters.vertexTangents ? '#define USE_TANGENT' : '',\n\t\t\tparameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',\n\t\t\tparameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',\n\t\t\tparameters.vertexUv1s ? '#define USE_UV1' : '',\n\t\t\tparameters.vertexUv2s ? '#define USE_UV2' : '',\n\t\t\tparameters.vertexUv3s ? '#define USE_UV3' : '',\n\n\t\t\tparameters.pointsUvs ? '#define USE_POINTS_UV' : '',\n\n\t\t\tparameters.gradientMap ? '#define USE_GRADIENTMAP' : '',\n\n\t\t\tparameters.flatShading ? '#define FLAT_SHADED' : '',\n\n\t\t\tparameters.doubleSided ? '#define DOUBLE_SIDED' : '',\n\t\t\tparameters.flipSided ? '#define FLIP_SIDED' : '',\n\n\t\t\tparameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',\n\t\t\tparameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',\n\n\t\t\tparameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',\n\n\t\t\tparameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',\n\n\t\t\tparameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',\n\t\t\t( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',\n\n\t\t\t'uniform mat4 viewMatrix;',\n\t\t\t'uniform vec3 cameraPosition;',\n\t\t\t'uniform bool isOrthographic;',\n\n\t\t\t( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',\n\t\t\t( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below\n\t\t\t( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',\n\n\t\t\tparameters.dithering ? '#define DITHERING' : '',\n\t\t\tparameters.opaque ? '#define OPAQUE' : '',\n\n\t\t\tShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below\n\t\t\tgetTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),\n\n\t\t\tparameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',\n\n\t\t\t'\\n'\n\n\t\t].filter( filterEmptyLine ).join( '\\n' );\n\n\t}\n\n\tvertexShader = resolveIncludes( vertexShader );\n\tvertexShader = replaceLightNums( vertexShader, parameters );\n\tvertexShader = replaceClippingPlaneNums( vertexShader, parameters );\n\n\tfragmentShader = resolveIncludes( fragmentShader );\n\tfragmentShader = replaceLightNums( fragmentShader, parameters );\n\tfragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );\n\n\tvertexShader = unrollLoops( vertexShader );\n\tfragmentShader = unrollLoops( fragmentShader );\n\n\tif ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {\n\n\t\t// GLSL 3.0 conversion for built-in materials and ShaderMaterial\n\n\t\tversionString = '#version 300 es\\n';\n\n\t\tprefixVertex = [\n\t\t\t'precision mediump sampler2DArray;',\n\t\t\t'#define attribute in',\n\t\t\t'#define varying out',\n\t\t\t'#define texture2D texture'\n\t\t].join( '\\n' ) + '\\n' + prefixVertex;\n\n\t\tprefixFragment = [\n\t\t\t'#define varying in',\n\t\t\t( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',\n\t\t\t( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',\n\t\t\t'#define gl_FragDepthEXT gl_FragDepth',\n\t\t\t'#define texture2D texture',\n\t\t\t'#define textureCube texture',\n\t\t\t'#define texture2DProj textureProj',\n\t\t\t'#define texture2DLodEXT textureLod',\n\t\t\t'#define texture2DProjLodEXT textureProjLod',\n\t\t\t'#define textureCubeLodEXT textureLod',\n\t\t\t'#define texture2DGradEXT textureGrad',\n\t\t\t'#define texture2DProjGradEXT textureProjGrad',\n\t\t\t'#define textureCubeGradEXT textureGrad'\n\t\t].join( '\\n' ) + '\\n' + prefixFragment;\n\n\t}\n\n\tconst vertexGlsl = versionString + prefixVertex + vertexShader;\n\tconst fragmentGlsl = versionString + prefixFragment + fragmentShader;\n\n\t// console.log( '*VERTEX*', vertexGlsl );\n\t// console.log( '*FRAGMENT*', fragmentGlsl );\n\n\tconst glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );\n\tconst glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );\n\n\tgl.attachShader( program, glVertexShader );\n\tgl.attachShader( program, glFragmentShader );\n\n\t// Force a particular attribute to index 0.\n\n\tif ( parameters.index0AttributeName !== undefined ) {\n\n\t\tgl.bindAttribLocation( program, 0, parameters.index0AttributeName );\n\n\t} else if ( parameters.morphTargets === true ) {\n\n\t\t// programs with morphTargets displace position out of attribute 0\n\t\tgl.bindAttribLocation( program, 0, 'position' );\n\n\t}\n\n\tgl.linkProgram( program );\n\n\t// check for link errors\n\tif ( renderer.debug.checkShaderErrors ) {\n\n\t\tconst programLog = gl.getProgramInfoLog( program ).trim();\n\t\tconst vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();\n\t\tconst fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();\n\n\t\tlet runnable = true;\n\t\tlet haveDiagnostics = true;\n\n\t\tif ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {\n\n\t\t\trunnable = false;\n\n\t\t\tif ( typeof renderer.debug.onShaderError === 'function' ) {\n\n\t\t\t\trenderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );\n\n\t\t\t} else {\n\n\t\t\t\t// default error reporting\n\n\t\t\t\tconst vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );\n\t\t\t\tconst fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );\n\n\t\t\t\tconsole.error(\n\t\t\t\t\t'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +\n\t\t\t\t\t'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\\n\\n' +\n\t\t\t\t\t'Program Info Log: ' + programLog + '\\n' +\n\t\t\t\t\tvertexErrors + '\\n' +\n\t\t\t\t\tfragmentErrors\n\t\t\t\t);\n\n\t\t\t}\n\n\t\t} else if ( programLog !== '' ) {\n\n\t\t\tconsole.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );\n\n\t\t} else if ( vertexLog === '' || fragmentLog === '' ) {\n\n\t\t\thaveDiagnostics = false;\n\n\t\t}\n\n\t\tif ( haveDiagnostics ) {\n\n\t\t\tthis.diagnostics = {\n\n\t\t\t\trunnable: runnable,\n\n\t\t\t\tprogramLog: programLog,\n\n\t\t\t\tvertexShader: {\n\n\t\t\t\t\tlog: vertexLog,\n\t\t\t\t\tprefix: prefixVertex\n\n\t\t\t\t},\n\n\t\t\t\tfragmentShader: {\n\n\t\t\t\t\tlog: fragmentLog,\n\t\t\t\t\tprefix: prefixFragment\n\n\t\t\t\t}\n\n\t\t\t};\n\n\t\t}\n\n\t}\n\n\t// Clean up\n\n\t// Crashes in iOS9 and iOS10. #18402\n\t// gl.detachShader( program, glVertexShader );\n\t// gl.detachShader( program, glFragmentShader );\n\n\tgl.deleteShader( glVertexShader );\n\tgl.deleteShader( glFragmentShader );\n\n\t// set up caching for uniform locations\n\n\tlet cachedUniforms;\n\n\tthis.getUniforms = function () {\n\n\t\tif ( cachedUniforms === undefined ) {\n\n\t\t\tcachedUniforms = new WebGLUniforms( gl, program );\n\n\t\t}\n\n\t\treturn cachedUniforms;\n\n\t};\n\n\t// set up caching for attribute locations\n\n\tlet cachedAttributes;\n\n\tthis.getAttributes = function () {\n\n\t\tif ( cachedAttributes === undefined ) {\n\n\t\t\tcachedAttributes = fetchAttributeLocations( gl, program );\n\n\t\t}\n\n\t\treturn cachedAttributes;\n\n\t};\n\n\t// free resource\n\n\tthis.destroy = function () {\n\n\t\tbindingStates.releaseStatesOfProgram( this );\n\n\t\tgl.deleteProgram( program );\n\t\tthis.program = undefined;\n\n\t};\n\n\t//\n\n\tthis.name = parameters.shaderName;\n\tthis.id = programIdCount ++;\n\tthis.cacheKey = cacheKey;\n\tthis.usedTimes = 1;\n\tthis.program = program;\n\tthis.vertexShader = glVertexShader;\n\tthis.fragmentShader = glFragmentShader;\n\n\treturn this;\n\n}\n\nlet _id = 0;\n\nclass WebGLShaderCache {\n\n\tconstructor() {\n\n\t\tthis.shaderCache = new Map();\n\t\tthis.materialCache = new Map();\n\n\t}\n\n\tupdate( material ) {\n\n\t\tconst vertexShader = material.vertexShader;\n\t\tconst fragmentShader = material.fragmentShader;\n\n\t\tconst vertexShaderStage = this._getShaderStage( vertexShader );\n\t\tconst fragmentShaderStage = this._getShaderStage( fragmentShader );\n\n\t\tconst materialShaders = this._getShaderCacheForMaterial( material );\n\n\t\tif ( materialShaders.has( vertexShaderStage ) === false ) {\n\n\t\t\tmaterialShaders.add( vertexShaderStage );\n\t\t\tvertexShaderStage.usedTimes ++;\n\n\t\t}\n\n\t\tif ( materialShaders.has( fragmentShaderStage ) === false ) {\n\n\t\t\tmaterialShaders.add( fragmentShaderStage );\n\t\t\tfragmentShaderStage.usedTimes ++;\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tremove( material ) {\n\n\t\tconst materialShaders = this.materialCache.get( material );\n\n\t\tfor ( const shaderStage of materialShaders ) {\n\n\t\t\tshaderStage.usedTimes --;\n\n\t\t\tif ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );\n\n\t\t}\n\n\t\tthis.materialCache.delete( material );\n\n\t\treturn this;\n\n\t}\n\n\tgetVertexShaderID( material ) {\n\n\t\treturn this._getShaderStage( material.vertexShader ).id;\n\n\t}\n\n\tgetFragmentShaderID( material ) {\n\n\t\treturn this._getShaderStage( material.fragmentShader ).id;\n\n\t}\n\n\tdispose() {\n\n\t\tthis.shaderCache.clear();\n\t\tthis.materialCache.clear();\n\n\t}\n\n\t_getShaderCacheForMaterial( material ) {\n\n\t\tconst cache = this.materialCache;\n\t\tlet set = cache.get( material );\n\n\t\tif ( set === undefined ) {\n\n\t\t\tset = new Set();\n\t\t\tcache.set( material, set );\n\n\t\t}\n\n\t\treturn set;\n\n\t}\n\n\t_getShaderStage( code ) {\n\n\t\tconst cache = this.shaderCache;\n\t\tlet stage = cache.get( code );\n\n\t\tif ( stage === undefined ) {\n\n\t\t\tstage = new WebGLShaderStage( code );\n\t\t\tcache.set( code, stage );\n\n\t\t}\n\n\t\treturn stage;\n\n\t}\n\n}\n\nclass WebGLShaderStage {\n\n\tconstructor( code ) {\n\n\t\tthis.id = _id ++;\n\n\t\tthis.code = code;\n\t\tthis.usedTimes = 0;\n\n\t}\n\n}\n\nfunction WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {\n\n\tconst _programLayers = new Layers();\n\tconst _customShaders = new WebGLShaderCache();\n\tconst programs = [];\n\n\tconst IS_WEBGL2 = capabilities.isWebGL2;\n\tconst logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;\n\tconst SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;\n\n\tlet precision = capabilities.precision;\n\n\tconst shaderIDs = {\n\t\tMeshDepthMaterial: 'depth',\n\t\tMeshDistanceMaterial: 'distanceRGBA',\n\t\tMeshNormalMaterial: 'normal',\n\t\tMeshBasicMaterial: 'basic',\n\t\tMeshLambertMaterial: 'lambert',\n\t\tMeshPhongMaterial: 'phong',\n\t\tMeshToonMaterial: 'toon',\n\t\tMeshStandardMaterial: 'physical',\n\t\tMeshPhysicalMaterial: 'physical',\n\t\tMeshMatcapMaterial: 'matcap',\n\t\tLineBasicMaterial: 'basic',\n\t\tLineDashedMaterial: 'dashed',\n\t\tPointsMaterial: 'points',\n\t\tShadowMaterial: 'shadow',\n\t\tSpriteMaterial: 'sprite'\n\t};\n\n\tfunction getChannel( value ) {\n\n\t\tif ( value === 1 ) return 'uv1';\n\t\tif ( value === 2 ) return 'uv2';\n\t\tif ( value === 3 ) return 'uv3';\n\n\t\treturn 'uv';\n\n\t}\n\n\tfunction getParameters( material, lights, shadows, scene, object ) {\n\n\t\tconst fog = scene.fog;\n\t\tconst geometry = object.geometry;\n\t\tconst environment = material.isMeshStandardMaterial ? scene.environment : null;\n\n\t\tconst envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );\n\t\tconst envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;\n\n\t\tconst shaderID = shaderIDs[ material.type ];\n\n\t\t// heuristics to create shader parameters according to lights in the scene\n\t\t// (not to blow over maxLights budget)\n\n\t\tif ( material.precision !== null ) {\n\n\t\t\tprecision = capabilities.getMaxPrecision( material.precision );\n\n\t\t\tif ( precision !== material.precision ) {\n\n\t\t\t\tconsole.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );\n\n\t\t\t}\n\n\t\t}\n\n\t\t//\n\n\t\tconst morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;\n\t\tconst morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;\n\n\t\tlet morphTextureStride = 0;\n\n\t\tif ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;\n\t\tif ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;\n\t\tif ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;\n\n\t\t//\n\n\t\tlet vertexShader, fragmentShader;\n\t\tlet customVertexShaderID, customFragmentShaderID;\n\n\t\tif ( shaderID ) {\n\n\t\t\tconst shader = ShaderLib[ shaderID ];\n\n\t\t\tvertexShader = shader.vertexShader;\n\t\t\tfragmentShader = shader.fragmentShader;\n\n\t\t} else {\n\n\t\t\tvertexShader = material.vertexShader;\n\t\t\tfragmentShader = material.fragmentShader;\n\n\t\t\t_customShaders.update( material );\n\n\t\t\tcustomVertexShaderID = _customShaders.getVertexShaderID( material );\n\t\t\tcustomFragmentShaderID = _customShaders.getFragmentShaderID( material );\n\n\t\t}\n\n\t\tconst currentRenderTarget = renderer.getRenderTarget();\n\n\t\tconst IS_INSTANCEDMESH = object.isInstancedMesh === true;\n\n\t\tconst HAS_MAP = !! material.map;\n\t\tconst HAS_MATCAP = !! material.matcap;\n\t\tconst HAS_ENVMAP = !! envMap;\n\t\tconst HAS_AOMAP = !! material.aoMap;\n\t\tconst HAS_LIGHTMAP = !! material.lightMap;\n\t\tconst HAS_BUMPMAP = !! material.bumpMap;\n\t\tconst HAS_NORMALMAP = !! material.normalMap;\n\t\tconst HAS_DISPLACEMENTMAP = !! material.displacementMap;\n\t\tconst HAS_EMISSIVEMAP = !! material.emissiveMap;\n\n\t\tconst HAS_METALNESSMAP = !! material.metalnessMap;\n\t\tconst HAS_ROUGHNESSMAP = !! material.roughnessMap;\n\n\t\tconst HAS_CLEARCOAT = material.clearcoat > 0;\n\t\tconst HAS_IRIDESCENCE = material.iridescence > 0;\n\t\tconst HAS_SHEEN = material.sheen > 0;\n\t\tconst HAS_TRANSMISSION = material.transmission > 0;\n\n\t\tconst HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;\n\t\tconst HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;\n\t\tconst HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;\n\n\t\tconst HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;\n\t\tconst HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;\n\n\t\tconst HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;\n\t\tconst HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;\n\n\t\tconst HAS_SPECULARMAP = !! material.specularMap;\n\t\tconst HAS_SPECULAR_COLORMAP = !! material.specularColorMap;\n\t\tconst HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;\n\n\t\tconst HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;\n\t\tconst HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;\n\n\t\tconst HAS_GRADIENTMAP = !! material.gradientMap;\n\n\t\tconst HAS_ALPHAMAP = !! material.alphaMap;\n\n\t\tconst HAS_ALPHATEST = material.alphaTest > 0;\n\n\t\tconst HAS_EXTENSIONS = !! material.extensions;\n\n\t\tconst HAS_ATTRIBUTE_UV1 = !! geometry.attributes.uv1;\n\t\tconst HAS_ATTRIBUTE_UV2 = !! geometry.attributes.uv2;\n\t\tconst HAS_ATTRIBUTE_UV3 = !! geometry.attributes.uv3;\n\n\t\tconst parameters = {\n\n\t\t\tisWebGL2: IS_WEBGL2,\n\n\t\t\tshaderID: shaderID,\n\t\t\tshaderName: material.type,\n\n\t\t\tvertexShader: vertexShader,\n\t\t\tfragmentShader: fragmentShader,\n\t\t\tdefines: material.defines,\n\n\t\t\tcustomVertexShaderID: customVertexShaderID,\n\t\t\tcustomFragmentShaderID: customFragmentShaderID,\n\n\t\t\tisRawShaderMaterial: material.isRawShaderMaterial === true,\n\t\t\tglslVersion: material.glslVersion,\n\n\t\t\tprecision: precision,\n\n\t\t\tinstancing: IS_INSTANCEDMESH,\n\t\t\tinstancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,\n\n\t\t\tsupportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,\n\t\t\toutputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),\n\n\t\t\tmap: HAS_MAP,\n\t\t\tmatcap: HAS_MATCAP,\n\t\t\tenvMap: HAS_ENVMAP,\n\t\t\tenvMapMode: HAS_ENVMAP && envMap.mapping,\n\t\t\tenvMapCubeUVHeight: envMapCubeUVHeight,\n\t\t\taoMap: HAS_AOMAP,\n\t\t\tlightMap: HAS_LIGHTMAP,\n\t\t\tbumpMap: HAS_BUMPMAP,\n\t\t\tnormalMap: HAS_NORMALMAP,\n\t\t\tdisplacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,\n\t\t\temissiveMap: HAS_EMISSIVEMAP,\n\n\t\t\tnormalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,\n\t\t\tnormalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,\n\n\t\t\tmetalnessMap: HAS_METALNESSMAP,\n\t\t\troughnessMap: HAS_ROUGHNESSMAP,\n\n\t\t\tclearcoat: HAS_CLEARCOAT,\n\t\t\tclearcoatMap: HAS_CLEARCOATMAP,\n\t\t\tclearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,\n\t\t\tclearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,\n\n\t\t\tiridescence: HAS_IRIDESCENCE,\n\t\t\tiridescenceMap: HAS_IRIDESCENCEMAP,\n\t\t\tiridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,\n\n\t\t\tsheen: HAS_SHEEN,\n\t\t\tsheenColorMap: HAS_SHEEN_COLORMAP,\n\t\t\tsheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,\n\n\t\t\tspecularMap: HAS_SPECULARMAP,\n\t\t\tspecularColorMap: HAS_SPECULAR_COLORMAP,\n\t\t\tspecularIntensityMap: HAS_SPECULAR_INTENSITYMAP,\n\n\t\t\ttransmission: HAS_TRANSMISSION,\n\t\t\ttransmissionMap: HAS_TRANSMISSIONMAP,\n\t\t\tthicknessMap: HAS_THICKNESSMAP,\n\n\t\t\tgradientMap: HAS_GRADIENTMAP,\n\n\t\t\topaque: material.transparent === false && material.blending === NormalBlending,\n\n\t\t\talphaMap: HAS_ALPHAMAP,\n\t\t\talphaTest: HAS_ALPHATEST,\n\n\t\t\tcombine: material.combine,\n\n\t\t\t//\n\n\t\t\tmapUv: HAS_MAP && getChannel( material.map.channel ),\n\t\t\taoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),\n\t\t\tlightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),\n\t\t\tbumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),\n\t\t\tnormalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),\n\t\t\tdisplacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),\n\t\t\temissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),\n\n\t\t\tmetalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),\n\t\t\troughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),\n\n\t\t\tclearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),\n\t\t\tclearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),\n\t\t\tclearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),\n\n\t\t\tiridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),\n\t\t\tiridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),\n\n\t\t\tsheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),\n\t\t\tsheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),\n\n\t\t\tspecularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),\n\t\t\tspecularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),\n\t\t\tspecularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),\n\n\t\t\ttransmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),\n\t\t\tthicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),\n\n\t\t\talphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),\n\n\t\t\t//\n\n\t\t\tvertexTangents: HAS_NORMALMAP && !! geometry.attributes.tangent,\n\t\t\tvertexColors: material.vertexColors,\n\t\t\tvertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,\n\t\t\tvertexUv1s: HAS_ATTRIBUTE_UV1,\n\t\t\tvertexUv2s: HAS_ATTRIBUTE_UV2,\n\t\t\tvertexUv3s: HAS_ATTRIBUTE_UV3,\n\n\t\t\tpointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),\n\n\t\t\tfog: !! fog,\n\t\t\tuseFog: material.fog === true,\n\t\t\tfogExp2: ( fog && fog.isFogExp2 ),\n\n\t\t\tflatShading: material.flatShading === true,\n\n\t\t\tsizeAttenuation: material.sizeAttenuation === true,\n\t\t\tlogarithmicDepthBuffer: logarithmicDepthBuffer,\n\n\t\t\tskinning: object.isSkinnedMesh === true,\n\n\t\t\tmorphTargets: geometry.morphAttributes.position !== undefined,\n\t\t\tmorphNormals: geometry.morphAttributes.normal !== undefined,\n\t\t\tmorphColors: geometry.morphAttributes.color !== undefined,\n\t\t\tmorphTargetsCount: morphTargetsCount,\n\t\t\tmorphTextureStride: morphTextureStride,\n\n\t\t\tnumDirLights: lights.directional.length,\n\t\t\tnumPointLights: lights.point.length,\n\t\t\tnumSpotLights: lights.spot.length,\n\t\t\tnumSpotLightMaps: lights.spotLightMap.length,\n\t\t\tnumRectAreaLights: lights.rectArea.length,\n\t\t\tnumHemiLights: lights.hemi.length,\n\n\t\t\tnumDirLightShadows: lights.directionalShadowMap.length,\n\t\t\tnumPointLightShadows: lights.pointShadowMap.length,\n\t\t\tnumSpotLightShadows: lights.spotShadowMap.length,\n\t\t\tnumSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,\n\n\t\t\tnumClippingPlanes: clipping.numPlanes,\n\t\t\tnumClipIntersection: clipping.numIntersection,\n\n\t\t\tdithering: material.dithering,\n\n\t\t\tshadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,\n\t\t\tshadowMapType: renderer.shadowMap.type,\n\n\t\t\ttoneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,\n\t\t\tuseLegacyLights: renderer.useLegacyLights,\n\n\t\t\tpremultipliedAlpha: material.premultipliedAlpha,\n\n\t\t\tdoubleSided: material.side === DoubleSide,\n\t\t\tflipSided: material.side === BackSide,\n\n\t\t\tuseDepthPacking: material.depthPacking >= 0,\n\t\t\tdepthPacking: material.depthPacking || 0,\n\n\t\t\tindex0AttributeName: material.index0AttributeName,\n\n\t\t\textensionDerivatives: HAS_EXTENSIONS && material.extensions.derivatives === true,\n\t\t\textensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true,\n\t\t\textensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true,\n\t\t\textensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true,\n\n\t\t\trendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ),\n\t\t\trendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ),\n\t\t\trendererExtensionShaderTextureLod: IS_WEBGL2 || extensions.has( 'EXT_shader_texture_lod' ),\n\n\t\t\tcustomProgramCacheKey: material.customProgramCacheKey()\n\n\t\t};\n\n\t\treturn parameters;\n\n\t}\n\n\tfunction getProgramCacheKey( parameters ) {\n\n\t\tconst array = [];\n\n\t\tif ( parameters.shaderID ) {\n\n\t\t\tarray.push( parameters.shaderID );\n\n\t\t} else {\n\n\t\t\tarray.push( parameters.customVertexShaderID );\n\t\t\tarray.push( parameters.customFragmentShaderID );\n\n\t\t}\n\n\t\tif ( parameters.defines !== undefined ) {\n\n\t\t\tfor ( const name in parameters.defines ) {\n\n\t\t\t\tarray.push( name );\n\t\t\t\tarray.push( parameters.defines[ name ] );\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( parameters.isRawShaderMaterial === false ) {\n\n\t\t\tgetProgramCacheKeyParameters( array, parameters );\n\t\t\tgetProgramCacheKeyBooleans( array, parameters );\n\t\t\tarray.push( renderer.outputColorSpace );\n\n\t\t}\n\n\t\tarray.push( parameters.customProgramCacheKey );\n\n\t\treturn array.join();\n\n\t}\n\n\tfunction getProgramCacheKeyParameters( array, parameters ) {\n\n\t\tarray.push( parameters.precision );\n\t\tarray.push( parameters.outputColorSpace );\n\t\tarray.push( parameters.envMapMode );\n\t\tarray.push( parameters.envMapCubeUVHeight );\n\t\tarray.push( parameters.mapUv );\n\t\tarray.push( parameters.alphaMapUv );\n\t\tarray.push( parameters.lightMapUv );\n\t\tarray.push( parameters.aoMapUv );\n\t\tarray.push( parameters.bumpMapUv );\n\t\tarray.push( parameters.normalMapUv );\n\t\tarray.push( parameters.displacementMapUv );\n\t\tarray.push( parameters.emissiveMapUv );\n\t\tarray.push( parameters.metalnessMapUv );\n\t\tarray.push( parameters.roughnessMapUv );\n\t\tarray.push( parameters.clearcoatMapUv );\n\t\tarray.push( parameters.clearcoatNormalMapUv );\n\t\tarray.push( parameters.clearcoatRoughnessMapUv );\n\t\tarray.push( parameters.iridescenceMapUv );\n\t\tarray.push( parameters.iridescenceThicknessMapUv );\n\t\tarray.push( parameters.sheenColorMapUv );\n\t\tarray.push( parameters.sheenRoughnessMapUv );\n\t\tarray.push( parameters.specularMapUv );\n\t\tarray.push( parameters.specularColorMapUv );\n\t\tarray.push( parameters.specularIntensityMapUv );\n\t\tarray.push( parameters.transmissionMapUv );\n\t\tarray.push( parameters.thicknessMapUv );\n\t\tarray.push( parameters.combine );\n\t\tarray.push( parameters.fogExp2 );\n\t\tarray.push( parameters.sizeAttenuation );\n\t\tarray.push( parameters.morphTargetsCount );\n\t\tarray.push( parameters.morphAttributeCount );\n\t\tarray.push( parameters.numDirLights );\n\t\tarray.push( parameters.numPointLights );\n\t\tarray.push( parameters.numSpotLights );\n\t\tarray.push( parameters.numSpotLightMaps );\n\t\tarray.push( parameters.numHemiLights );\n\t\tarray.push( parameters.numRectAreaLights );\n\t\tarray.push( parameters.numDirLightShadows );\n\t\tarray.push( parameters.numPointLightShadows );\n\t\tarray.push( parameters.numSpotLightShadows );\n\t\tarray.push( parameters.numSpotLightShadowsWithMaps );\n\t\tarray.push( parameters.shadowMapType );\n\t\tarray.push( parameters.toneMapping );\n\t\tarray.push( parameters.numClippingPlanes );\n\t\tarray.push( parameters.numClipIntersection );\n\t\tarray.push( parameters.depthPacking );\n\n\t}\n\n\tfunction getProgramCacheKeyBooleans( array, parameters ) {\n\n\t\t_programLayers.disableAll();\n\n\t\tif ( parameters.isWebGL2 )\n\t\t\t_programLayers.enable( 0 );\n\t\tif ( parameters.supportsVertexTextures )\n\t\t\t_programLayers.enable( 1 );\n\t\tif ( parameters.instancing )\n\t\t\t_programLayers.enable( 2 );\n\t\tif ( parameters.instancingColor )\n\t\t\t_programLayers.enable( 3 );\n\t\tif ( parameters.matcap )\n\t\t\t_programLayers.enable( 4 );\n\t\tif ( parameters.envMap )\n\t\t\t_programLayers.enable( 5 );\n\t\tif ( parameters.normalMapObjectSpace )\n\t\t\t_programLayers.enable( 6 );\n\t\tif ( parameters.normalMapTangentSpace )\n\t\t\t_programLayers.enable( 7 );\n\t\tif ( parameters.clearcoat )\n\t\t\t_programLayers.enable( 8 );\n\t\tif ( parameters.iridescence )\n\t\t\t_programLayers.enable( 9 );\n\t\tif ( parameters.alphaTest )\n\t\t\t_programLayers.enable( 10 );\n\t\tif ( parameters.vertexColors )\n\t\t\t_programLayers.enable( 11 );\n\t\tif ( parameters.vertexAlphas )\n\t\t\t_programLayers.enable( 12 );\n\t\tif ( parameters.vertexUv1s )\n\t\t\t_programLayers.enable( 13 );\n\t\tif ( parameters.vertexUv2s )\n\t\t\t_programLayers.enable( 14 );\n\t\tif ( parameters.vertexUv3s )\n\t\t\t_programLayers.enable( 15 );\n\t\tif ( parameters.vertexTangents )\n\t\t\t_programLayers.enable( 16 );\n\n\t\tarray.push( _programLayers.mask );\n\t\t_programLayers.disableAll();\n\n\t\tif ( parameters.fog )\n\t\t\t_programLayers.enable( 0 );\n\t\tif ( parameters.useFog )\n\t\t\t_programLayers.enable( 1 );\n\t\tif ( parameters.flatShading )\n\t\t\t_programLayers.enable( 2 );\n\t\tif ( parameters.logarithmicDepthBuffer )\n\t\t\t_programLayers.enable( 3 );\n\t\tif ( parameters.skinning )\n\t\t\t_programLayers.enable( 4 );\n\t\tif ( parameters.morphTargets )\n\t\t\t_programLayers.enable( 5 );\n\t\tif ( parameters.morphNormals )\n\t\t\t_programLayers.enable( 6 );\n\t\tif ( parameters.morphColors )\n\t\t\t_programLayers.enable( 7 );\n\t\tif ( parameters.premultipliedAlpha )\n\t\t\t_programLayers.enable( 8 );\n\t\tif ( parameters.shadowMapEnabled )\n\t\t\t_programLayers.enable( 9 );\n\t\tif ( parameters.useLegacyLights )\n\t\t\t_programLayers.enable( 10 );\n\t\tif ( parameters.doubleSided )\n\t\t\t_programLayers.enable( 11 );\n\t\tif ( parameters.flipSided )\n\t\t\t_programLayers.enable( 12 );\n\t\tif ( parameters.useDepthPacking )\n\t\t\t_programLayers.enable( 13 );\n\t\tif ( parameters.dithering )\n\t\t\t_programLayers.enable( 14 );\n\t\tif ( parameters.transmission )\n\t\t\t_programLayers.enable( 15 );\n\t\tif ( parameters.sheen )\n\t\t\t_programLayers.enable( 16 );\n\t\tif ( parameters.opaque )\n\t\t\t_programLayers.enable( 17 );\n\t\tif ( parameters.pointsUvs )\n\t\t\t_programLayers.enable( 18 );\n\n\t\tarray.push( _programLayers.mask );\n\n\t}\n\n\tfunction getUniforms( material ) {\n\n\t\tconst shaderID = shaderIDs[ material.type ];\n\t\tlet uniforms;\n\n\t\tif ( shaderID ) {\n\n\t\t\tconst shader = ShaderLib[ shaderID ];\n\t\t\tuniforms = UniformsUtils.clone( shader.uniforms );\n\n\t\t} else {\n\n\t\t\tuniforms = material.uniforms;\n\n\t\t}\n\n\t\treturn uniforms;\n\n\t}\n\n\tfunction acquireProgram( parameters, cacheKey ) {\n\n\t\tlet program;\n\n\t\t// Check if code has been already compiled\n\t\tfor ( let p = 0, pl = programs.length; p < pl; p ++ ) {\n\n\t\t\tconst preexistingProgram = programs[ p ];\n\n\t\t\tif ( preexistingProgram.cacheKey === cacheKey ) {\n\n\t\t\t\tprogram = preexistingProgram;\n\t\t\t\t++ program.usedTimes;\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( program === undefined ) {\n\n\t\t\tprogram = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );\n\t\t\tprograms.push( program );\n\n\t\t}\n\n\t\treturn program;\n\n\t}\n\n\tfunction releaseProgram( program ) {\n\n\t\tif ( -- program.usedTimes === 0 ) {\n\n\t\t\t// Remove from unordered set\n\t\t\tconst i = programs.indexOf( program );\n\t\t\tprograms[ i ] = programs[ programs.length - 1 ];\n\t\t\tprograms.pop();\n\n\t\t\t// Free WebGL resources\n\t\t\tprogram.destroy();\n\n\t\t}\n\n\t}\n\n\tfunction releaseShaderCache( material ) {\n\n\t\t_customShaders.remove( material );\n\n\t}\n\n\tfunction dispose() {\n\n\t\t_customShaders.dispose();\n\n\t}\n\n\treturn {\n\t\tgetParameters: getParameters,\n\t\tgetProgramCacheKey: getProgramCacheKey,\n\t\tgetUniforms: getUniforms,\n\t\tacquireProgram: acquireProgram,\n\t\treleaseProgram: releaseProgram,\n\t\treleaseShaderCache: releaseShaderCache,\n\t\t// Exposed for resource monitoring & error feedback via renderer.info:\n\t\tprograms: programs,\n\t\tdispose: dispose\n\t};\n\n}\n\nfunction WebGLProperties() {\n\n\tlet properties = new WeakMap();\n\n\tfunction get( object ) {\n\n\t\tlet map = properties.get( object );\n\n\t\tif ( map === undefined ) {\n\n\t\t\tmap = {};\n\t\t\tproperties.set( object, map );\n\n\t\t}\n\n\t\treturn map;\n\n\t}\n\n\tfunction remove( object ) {\n\n\t\tproperties.delete( object );\n\n\t}\n\n\tfunction update( object, key, value ) {\n\n\t\tproperties.get( object )[ key ] = value;\n\n\t}\n\n\tfunction dispose() {\n\n\t\tproperties = new WeakMap();\n\n\t}\n\n\treturn {\n\t\tget: get,\n\t\tremove: remove,\n\t\tupdate: update,\n\t\tdispose: dispose\n\t};\n\n}\n\nfunction painterSortStable( a, b ) {\n\n\tif ( a.groupOrder !== b.groupOrder ) {\n\n\t\treturn a.groupOrder - b.groupOrder;\n\n\t} else if ( a.renderOrder !== b.renderOrder ) {\n\n\t\treturn a.renderOrder - b.renderOrder;\n\n\t} else if ( a.material.id !== b.material.id ) {\n\n\t\treturn a.material.id - b.material.id;\n\n\t} else if ( a.z !== b.z ) {\n\n\t\treturn a.z - b.z;\n\n\t} else {\n\n\t\treturn a.id - b.id;\n\n\t}\n\n}\n\nfunction reversePainterSortStable( a, b ) {\n\n\tif ( a.groupOrder !== b.groupOrder ) {\n\n\t\treturn a.groupOrder - b.groupOrder;\n\n\t} else if ( a.renderOrder !== b.renderOrder ) {\n\n\t\treturn a.renderOrder - b.renderOrder;\n\n\t} else if ( a.z !== b.z ) {\n\n\t\treturn b.z - a.z;\n\n\t} else {\n\n\t\treturn a.id - b.id;\n\n\t}\n\n}\n\n\nfunction WebGLRenderList() {\n\n\tconst renderItems = [];\n\tlet renderItemsIndex = 0;\n\n\tconst opaque = [];\n\tconst transmissive = [];\n\tconst transparent = [];\n\n\tfunction init() {\n\n\t\trenderItemsIndex = 0;\n\n\t\topaque.length = 0;\n\t\ttransmissive.length = 0;\n\t\ttransparent.length = 0;\n\n\t}\n\n\tfunction getNextRenderItem( object, geometry, material, groupOrder, z, group ) {\n\n\t\tlet renderItem = renderItems[ renderItemsIndex ];\n\n\t\tif ( renderItem === undefined ) {\n\n\t\t\trenderItem = {\n\t\t\t\tid: object.id,\n\t\t\t\tobject: object,\n\t\t\t\tgeometry: geometry,\n\t\t\t\tmaterial: material,\n\t\t\t\tgroupOrder: groupOrder,\n\t\t\t\trenderOrder: object.renderOrder,\n\t\t\t\tz: z,\n\t\t\t\tgroup: group\n\t\t\t};\n\n\t\t\trenderItems[ renderItemsIndex ] = renderItem;\n\n\t\t} else {\n\n\t\t\trenderItem.id = object.id;\n\t\t\trenderItem.object = object;\n\t\t\trenderItem.geometry = geometry;\n\t\t\trenderItem.material = material;\n\t\t\trenderItem.groupOrder = groupOrder;\n\t\t\trenderItem.renderOrder = object.renderOrder;\n\t\t\trenderItem.z = z;\n\t\t\trenderItem.group = group;\n\n\t\t}\n\n\t\trenderItemsIndex ++;\n\n\t\treturn renderItem;\n\n\t}\n\n\tfunction push( object, geometry, material, groupOrder, z, group ) {\n\n\t\tconst renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );\n\n\t\tif ( material.transmission > 0.0 ) {\n\n\t\t\ttransmissive.push( renderItem );\n\n\t\t} else if ( material.transparent === true ) {\n\n\t\t\ttransparent.push( renderItem );\n\n\t\t} else {\n\n\t\t\topaque.push( renderItem );\n\n\t\t}\n\n\t}\n\n\tfunction unshift( object, geometry, material, groupOrder, z, group ) {\n\n\t\tconst renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );\n\n\t\tif ( material.transmission > 0.0 ) {\n\n\t\t\ttransmissive.unshift( renderItem );\n\n\t\t} else if ( material.transparent === true ) {\n\n\t\t\ttransparent.unshift( renderItem );\n\n\t\t} else {\n\n\t\t\topaque.unshift( renderItem );\n\n\t\t}\n\n\t}\n\n\tfunction sort( customOpaqueSort, customTransparentSort ) {\n\n\t\tif ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );\n\t\tif ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );\n\t\tif ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );\n\n\t}\n\n\tfunction finish() {\n\n\t\t// Clear references from inactive renderItems in the list\n\n\t\tfor ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {\n\n\t\t\tconst renderItem = renderItems[ i ];\n\n\t\t\tif ( renderItem.id === null ) break;\n\n\t\t\trenderItem.id = null;\n\t\t\trenderItem.object = null;\n\t\t\trenderItem.geometry = null;\n\t\t\trenderItem.material = null;\n\t\t\trenderItem.group = null;\n\n\t\t}\n\n\t}\n\n\treturn {\n\n\t\topaque: opaque,\n\t\ttransmissive: transmissive,\n\t\ttransparent: transparent,\n\n\t\tinit: init,\n\t\tpush: push,\n\t\tunshift: unshift,\n\t\tfinish: finish,\n\n\t\tsort: sort\n\t};\n\n}\n\nfunction WebGLRenderLists() {\n\n\tlet lists = new WeakMap();\n\n\tfunction get( scene, renderCallDepth ) {\n\n\t\tconst listArray = lists.get( scene );\n\t\tlet list;\n\n\t\tif ( listArray === undefined ) {\n\n\t\t\tlist = new WebGLRenderList();\n\t\t\tlists.set( scene, [ list ] );\n\n\t\t} else {\n\n\t\t\tif ( renderCallDepth >= listArray.length ) {\n\n\t\t\t\tlist = new WebGLRenderList();\n\t\t\t\tlistArray.push( list );\n\n\t\t\t} else {\n\n\t\t\t\tlist = listArray[ renderCallDepth ];\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn list;\n\n\t}\n\n\tfunction dispose() {\n\n\t\tlists = new WeakMap();\n\n\t}\n\n\treturn {\n\t\tget: get,\n\t\tdispose: dispose\n\t};\n\n}\n\nfunction UniformsCache() {\n\n\tconst lights = {};\n\n\treturn {\n\n\t\tget: function ( light ) {\n\n\t\t\tif ( lights[ light.id ] !== undefined ) {\n\n\t\t\t\treturn lights[ light.id ];\n\n\t\t\t}\n\n\t\t\tlet uniforms;\n\n\t\t\tswitch ( light.type ) {\n\n\t\t\t\tcase 'DirectionalLight':\n\t\t\t\t\tuniforms = {\n\t\t\t\t\t\tdirection: new Vector3(),\n\t\t\t\t\t\tcolor: new Color()\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'SpotLight':\n\t\t\t\t\tuniforms = {\n\t\t\t\t\t\tposition: new Vector3(),\n\t\t\t\t\t\tdirection: new Vector3(),\n\t\t\t\t\t\tcolor: new Color(),\n\t\t\t\t\t\tdistance: 0,\n\t\t\t\t\t\tconeCos: 0,\n\t\t\t\t\t\tpenumbraCos: 0,\n\t\t\t\t\t\tdecay: 0\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'PointLight':\n\t\t\t\t\tuniforms = {\n\t\t\t\t\t\tposition: new Vector3(),\n\t\t\t\t\t\tcolor: new Color(),\n\t\t\t\t\t\tdistance: 0,\n\t\t\t\t\t\tdecay: 0\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'HemisphereLight':\n\t\t\t\t\tuniforms = {\n\t\t\t\t\t\tdirection: new Vector3(),\n\t\t\t\t\t\tskyColor: new Color(),\n\t\t\t\t\t\tgroundColor: new Color()\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'RectAreaLight':\n\t\t\t\t\tuniforms = {\n\t\t\t\t\t\tcolor: new Color(),\n\t\t\t\t\t\tposition: new Vector3(),\n\t\t\t\t\t\thalfWidth: new Vector3(),\n\t\t\t\t\t\thalfHeight: new Vector3()\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\tlights[ light.id ] = uniforms;\n\n\t\t\treturn uniforms;\n\n\t\t}\n\n\t};\n\n}\n\nfunction ShadowUniformsCache() {\n\n\tconst lights = {};\n\n\treturn {\n\n\t\tget: function ( light ) {\n\n\t\t\tif ( lights[ light.id ] !== undefined ) {\n\n\t\t\t\treturn lights[ light.id ];\n\n\t\t\t}\n\n\t\t\tlet uniforms;\n\n\t\t\tswitch ( light.type ) {\n\n\t\t\t\tcase 'DirectionalLight':\n\t\t\t\t\tuniforms = {\n\t\t\t\t\t\tshadowBias: 0,\n\t\t\t\t\t\tshadowNormalBias: 0,\n\t\t\t\t\t\tshadowRadius: 1,\n\t\t\t\t\t\tshadowMapSize: new Vector2()\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'SpotLight':\n\t\t\t\t\tuniforms = {\n\t\t\t\t\t\tshadowBias: 0,\n\t\t\t\t\t\tshadowNormalBias: 0,\n\t\t\t\t\t\tshadowRadius: 1,\n\t\t\t\t\t\tshadowMapSize: new Vector2()\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'PointLight':\n\t\t\t\t\tuniforms = {\n\t\t\t\t\t\tshadowBias: 0,\n\t\t\t\t\t\tshadowNormalBias: 0,\n\t\t\t\t\t\tshadowRadius: 1,\n\t\t\t\t\t\tshadowMapSize: new Vector2(),\n\t\t\t\t\t\tshadowCameraNear: 1,\n\t\t\t\t\t\tshadowCameraFar: 1000\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\n\t\t\t\t// TODO (abelnation): set RectAreaLight shadow uniforms\n\n\t\t\t}\n\n\t\t\tlights[ light.id ] = uniforms;\n\n\t\t\treturn uniforms;\n\n\t\t}\n\n\t};\n\n}\n\n\n\nlet nextVersion = 0;\n\nfunction shadowCastingAndTexturingLightsFirst( lightA, lightB ) {\n\n\treturn ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );\n\n}\n\nfunction WebGLLights( extensions, capabilities ) {\n\n\tconst cache = new UniformsCache();\n\n\tconst shadowCache = ShadowUniformsCache();\n\n\tconst state = {\n\n\t\tversion: 0,\n\n\t\thash: {\n\t\t\tdirectionalLength: - 1,\n\t\t\tpointLength: - 1,\n\t\t\tspotLength: - 1,\n\t\t\trectAreaLength: - 1,\n\t\t\themiLength: - 1,\n\n\t\t\tnumDirectionalShadows: - 1,\n\t\t\tnumPointShadows: - 1,\n\t\t\tnumSpotShadows: - 1,\n\t\t\tnumSpotMaps: - 1\n\t\t},\n\n\t\tambient: [ 0, 0, 0 ],\n\t\tprobe: [],\n\t\tdirectional: [],\n\t\tdirectionalShadow: [],\n\t\tdirectionalShadowMap: [],\n\t\tdirectionalShadowMatrix: [],\n\t\tspot: [],\n\t\tspotLightMap: [],\n\t\tspotShadow: [],\n\t\tspotShadowMap: [],\n\t\tspotLightMatrix: [],\n\t\trectArea: [],\n\t\trectAreaLTC1: null,\n\t\trectAreaLTC2: null,\n\t\tpoint: [],\n\t\tpointShadow: [],\n\t\tpointShadowMap: [],\n\t\tpointShadowMatrix: [],\n\t\themi: [],\n\t\tnumSpotLightShadowsWithMaps: 0\n\n\t};\n\n\tfor ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );\n\n\tconst vector3 = new Vector3();\n\tconst matrix4 = new Matrix4();\n\tconst matrix42 = new Matrix4();\n\n\tfunction setup( lights, useLegacyLights ) {\n\n\t\tlet r = 0, g = 0, b = 0;\n\n\t\tfor ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );\n\n\t\tlet directionalLength = 0;\n\t\tlet pointLength = 0;\n\t\tlet spotLength = 0;\n\t\tlet rectAreaLength = 0;\n\t\tlet hemiLength = 0;\n\n\t\tlet numDirectionalShadows = 0;\n\t\tlet numPointShadows = 0;\n\t\tlet numSpotShadows = 0;\n\t\tlet numSpotMaps = 0;\n\t\tlet numSpotShadowsWithMaps = 0;\n\n\t\t// ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]\n\t\tlights.sort( shadowCastingAndTexturingLightsFirst );\n\n\t\t// artist-friendly light intensity scaling factor\n\t\tconst scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;\n\n\t\tfor ( let i = 0, l = lights.length; i < l; i ++ ) {\n\n\t\t\tconst light = lights[ i ];\n\n\t\t\tconst color = light.color;\n\t\t\tconst intensity = light.intensity;\n\t\t\tconst distance = light.distance;\n\n\t\t\tconst shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;\n\n\t\t\tif ( light.isAmbientLight ) {\n\n\t\t\t\tr += color.r * intensity * scaleFactor;\n\t\t\t\tg += color.g * intensity * scaleFactor;\n\t\t\t\tb += color.b * intensity * scaleFactor;\n\n\t\t\t} else if ( light.isLightProbe ) {\n\n\t\t\t\tfor ( let j = 0; j < 9; j ++ ) {\n\n\t\t\t\t\tstate.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );\n\n\t\t\t\t}\n\n\t\t\t} else if ( light.isDirectionalLight ) {\n\n\t\t\t\tconst uniforms = cache.get( light );\n\n\t\t\t\tuniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );\n\n\t\t\t\tif ( light.castShadow ) {\n\n\t\t\t\t\tconst shadow = light.shadow;\n\n\t\t\t\t\tconst shadowUniforms = shadowCache.get( light );\n\n\t\t\t\t\tshadowUniforms.shadowBias = shadow.bias;\n\t\t\t\t\tshadowUniforms.shadowNormalBias = shadow.normalBias;\n\t\t\t\t\tshadowUniforms.shadowRadius = shadow.radius;\n\t\t\t\t\tshadowUniforms.shadowMapSize = shadow.mapSize;\n\n\t\t\t\t\tstate.directionalShadow[ directionalLength ] = shadowUniforms;\n\t\t\t\t\tstate.directionalShadowMap[ directionalLength ] = shadowMap;\n\t\t\t\t\tstate.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;\n\n\t\t\t\t\tnumDirectionalShadows ++;\n\n\t\t\t\t}\n\n\t\t\t\tstate.directional[ directionalLength ] = uniforms;\n\n\t\t\t\tdirectionalLength ++;\n\n\t\t\t} else if ( light.isSpotLight ) {\n\n\t\t\t\tconst uniforms = cache.get( light );\n\n\t\t\t\tuniforms.position.setFromMatrixPosition( light.matrixWorld );\n\n\t\t\t\tuniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );\n\t\t\t\tuniforms.distance = distance;\n\n\t\t\t\tuniforms.coneCos = Math.cos( light.angle );\n\t\t\t\tuniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );\n\t\t\t\tuniforms.decay = light.decay;\n\n\t\t\t\tstate.spot[ spotLength ] = uniforms;\n\n\t\t\t\tconst shadow = light.shadow;\n\n\t\t\t\tif ( light.map ) {\n\n\t\t\t\t\tstate.spotLightMap[ numSpotMaps ] = light.map;\n\t\t\t\t\tnumSpotMaps ++;\n\n\t\t\t\t\t// make sure the lightMatrix is up to date\n\t\t\t\t\t// TODO : do it if required only\n\t\t\t\t\tshadow.updateMatrices( light );\n\n\t\t\t\t\tif ( light.castShadow ) numSpotShadowsWithMaps ++;\n\n\t\t\t\t}\n\n\t\t\t\tstate.spotLightMatrix[ spotLength ] = shadow.matrix;\n\n\t\t\t\tif ( light.castShadow ) {\n\n\t\t\t\t\tconst shadowUniforms = shadowCache.get( light );\n\n\t\t\t\t\tshadowUniforms.shadowBias = shadow.bias;\n\t\t\t\t\tshadowUniforms.shadowNormalBias = shadow.normalBias;\n\t\t\t\t\tshadowUniforms.shadowRadius = shadow.radius;\n\t\t\t\t\tshadowUniforms.shadowMapSize = shadow.mapSize;\n\n\t\t\t\t\tstate.spotShadow[ spotLength ] = shadowUniforms;\n\t\t\t\t\tstate.spotShadowMap[ spotLength ] = shadowMap;\n\n\t\t\t\t\tnumSpotShadows ++;\n\n\t\t\t\t}\n\n\t\t\t\tspotLength ++;\n\n\t\t\t} else if ( light.isRectAreaLight ) {\n\n\t\t\t\tconst uniforms = cache.get( light );\n\n\t\t\t\tuniforms.color.copy( color ).multiplyScalar( intensity );\n\n\t\t\t\tuniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );\n\t\t\t\tuniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );\n\n\t\t\t\tstate.rectArea[ rectAreaLength ] = uniforms;\n\n\t\t\t\trectAreaLength ++;\n\n\t\t\t} else if ( light.isPointLight ) {\n\n\t\t\t\tconst uniforms = cache.get( light );\n\n\t\t\t\tuniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );\n\t\t\t\tuniforms.distance = light.distance;\n\t\t\t\tuniforms.decay = light.decay;\n\n\t\t\t\tif ( light.castShadow ) {\n\n\t\t\t\t\tconst shadow = light.shadow;\n\n\t\t\t\t\tconst shadowUniforms = shadowCache.get( light );\n\n\t\t\t\t\tshadowUniforms.shadowBias = shadow.bias;\n\t\t\t\t\tshadowUniforms.shadowNormalBias = shadow.normalBias;\n\t\t\t\t\tshadowUniforms.shadowRadius = shadow.radius;\n\t\t\t\t\tshadowUniforms.shadowMapSize = shadow.mapSize;\n\t\t\t\t\tshadowUniforms.shadowCameraNear = shadow.camera.near;\n\t\t\t\t\tshadowUniforms.shadowCameraFar = shadow.camera.far;\n\n\t\t\t\t\tstate.pointShadow[ pointLength ] = shadowUniforms;\n\t\t\t\t\tstate.pointShadowMap[ pointLength ] = shadowMap;\n\t\t\t\t\tstate.pointShadowMatrix[ pointLength ] = light.shadow.matrix;\n\n\t\t\t\t\tnumPointShadows ++;\n\n\t\t\t\t}\n\n\t\t\t\tstate.point[ pointLength ] = uniforms;\n\n\t\t\t\tpointLength ++;\n\n\t\t\t} else if ( light.isHemisphereLight ) {\n\n\t\t\t\tconst uniforms = cache.get( light );\n\n\t\t\t\tuniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );\n\t\t\t\tuniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );\n\n\t\t\t\tstate.hemi[ hemiLength ] = uniforms;\n\n\t\t\t\themiLength ++;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( rectAreaLength > 0 ) {\n\n\t\t\tif ( capabilities.isWebGL2 ) {\n\n\t\t\t\t// WebGL 2\n\n\t\t\t\tstate.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;\n\t\t\t\tstate.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;\n\n\t\t\t} else {\n\n\t\t\t\t// WebGL 1\n\n\t\t\t\tif ( extensions.has( 'OES_texture_float_linear' ) === true ) {\n\n\t\t\t\t\tstate.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;\n\t\t\t\t\tstate.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;\n\n\t\t\t\t} else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {\n\n\t\t\t\t\tstate.rectAreaLTC1 = UniformsLib.LTC_HALF_1;\n\t\t\t\t\tstate.rectAreaLTC2 = UniformsLib.LTC_HALF_2;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tconsole.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tstate.ambient[ 0 ] = r;\n\t\tstate.ambient[ 1 ] = g;\n\t\tstate.ambient[ 2 ] = b;\n\n\t\tconst hash = state.hash;\n\n\t\tif ( hash.directionalLength !== directionalLength ||\n\t\t\thash.pointLength !== pointLength ||\n\t\t\thash.spotLength !== spotLength ||\n\t\t\thash.rectAreaLength !== rectAreaLength ||\n\t\t\thash.hemiLength !== hemiLength ||\n\t\t\thash.numDirectionalShadows !== numDirectionalShadows ||\n\t\t\thash.numPointShadows !== numPointShadows ||\n\t\t\thash.numSpotShadows !== numSpotShadows ||\n\t\t\thash.numSpotMaps !== numSpotMaps ) {\n\n\t\t\tstate.directional.length = directionalLength;\n\t\t\tstate.spot.length = spotLength;\n\t\t\tstate.rectArea.length = rectAreaLength;\n\t\t\tstate.point.length = pointLength;\n\t\t\tstate.hemi.length = hemiLength;\n\n\t\t\tstate.directionalShadow.length = numDirectionalShadows;\n\t\t\tstate.directionalShadowMap.length = numDirectionalShadows;\n\t\t\tstate.pointShadow.length = numPointShadows;\n\t\t\tstate.pointShadowMap.length = numPointShadows;\n\t\t\tstate.spotShadow.length = numSpotShadows;\n\t\t\tstate.spotShadowMap.length = numSpotShadows;\n\t\t\tstate.directionalShadowMatrix.length = numDirectionalShadows;\n\t\t\tstate.pointShadowMatrix.length = numPointShadows;\n\t\t\tstate.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;\n\t\t\tstate.spotLightMap.length = numSpotMaps;\n\t\t\tstate.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;\n\n\t\t\thash.directionalLength = directionalLength;\n\t\t\thash.pointLength = pointLength;\n\t\t\thash.spotLength = spotLength;\n\t\t\thash.rectAreaLength = rectAreaLength;\n\t\t\thash.hemiLength = hemiLength;\n\n\t\t\thash.numDirectionalShadows = numDirectionalShadows;\n\t\t\thash.numPointShadows = numPointShadows;\n\t\t\thash.numSpotShadows = numSpotShadows;\n\t\t\thash.numSpotMaps = numSpotMaps;\n\n\t\t\tstate.version = nextVersion ++;\n\n\t\t}\n\n\t}\n\n\tfunction setupView( lights, camera ) {\n\n\t\tlet directionalLength = 0;\n\t\tlet pointLength = 0;\n\t\tlet spotLength = 0;\n\t\tlet rectAreaLength = 0;\n\t\tlet hemiLength = 0;\n\n\t\tconst viewMatrix = camera.matrixWorldInverse;\n\n\t\tfor ( let i = 0, l = lights.length; i < l; i ++ ) {\n\n\t\t\tconst light = lights[ i ];\n\n\t\t\tif ( light.isDirectionalLight ) {\n\n\t\t\t\tconst uniforms = state.directional[ directionalLength ];\n\n\t\t\t\tuniforms.direction.setFromMatrixPosition( light.matrixWorld );\n\t\t\t\tvector3.setFromMatrixPosition( light.target.matrixWorld );\n\t\t\t\tuniforms.direction.sub( vector3 );\n\t\t\t\tuniforms.direction.transformDirection( viewMatrix );\n\n\t\t\t\tdirectionalLength ++;\n\n\t\t\t} else if ( light.isSpotLight ) {\n\n\t\t\t\tconst uniforms = state.spot[ spotLength ];\n\n\t\t\t\tuniforms.position.setFromMatrixPosition( light.matrixWorld );\n\t\t\t\tuniforms.position.applyMatrix4( viewMatrix );\n\n\t\t\t\tuniforms.direction.setFromMatrixPosition( light.matrixWorld );\n\t\t\t\tvector3.setFromMatrixPosition( light.target.matrixWorld );\n\t\t\t\tuniforms.direction.sub( vector3 );\n\t\t\t\tuniforms.direction.transformDirection( viewMatrix );\n\n\t\t\t\tspotLength ++;\n\n\t\t\t} else if ( light.isRectAreaLight ) {\n\n\t\t\t\tconst uniforms = state.rectArea[ rectAreaLength ];\n\n\t\t\t\tuniforms.position.setFromMatrixPosition( light.matrixWorld );\n\t\t\t\tuniforms.position.applyMatrix4( viewMatrix );\n\n\t\t\t\t// extract local rotation of light to derive width/height half vectors\n\t\t\t\tmatrix42.identity();\n\t\t\t\tmatrix4.copy( light.matrixWorld );\n\t\t\t\tmatrix4.premultiply( viewMatrix );\n\t\t\t\tmatrix42.extractRotation( matrix4 );\n\n\t\t\t\tuniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );\n\t\t\t\tuniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );\n\n\t\t\t\tuniforms.halfWidth.applyMatrix4( matrix42 );\n\t\t\t\tuniforms.halfHeight.applyMatrix4( matrix42 );\n\n\t\t\t\trectAreaLength ++;\n\n\t\t\t} else if ( light.isPointLight ) {\n\n\t\t\t\tconst uniforms = state.point[ pointLength ];\n\n\t\t\t\tuniforms.position.setFromMatrixPosition( light.matrixWorld );\n\t\t\t\tuniforms.position.applyMatrix4( viewMatrix );\n\n\t\t\t\tpointLength ++;\n\n\t\t\t} else if ( light.isHemisphereLight ) {\n\n\t\t\t\tconst uniforms = state.hemi[ hemiLength ];\n\n\t\t\t\tuniforms.direction.setFromMatrixPosition( light.matrixWorld );\n\t\t\t\tuniforms.direction.transformDirection( viewMatrix );\n\n\t\t\t\themiLength ++;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn {\n\t\tsetup: setup,\n\t\tsetupView: setupView,\n\t\tstate: state\n\t};\n\n}\n\nfunction WebGLRenderState( extensions, capabilities ) {\n\n\tconst lights = new WebGLLights( extensions, capabilities );\n\n\tconst lightsArray = [];\n\tconst shadowsArray = [];\n\n\tfunction init() {\n\n\t\tlightsArray.length = 0;\n\t\tshadowsArray.length = 0;\n\n\t}\n\n\tfunction pushLight( light ) {\n\n\t\tlightsArray.push( light );\n\n\t}\n\n\tfunction pushShadow( shadowLight ) {\n\n\t\tshadowsArray.push( shadowLight );\n\n\t}\n\n\tfunction setupLights( useLegacyLights ) {\n\n\t\tlights.setup( lightsArray, useLegacyLights );\n\n\t}\n\n\tfunction setupLightsView( camera ) {\n\n\t\tlights.setupView( lightsArray, camera );\n\n\t}\n\n\tconst state = {\n\t\tlightsArray: lightsArray,\n\t\tshadowsArray: shadowsArray,\n\n\t\tlights: lights\n\t};\n\n\treturn {\n\t\tinit: init,\n\t\tstate: state,\n\t\tsetupLights: setupLights,\n\t\tsetupLightsView: setupLightsView,\n\n\t\tpushLight: pushLight,\n\t\tpushShadow: pushShadow\n\t};\n\n}\n\nfunction WebGLRenderStates( extensions, capabilities ) {\n\n\tlet renderStates = new WeakMap();\n\n\tfunction get( scene, renderCallDepth = 0 ) {\n\n\t\tconst renderStateArray = renderStates.get( scene );\n\t\tlet renderState;\n\n\t\tif ( renderStateArray === undefined ) {\n\n\t\t\trenderState = new WebGLRenderState( extensions, capabilities );\n\t\t\trenderStates.set( scene, [ renderState ] );\n\n\t\t} else {\n\n\t\t\tif ( renderCallDepth >= renderStateArray.length ) {\n\n\t\t\t\trenderState = new WebGLRenderState( extensions, capabilities );\n\t\t\t\trenderStateArray.push( renderState );\n\n\t\t\t} else {\n\n\t\t\t\trenderState = renderStateArray[ renderCallDepth ];\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn renderState;\n\n\t}\n\n\tfunction dispose() {\n\n\t\trenderStates = new WeakMap();\n\n\t}\n\n\treturn {\n\t\tget: get,\n\t\tdispose: dispose\n\t};\n\n}\n\nclass MeshDepthMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isMeshDepthMaterial = true;\n\n\t\tthis.type = 'MeshDepthMaterial';\n\n\t\tthis.depthPacking = BasicDepthPacking;\n\n\t\tthis.map = null;\n\n\t\tthis.alphaMap = null;\n\n\t\tthis.displacementMap = null;\n\t\tthis.displacementScale = 1;\n\t\tthis.displacementBias = 0;\n\n\t\tthis.wireframe = false;\n\t\tthis.wireframeLinewidth = 1;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.depthPacking = source.depthPacking;\n\n\t\tthis.map = source.map;\n\n\t\tthis.alphaMap = source.alphaMap;\n\n\t\tthis.displacementMap = source.displacementMap;\n\t\tthis.displacementScale = source.displacementScale;\n\t\tthis.displacementBias = source.displacementBias;\n\n\t\tthis.wireframe = source.wireframe;\n\t\tthis.wireframeLinewidth = source.wireframeLinewidth;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass MeshDistanceMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isMeshDistanceMaterial = true;\n\n\t\tthis.type = 'MeshDistanceMaterial';\n\n\t\tthis.map = null;\n\n\t\tthis.alphaMap = null;\n\n\t\tthis.displacementMap = null;\n\t\tthis.displacementScale = 1;\n\t\tthis.displacementBias = 0;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.map = source.map;\n\n\t\tthis.alphaMap = source.alphaMap;\n\n\t\tthis.displacementMap = source.displacementMap;\n\t\tthis.displacementScale = source.displacementScale;\n\t\tthis.displacementBias = source.displacementBias;\n\n\t\treturn this;\n\n\t}\n\n}\n\nconst vertex = \"void main() {\\n\\tgl_Position = vec4( position, 1.0 );\\n}\";\n\nconst fragment = \"uniform sampler2D shadow_pass;\\nuniform vec2 resolution;\\nuniform float radius;\\n#include \\nvoid main() {\\n\\tconst float samples = float( VSM_SAMPLES );\\n\\tfloat mean = 0.0;\\n\\tfloat squared_mean = 0.0;\\n\\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\\n\\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\\n\\tfor ( float i = 0.0; i < samples; i ++ ) {\\n\\t\\tfloat uvOffset = uvStart + i * uvStride;\\n\\t\\t#ifdef HORIZONTAL_PASS\\n\\t\\t\\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\\n\\t\\t\\tmean += distribution.x;\\n\\t\\t\\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\\n\\t\\t#else\\n\\t\\t\\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\\n\\t\\t\\tmean += depth;\\n\\t\\t\\tsquared_mean += depth * depth;\\n\\t\\t#endif\\n\\t}\\n\\tmean = mean / samples;\\n\\tsquared_mean = squared_mean / samples;\\n\\tfloat std_dev = sqrt( squared_mean - mean * mean );\\n\\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\\n}\";\n\nfunction WebGLShadowMap( _renderer, _objects, _capabilities ) {\n\n\tlet _frustum = new Frustum();\n\n\tconst _shadowMapSize = new Vector2(),\n\t\t_viewportSize = new Vector2(),\n\n\t\t_viewport = new Vector4(),\n\n\t\t_depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),\n\t\t_distanceMaterial = new MeshDistanceMaterial(),\n\n\t\t_materialCache = {},\n\n\t\t_maxTextureSize = _capabilities.maxTextureSize;\n\n\tconst shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };\n\n\tconst shadowMaterialVertical = new ShaderMaterial( {\n\t\tdefines: {\n\t\t\tVSM_SAMPLES: 8\n\t\t},\n\t\tuniforms: {\n\t\t\tshadow_pass: { value: null },\n\t\t\tresolution: { value: new Vector2() },\n\t\t\tradius: { value: 4.0 }\n\t\t},\n\n\t\tvertexShader: vertex,\n\t\tfragmentShader: fragment\n\n\t} );\n\n\tconst shadowMaterialHorizontal = shadowMaterialVertical.clone();\n\tshadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;\n\n\tconst fullScreenTri = new BufferGeometry();\n\tfullScreenTri.setAttribute(\n\t\t'position',\n\t\tnew BufferAttribute(\n\t\t\tnew Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),\n\t\t\t3\n\t\t)\n\t);\n\n\tconst fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );\n\n\tconst scope = this;\n\n\tthis.enabled = false;\n\n\tthis.autoUpdate = true;\n\tthis.needsUpdate = false;\n\n\tthis.type = PCFShadowMap;\n\tlet _previousType = this.type;\n\n\tthis.render = function ( lights, scene, camera ) {\n\n\t\tif ( scope.enabled === false ) return;\n\t\tif ( scope.autoUpdate === false && scope.needsUpdate === false ) return;\n\n\t\tif ( lights.length === 0 ) return;\n\n\t\tconst currentRenderTarget = _renderer.getRenderTarget();\n\t\tconst activeCubeFace = _renderer.getActiveCubeFace();\n\t\tconst activeMipmapLevel = _renderer.getActiveMipmapLevel();\n\n\t\tconst _state = _renderer.state;\n\n\t\t// Set GL state for depth map.\n\t\t_state.setBlending( NoBlending );\n\t\t_state.buffers.color.setClear( 1, 1, 1, 1 );\n\t\t_state.buffers.depth.setTest( true );\n\t\t_state.setScissorTest( false );\n\n\t\t// check for shadow map type changes\n\n\t\tconst toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );\n\t\tconst fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );\n\n\t\t// render depth map\n\n\t\tfor ( let i = 0, il = lights.length; i < il; i ++ ) {\n\n\t\t\tconst light = lights[ i ];\n\t\t\tconst shadow = light.shadow;\n\n\t\t\tif ( shadow === undefined ) {\n\n\t\t\t\tconsole.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t\tif ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;\n\n\t\t\t_shadowMapSize.copy( shadow.mapSize );\n\n\t\t\tconst shadowFrameExtents = shadow.getFrameExtents();\n\n\t\t\t_shadowMapSize.multiply( shadowFrameExtents );\n\n\t\t\t_viewportSize.copy( shadow.mapSize );\n\n\t\t\tif ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {\n\n\t\t\t\tif ( _shadowMapSize.x > _maxTextureSize ) {\n\n\t\t\t\t\t_viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );\n\t\t\t\t\t_shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;\n\t\t\t\t\tshadow.mapSize.x = _viewportSize.x;\n\n\t\t\t\t}\n\n\t\t\t\tif ( _shadowMapSize.y > _maxTextureSize ) {\n\n\t\t\t\t\t_viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );\n\t\t\t\t\t_shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;\n\t\t\t\t\tshadow.mapSize.y = _viewportSize.y;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( shadow.map === null || toVSM === true || fromVSM === true ) {\n\n\t\t\t\tconst pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};\n\n\t\t\t\tif ( shadow.map !== null ) {\n\n\t\t\t\t\tshadow.map.dispose();\n\n\t\t\t\t}\n\n\t\t\t\tshadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );\n\t\t\t\tshadow.map.texture.name = light.name + '.shadowMap';\n\n\t\t\t\tshadow.camera.updateProjectionMatrix();\n\n\t\t\t}\n\n\t\t\t_renderer.setRenderTarget( shadow.map );\n\t\t\t_renderer.clear();\n\n\t\t\tconst viewportCount = shadow.getViewportCount();\n\n\t\t\tfor ( let vp = 0; vp < viewportCount; vp ++ ) {\n\n\t\t\t\tconst viewport = shadow.getViewport( vp );\n\n\t\t\t\t_viewport.set(\n\t\t\t\t\t_viewportSize.x * viewport.x,\n\t\t\t\t\t_viewportSize.y * viewport.y,\n\t\t\t\t\t_viewportSize.x * viewport.z,\n\t\t\t\t\t_viewportSize.y * viewport.w\n\t\t\t\t);\n\n\t\t\t\t_state.viewport( _viewport );\n\n\t\t\t\tshadow.updateMatrices( light, vp );\n\n\t\t\t\t_frustum = shadow.getFrustum();\n\n\t\t\t\trenderObject( scene, camera, shadow.camera, light, this.type );\n\n\t\t\t}\n\n\t\t\t// do blur pass for VSM\n\n\t\t\tif ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {\n\n\t\t\t\tVSMPass( shadow, camera );\n\n\t\t\t}\n\n\t\t\tshadow.needsUpdate = false;\n\n\t\t}\n\n\t\t_previousType = this.type;\n\n\t\tscope.needsUpdate = false;\n\n\t\t_renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );\n\n\t};\n\n\tfunction VSMPass( shadow, camera ) {\n\n\t\tconst geometry = _objects.update( fullScreenMesh );\n\n\t\tif ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {\n\n\t\t\tshadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;\n\t\t\tshadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;\n\n\t\t\tshadowMaterialVertical.needsUpdate = true;\n\t\t\tshadowMaterialHorizontal.needsUpdate = true;\n\n\t\t}\n\n\t\tif ( shadow.mapPass === null ) {\n\n\t\t\tshadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );\n\n\t\t}\n\n\t\t// vertical pass\n\n\t\tshadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;\n\t\tshadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;\n\t\tshadowMaterialVertical.uniforms.radius.value = shadow.radius;\n\t\t_renderer.setRenderTarget( shadow.mapPass );\n\t\t_renderer.clear();\n\t\t_renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );\n\n\t\t// horizontal pass\n\n\t\tshadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;\n\t\tshadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;\n\t\tshadowMaterialHorizontal.uniforms.radius.value = shadow.radius;\n\t\t_renderer.setRenderTarget( shadow.map );\n\t\t_renderer.clear();\n\t\t_renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );\n\n\t}\n\n\tfunction getDepthMaterial( object, material, light, type ) {\n\n\t\tlet result = null;\n\n\t\tconst customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;\n\n\t\tif ( customMaterial !== undefined ) {\n\n\t\t\tresult = customMaterial;\n\n\t\t} else {\n\n\t\t\tresult = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;\n\n\t\t\tif ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||\n\t\t\t\t( material.displacementMap && material.displacementScale !== 0 ) ||\n\t\t\t\t( material.alphaMap && material.alphaTest > 0 ) ||\n\t\t\t\t( material.map && material.alphaTest > 0 ) ) {\n\n\t\t\t\t// in this case we need a unique material instance reflecting the\n\t\t\t\t// appropriate state\n\n\t\t\t\tconst keyA = result.uuid, keyB = material.uuid;\n\n\t\t\t\tlet materialsForVariant = _materialCache[ keyA ];\n\n\t\t\t\tif ( materialsForVariant === undefined ) {\n\n\t\t\t\t\tmaterialsForVariant = {};\n\t\t\t\t\t_materialCache[ keyA ] = materialsForVariant;\n\n\t\t\t\t}\n\n\t\t\t\tlet cachedMaterial = materialsForVariant[ keyB ];\n\n\t\t\t\tif ( cachedMaterial === undefined ) {\n\n\t\t\t\t\tcachedMaterial = result.clone();\n\t\t\t\t\tmaterialsForVariant[ keyB ] = cachedMaterial;\n\n\t\t\t\t}\n\n\t\t\t\tresult = cachedMaterial;\n\n\t\t\t}\n\n\t\t}\n\n\t\tresult.visible = material.visible;\n\t\tresult.wireframe = material.wireframe;\n\n\t\tif ( type === VSMShadowMap ) {\n\n\t\t\tresult.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;\n\n\t\t} else {\n\n\t\t\tresult.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];\n\n\t\t}\n\n\t\tresult.alphaMap = material.alphaMap;\n\t\tresult.alphaTest = material.alphaTest;\n\t\tresult.map = material.map;\n\n\t\tresult.clipShadows = material.clipShadows;\n\t\tresult.clippingPlanes = material.clippingPlanes;\n\t\tresult.clipIntersection = material.clipIntersection;\n\n\t\tresult.displacementMap = material.displacementMap;\n\t\tresult.displacementScale = material.displacementScale;\n\t\tresult.displacementBias = material.displacementBias;\n\n\t\tresult.wireframeLinewidth = material.wireframeLinewidth;\n\t\tresult.linewidth = material.linewidth;\n\n\t\tif ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {\n\n\t\t\tconst materialProperties = _renderer.properties.get( result );\n\t\t\tmaterialProperties.light = light;\n\n\t\t}\n\n\t\treturn result;\n\n\t}\n\n\tfunction renderObject( object, camera, shadowCamera, light, type ) {\n\n\t\tif ( object.visible === false ) return;\n\n\t\tconst visible = object.layers.test( camera.layers );\n\n\t\tif ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {\n\n\t\t\tif ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {\n\n\t\t\t\tobject.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );\n\n\t\t\t\tconst geometry = _objects.update( object );\n\t\t\t\tconst material = object.material;\n\n\t\t\t\tif ( Array.isArray( material ) ) {\n\n\t\t\t\t\tconst groups = geometry.groups;\n\n\t\t\t\t\tfor ( let k = 0, kl = groups.length; k < kl; k ++ ) {\n\n\t\t\t\t\t\tconst group = groups[ k ];\n\t\t\t\t\t\tconst groupMaterial = material[ group.materialIndex ];\n\n\t\t\t\t\t\tif ( groupMaterial && groupMaterial.visible ) {\n\n\t\t\t\t\t\t\tconst depthMaterial = getDepthMaterial( object, groupMaterial, light, type );\n\n\t\t\t\t\t\t\t_renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if ( material.visible ) {\n\n\t\t\t\t\tconst depthMaterial = getDepthMaterial( object, material, light, type );\n\n\t\t\t\t\t_renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst children = object.children;\n\n\t\tfor ( let i = 0, l = children.length; i < l; i ++ ) {\n\n\t\t\trenderObject( children[ i ], camera, shadowCamera, light, type );\n\n\t\t}\n\n\t}\n\n}\n\nfunction WebGLState( gl, extensions, capabilities ) {\n\n\tconst isWebGL2 = capabilities.isWebGL2;\n\n\tfunction ColorBuffer() {\n\n\t\tlet locked = false;\n\n\t\tconst color = new Vector4();\n\t\tlet currentColorMask = null;\n\t\tconst currentColorClear = new Vector4( 0, 0, 0, 0 );\n\n\t\treturn {\n\n\t\t\tsetMask: function ( colorMask ) {\n\n\t\t\t\tif ( currentColorMask !== colorMask && ! locked ) {\n\n\t\t\t\t\tgl.colorMask( colorMask, colorMask, colorMask, colorMask );\n\t\t\t\t\tcurrentColorMask = colorMask;\n\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\tsetLocked: function ( lock ) {\n\n\t\t\t\tlocked = lock;\n\n\t\t\t},\n\n\t\t\tsetClear: function ( r, g, b, a, premultipliedAlpha ) {\n\n\t\t\t\tif ( premultipliedAlpha === true ) {\n\n\t\t\t\t\tr *= a; g *= a; b *= a;\n\n\t\t\t\t}\n\n\t\t\t\tcolor.set( r, g, b, a );\n\n\t\t\t\tif ( currentColorClear.equals( color ) === false ) {\n\n\t\t\t\t\tgl.clearColor( r, g, b, a );\n\t\t\t\t\tcurrentColorClear.copy( color );\n\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\treset: function () {\n\n\t\t\t\tlocked = false;\n\n\t\t\t\tcurrentColorMask = null;\n\t\t\t\tcurrentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state\n\n\t\t\t}\n\n\t\t};\n\n\t}\n\n\tfunction DepthBuffer() {\n\n\t\tlet locked = false;\n\n\t\tlet currentDepthMask = null;\n\t\tlet currentDepthFunc = null;\n\t\tlet currentDepthClear = null;\n\n\t\treturn {\n\n\t\t\tsetTest: function ( depthTest ) {\n\n\t\t\t\tif ( depthTest ) {\n\n\t\t\t\t\tenable( gl.DEPTH_TEST );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tdisable( gl.DEPTH_TEST );\n\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\tsetMask: function ( depthMask ) {\n\n\t\t\t\tif ( currentDepthMask !== depthMask && ! locked ) {\n\n\t\t\t\t\tgl.depthMask( depthMask );\n\t\t\t\t\tcurrentDepthMask = depthMask;\n\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\tsetFunc: function ( depthFunc ) {\n\n\t\t\t\tif ( currentDepthFunc !== depthFunc ) {\n\n\t\t\t\t\tswitch ( depthFunc ) {\n\n\t\t\t\t\t\tcase NeverDepth:\n\n\t\t\t\t\t\t\tgl.depthFunc( gl.NEVER );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase AlwaysDepth:\n\n\t\t\t\t\t\t\tgl.depthFunc( gl.ALWAYS );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase LessDepth:\n\n\t\t\t\t\t\t\tgl.depthFunc( gl.LESS );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase LessEqualDepth:\n\n\t\t\t\t\t\t\tgl.depthFunc( gl.LEQUAL );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase EqualDepth:\n\n\t\t\t\t\t\t\tgl.depthFunc( gl.EQUAL );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase GreaterEqualDepth:\n\n\t\t\t\t\t\t\tgl.depthFunc( gl.GEQUAL );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase GreaterDepth:\n\n\t\t\t\t\t\t\tgl.depthFunc( gl.GREATER );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase NotEqualDepth:\n\n\t\t\t\t\t\t\tgl.depthFunc( gl.NOTEQUAL );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tdefault:\n\n\t\t\t\t\t\t\tgl.depthFunc( gl.LEQUAL );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentDepthFunc = depthFunc;\n\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\tsetLocked: function ( lock ) {\n\n\t\t\t\tlocked = lock;\n\n\t\t\t},\n\n\t\t\tsetClear: function ( depth ) {\n\n\t\t\t\tif ( currentDepthClear !== depth ) {\n\n\t\t\t\t\tgl.clearDepth( depth );\n\t\t\t\t\tcurrentDepthClear = depth;\n\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\treset: function () {\n\n\t\t\t\tlocked = false;\n\n\t\t\t\tcurrentDepthMask = null;\n\t\t\t\tcurrentDepthFunc = null;\n\t\t\t\tcurrentDepthClear = null;\n\n\t\t\t}\n\n\t\t};\n\n\t}\n\n\tfunction StencilBuffer() {\n\n\t\tlet locked = false;\n\n\t\tlet currentStencilMask = null;\n\t\tlet currentStencilFunc = null;\n\t\tlet currentStencilRef = null;\n\t\tlet currentStencilFuncMask = null;\n\t\tlet currentStencilFail = null;\n\t\tlet currentStencilZFail = null;\n\t\tlet currentStencilZPass = null;\n\t\tlet currentStencilClear = null;\n\n\t\treturn {\n\n\t\t\tsetTest: function ( stencilTest ) {\n\n\t\t\t\tif ( ! locked ) {\n\n\t\t\t\t\tif ( stencilTest ) {\n\n\t\t\t\t\t\tenable( gl.STENCIL_TEST );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tdisable( gl.STENCIL_TEST );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\tsetMask: function ( stencilMask ) {\n\n\t\t\t\tif ( currentStencilMask !== stencilMask && ! locked ) {\n\n\t\t\t\t\tgl.stencilMask( stencilMask );\n\t\t\t\t\tcurrentStencilMask = stencilMask;\n\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\tsetFunc: function ( stencilFunc, stencilRef, stencilMask ) {\n\n\t\t\t\tif ( currentStencilFunc !== stencilFunc ||\n\t\t\t\t currentStencilRef !== stencilRef ||\n\t\t\t\t currentStencilFuncMask !== stencilMask ) {\n\n\t\t\t\t\tgl.stencilFunc( stencilFunc, stencilRef, stencilMask );\n\n\t\t\t\t\tcurrentStencilFunc = stencilFunc;\n\t\t\t\t\tcurrentStencilRef = stencilRef;\n\t\t\t\t\tcurrentStencilFuncMask = stencilMask;\n\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\tsetOp: function ( stencilFail, stencilZFail, stencilZPass ) {\n\n\t\t\t\tif ( currentStencilFail !== stencilFail ||\n\t\t\t\t currentStencilZFail !== stencilZFail ||\n\t\t\t\t currentStencilZPass !== stencilZPass ) {\n\n\t\t\t\t\tgl.stencilOp( stencilFail, stencilZFail, stencilZPass );\n\n\t\t\t\t\tcurrentStencilFail = stencilFail;\n\t\t\t\t\tcurrentStencilZFail = stencilZFail;\n\t\t\t\t\tcurrentStencilZPass = stencilZPass;\n\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\tsetLocked: function ( lock ) {\n\n\t\t\t\tlocked = lock;\n\n\t\t\t},\n\n\t\t\tsetClear: function ( stencil ) {\n\n\t\t\t\tif ( currentStencilClear !== stencil ) {\n\n\t\t\t\t\tgl.clearStencil( stencil );\n\t\t\t\t\tcurrentStencilClear = stencil;\n\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\treset: function () {\n\n\t\t\t\tlocked = false;\n\n\t\t\t\tcurrentStencilMask = null;\n\t\t\t\tcurrentStencilFunc = null;\n\t\t\t\tcurrentStencilRef = null;\n\t\t\t\tcurrentStencilFuncMask = null;\n\t\t\t\tcurrentStencilFail = null;\n\t\t\t\tcurrentStencilZFail = null;\n\t\t\t\tcurrentStencilZPass = null;\n\t\t\t\tcurrentStencilClear = null;\n\n\t\t\t}\n\n\t\t};\n\n\t}\n\n\t//\n\n\tconst colorBuffer = new ColorBuffer();\n\tconst depthBuffer = new DepthBuffer();\n\tconst stencilBuffer = new StencilBuffer();\n\n\tconst uboBindings = new WeakMap();\n\tconst uboProgramMap = new WeakMap();\n\n\tlet enabledCapabilities = {};\n\n\tlet currentBoundFramebuffers = {};\n\tlet currentDrawbuffers = new WeakMap();\n\tlet defaultDrawbuffers = [];\n\n\tlet currentProgram = null;\n\n\tlet currentBlendingEnabled = false;\n\tlet currentBlending = null;\n\tlet currentBlendEquation = null;\n\tlet currentBlendSrc = null;\n\tlet currentBlendDst = null;\n\tlet currentBlendEquationAlpha = null;\n\tlet currentBlendSrcAlpha = null;\n\tlet currentBlendDstAlpha = null;\n\tlet currentPremultipledAlpha = false;\n\n\tlet currentFlipSided = null;\n\tlet currentCullFace = null;\n\n\tlet currentLineWidth = null;\n\n\tlet currentPolygonOffsetFactor = null;\n\tlet currentPolygonOffsetUnits = null;\n\n\tconst maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );\n\n\tlet lineWidthAvailable = false;\n\tlet version = 0;\n\tconst glVersion = gl.getParameter( gl.VERSION );\n\n\tif ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {\n\n\t\tversion = parseFloat( /^WebGL (\\d)/.exec( glVersion )[ 1 ] );\n\t\tlineWidthAvailable = ( version >= 1.0 );\n\n\t} else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {\n\n\t\tversion = parseFloat( /^OpenGL ES (\\d)/.exec( glVersion )[ 1 ] );\n\t\tlineWidthAvailable = ( version >= 2.0 );\n\n\t}\n\n\tlet currentTextureSlot = null;\n\tlet currentBoundTextures = {};\n\n\tconst scissorParam = gl.getParameter( gl.SCISSOR_BOX );\n\tconst viewportParam = gl.getParameter( gl.VIEWPORT );\n\n\tconst currentScissor = new Vector4().fromArray( scissorParam );\n\tconst currentViewport = new Vector4().fromArray( viewportParam );\n\n\tfunction createTexture( type, target, count, dimensions ) {\n\n\t\tconst data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.\n\t\tconst texture = gl.createTexture();\n\n\t\tgl.bindTexture( type, texture );\n\t\tgl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );\n\t\tgl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );\n\n\t\tfor ( let i = 0; i < count; i ++ ) {\n\n\t\t\tif ( isWebGL2 && ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) ) {\n\n\t\t\t\tgl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );\n\n\t\t\t} else {\n\n\t\t\t\tgl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn texture;\n\n\t}\n\n\tconst emptyTextures = {};\n\temptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );\n\temptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );\n\n\tif ( isWebGL2 ) {\n\n\t\temptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );\n\t\temptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );\n\n\t}\n\n\t// init\n\n\tcolorBuffer.setClear( 0, 0, 0, 1 );\n\tdepthBuffer.setClear( 1 );\n\tstencilBuffer.setClear( 0 );\n\n\tenable( gl.DEPTH_TEST );\n\tdepthBuffer.setFunc( LessEqualDepth );\n\n\tsetFlipSided( false );\n\tsetCullFace( CullFaceBack );\n\tenable( gl.CULL_FACE );\n\n\tsetBlending( NoBlending );\n\n\t//\n\n\tfunction enable( id ) {\n\n\t\tif ( enabledCapabilities[ id ] !== true ) {\n\n\t\t\tgl.enable( id );\n\t\t\tenabledCapabilities[ id ] = true;\n\n\t\t}\n\n\t}\n\n\tfunction disable( id ) {\n\n\t\tif ( enabledCapabilities[ id ] !== false ) {\n\n\t\t\tgl.disable( id );\n\t\t\tenabledCapabilities[ id ] = false;\n\n\t\t}\n\n\t}\n\n\tfunction bindFramebuffer( target, framebuffer ) {\n\n\t\tif ( currentBoundFramebuffers[ target ] !== framebuffer ) {\n\n\t\t\tgl.bindFramebuffer( target, framebuffer );\n\n\t\t\tcurrentBoundFramebuffers[ target ] = framebuffer;\n\n\t\t\tif ( isWebGL2 ) {\n\n\t\t\t\t// gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER\n\n\t\t\t\tif ( target === gl.DRAW_FRAMEBUFFER ) {\n\n\t\t\t\t\tcurrentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;\n\n\t\t\t\t}\n\n\t\t\t\tif ( target === gl.FRAMEBUFFER ) {\n\n\t\t\t\t\tcurrentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn true;\n\n\t\t}\n\n\t\treturn false;\n\n\t}\n\n\tfunction drawBuffers( renderTarget, framebuffer ) {\n\n\t\tlet drawBuffers = defaultDrawbuffers;\n\n\t\tlet needsUpdate = false;\n\n\t\tif ( renderTarget ) {\n\n\t\t\tdrawBuffers = currentDrawbuffers.get( framebuffer );\n\n\t\t\tif ( drawBuffers === undefined ) {\n\n\t\t\t\tdrawBuffers = [];\n\t\t\t\tcurrentDrawbuffers.set( framebuffer, drawBuffers );\n\n\t\t\t}\n\n\t\t\tif ( renderTarget.isWebGLMultipleRenderTargets ) {\n\n\t\t\t\tconst textures = renderTarget.texture;\n\n\t\t\t\tif ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {\n\n\t\t\t\t\tfor ( let i = 0, il = textures.length; i < il; i ++ ) {\n\n\t\t\t\t\t\tdrawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tdrawBuffers.length = textures.length;\n\n\t\t\t\t\tneedsUpdate = true;\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tif ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {\n\n\t\t\t\t\tdrawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0;\n\n\t\t\t\t\tneedsUpdate = true;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tif ( drawBuffers[ 0 ] !== gl.BACK ) {\n\n\t\t\t\tdrawBuffers[ 0 ] = gl.BACK;\n\n\t\t\t\tneedsUpdate = true;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( needsUpdate ) {\n\n\t\t\tif ( capabilities.isWebGL2 ) {\n\n\t\t\t\tgl.drawBuffers( drawBuffers );\n\n\t\t\t} else {\n\n\t\t\t\textensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );\n\n\t\t\t}\n\n\t\t}\n\n\n\t}\n\n\tfunction useProgram( program ) {\n\n\t\tif ( currentProgram !== program ) {\n\n\t\t\tgl.useProgram( program );\n\n\t\t\tcurrentProgram = program;\n\n\t\t\treturn true;\n\n\t\t}\n\n\t\treturn false;\n\n\t}\n\n\tconst equationToGL = {\n\t\t[ AddEquation ]: gl.FUNC_ADD,\n\t\t[ SubtractEquation ]: gl.FUNC_SUBTRACT,\n\t\t[ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT\n\t};\n\n\tif ( isWebGL2 ) {\n\n\t\tequationToGL[ MinEquation ] = gl.MIN;\n\t\tequationToGL[ MaxEquation ] = gl.MAX;\n\n\t} else {\n\n\t\tconst extension = extensions.get( 'EXT_blend_minmax' );\n\n\t\tif ( extension !== null ) {\n\n\t\t\tequationToGL[ MinEquation ] = extension.MIN_EXT;\n\t\t\tequationToGL[ MaxEquation ] = extension.MAX_EXT;\n\n\t\t}\n\n\t}\n\n\tconst factorToGL = {\n\t\t[ ZeroFactor ]: gl.ZERO,\n\t\t[ OneFactor ]: gl.ONE,\n\t\t[ SrcColorFactor ]: gl.SRC_COLOR,\n\t\t[ SrcAlphaFactor ]: gl.SRC_ALPHA,\n\t\t[ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,\n\t\t[ DstColorFactor ]: gl.DST_COLOR,\n\t\t[ DstAlphaFactor ]: gl.DST_ALPHA,\n\t\t[ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,\n\t\t[ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,\n\t\t[ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,\n\t\t[ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA\n\t};\n\n\tfunction setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {\n\n\t\tif ( blending === NoBlending ) {\n\n\t\t\tif ( currentBlendingEnabled === true ) {\n\n\t\t\t\tdisable( gl.BLEND );\n\t\t\t\tcurrentBlendingEnabled = false;\n\n\t\t\t}\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tif ( currentBlendingEnabled === false ) {\n\n\t\t\tenable( gl.BLEND );\n\t\t\tcurrentBlendingEnabled = true;\n\n\t\t}\n\n\t\tif ( blending !== CustomBlending ) {\n\n\t\t\tif ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {\n\n\t\t\t\tif ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {\n\n\t\t\t\t\tgl.blendEquation( gl.FUNC_ADD );\n\n\t\t\t\t\tcurrentBlendEquation = AddEquation;\n\t\t\t\t\tcurrentBlendEquationAlpha = AddEquation;\n\n\t\t\t\t}\n\n\t\t\t\tif ( premultipliedAlpha ) {\n\n\t\t\t\t\tswitch ( blending ) {\n\n\t\t\t\t\t\tcase NormalBlending:\n\t\t\t\t\t\t\tgl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase AdditiveBlending:\n\t\t\t\t\t\t\tgl.blendFunc( gl.ONE, gl.ONE );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase SubtractiveBlending:\n\t\t\t\t\t\t\tgl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase MultiplyBlending:\n\t\t\t\t\t\t\tgl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tconsole.error( 'THREE.WebGLState: Invalid blending: ', blending );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\tswitch ( blending ) {\n\n\t\t\t\t\t\tcase NormalBlending:\n\t\t\t\t\t\t\tgl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase AdditiveBlending:\n\t\t\t\t\t\t\tgl.blendFunc( gl.SRC_ALPHA, gl.ONE );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase SubtractiveBlending:\n\t\t\t\t\t\t\tgl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase MultiplyBlending:\n\t\t\t\t\t\t\tgl.blendFunc( gl.ZERO, gl.SRC_COLOR );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tconsole.error( 'THREE.WebGLState: Invalid blending: ', blending );\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tcurrentBlendSrc = null;\n\t\t\t\tcurrentBlendDst = null;\n\t\t\t\tcurrentBlendSrcAlpha = null;\n\t\t\t\tcurrentBlendDstAlpha = null;\n\n\t\t\t\tcurrentBlending = blending;\n\t\t\t\tcurrentPremultipledAlpha = premultipliedAlpha;\n\n\t\t\t}\n\n\t\t\treturn;\n\n\t\t}\n\n\t\t// custom blending\n\n\t\tblendEquationAlpha = blendEquationAlpha || blendEquation;\n\t\tblendSrcAlpha = blendSrcAlpha || blendSrc;\n\t\tblendDstAlpha = blendDstAlpha || blendDst;\n\n\t\tif ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {\n\n\t\t\tgl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );\n\n\t\t\tcurrentBlendEquation = blendEquation;\n\t\t\tcurrentBlendEquationAlpha = blendEquationAlpha;\n\n\t\t}\n\n\t\tif ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {\n\n\t\t\tgl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );\n\n\t\t\tcurrentBlendSrc = blendSrc;\n\t\t\tcurrentBlendDst = blendDst;\n\t\t\tcurrentBlendSrcAlpha = blendSrcAlpha;\n\t\t\tcurrentBlendDstAlpha = blendDstAlpha;\n\n\t\t}\n\n\t\tcurrentBlending = blending;\n\t\tcurrentPremultipledAlpha = false;\n\n\t}\n\n\tfunction setMaterial( material, frontFaceCW ) {\n\n\t\tmaterial.side === DoubleSide\n\t\t\t? disable( gl.CULL_FACE )\n\t\t\t: enable( gl.CULL_FACE );\n\n\t\tlet flipSided = ( material.side === BackSide );\n\t\tif ( frontFaceCW ) flipSided = ! flipSided;\n\n\t\tsetFlipSided( flipSided );\n\n\t\t( material.blending === NormalBlending && material.transparent === false )\n\t\t\t? setBlending( NoBlending )\n\t\t\t: setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );\n\n\t\tdepthBuffer.setFunc( material.depthFunc );\n\t\tdepthBuffer.setTest( material.depthTest );\n\t\tdepthBuffer.setMask( material.depthWrite );\n\t\tcolorBuffer.setMask( material.colorWrite );\n\n\t\tconst stencilWrite = material.stencilWrite;\n\t\tstencilBuffer.setTest( stencilWrite );\n\t\tif ( stencilWrite ) {\n\n\t\t\tstencilBuffer.setMask( material.stencilWriteMask );\n\t\t\tstencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );\n\t\t\tstencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );\n\n\t\t}\n\n\t\tsetPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );\n\n\t\tmaterial.alphaToCoverage === true\n\t\t\t? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )\n\t\t\t: disable( gl.SAMPLE_ALPHA_TO_COVERAGE );\n\n\t}\n\n\t//\n\n\tfunction setFlipSided( flipSided ) {\n\n\t\tif ( currentFlipSided !== flipSided ) {\n\n\t\t\tif ( flipSided ) {\n\n\t\t\t\tgl.frontFace( gl.CW );\n\n\t\t\t} else {\n\n\t\t\t\tgl.frontFace( gl.CCW );\n\n\t\t\t}\n\n\t\t\tcurrentFlipSided = flipSided;\n\n\t\t}\n\n\t}\n\n\tfunction setCullFace( cullFace ) {\n\n\t\tif ( cullFace !== CullFaceNone ) {\n\n\t\t\tenable( gl.CULL_FACE );\n\n\t\t\tif ( cullFace !== currentCullFace ) {\n\n\t\t\t\tif ( cullFace === CullFaceBack ) {\n\n\t\t\t\t\tgl.cullFace( gl.BACK );\n\n\t\t\t\t} else if ( cullFace === CullFaceFront ) {\n\n\t\t\t\t\tgl.cullFace( gl.FRONT );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tgl.cullFace( gl.FRONT_AND_BACK );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tdisable( gl.CULL_FACE );\n\n\t\t}\n\n\t\tcurrentCullFace = cullFace;\n\n\t}\n\n\tfunction setLineWidth( width ) {\n\n\t\tif ( width !== currentLineWidth ) {\n\n\t\t\tif ( lineWidthAvailable ) gl.lineWidth( width );\n\n\t\t\tcurrentLineWidth = width;\n\n\t\t}\n\n\t}\n\n\tfunction setPolygonOffset( polygonOffset, factor, units ) {\n\n\t\tif ( polygonOffset ) {\n\n\t\t\tenable( gl.POLYGON_OFFSET_FILL );\n\n\t\t\tif ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {\n\n\t\t\t\tgl.polygonOffset( factor, units );\n\n\t\t\t\tcurrentPolygonOffsetFactor = factor;\n\t\t\t\tcurrentPolygonOffsetUnits = units;\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tdisable( gl.POLYGON_OFFSET_FILL );\n\n\t\t}\n\n\t}\n\n\tfunction setScissorTest( scissorTest ) {\n\n\t\tif ( scissorTest ) {\n\n\t\t\tenable( gl.SCISSOR_TEST );\n\n\t\t} else {\n\n\t\t\tdisable( gl.SCISSOR_TEST );\n\n\t\t}\n\n\t}\n\n\t// texture\n\n\tfunction activeTexture( webglSlot ) {\n\n\t\tif ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;\n\n\t\tif ( currentTextureSlot !== webglSlot ) {\n\n\t\t\tgl.activeTexture( webglSlot );\n\t\t\tcurrentTextureSlot = webglSlot;\n\n\t\t}\n\n\t}\n\n\tfunction bindTexture( webglType, webglTexture, webglSlot ) {\n\n\t\tif ( webglSlot === undefined ) {\n\n\t\t\tif ( currentTextureSlot === null ) {\n\n\t\t\t\twebglSlot = gl.TEXTURE0 + maxTextures - 1;\n\n\t\t\t} else {\n\n\t\t\t\twebglSlot = currentTextureSlot;\n\n\t\t\t}\n\n\t\t}\n\n\t\tlet boundTexture = currentBoundTextures[ webglSlot ];\n\n\t\tif ( boundTexture === undefined ) {\n\n\t\t\tboundTexture = { type: undefined, texture: undefined };\n\t\t\tcurrentBoundTextures[ webglSlot ] = boundTexture;\n\n\t\t}\n\n\t\tif ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {\n\n\t\t\tif ( currentTextureSlot !== webglSlot ) {\n\n\t\t\t\tgl.activeTexture( webglSlot );\n\t\t\t\tcurrentTextureSlot = webglSlot;\n\n\t\t\t}\n\n\t\t\tgl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );\n\n\t\t\tboundTexture.type = webglType;\n\t\t\tboundTexture.texture = webglTexture;\n\n\t\t}\n\n\t}\n\n\tfunction unbindTexture() {\n\n\t\tconst boundTexture = currentBoundTextures[ currentTextureSlot ];\n\n\t\tif ( boundTexture !== undefined && boundTexture.type !== undefined ) {\n\n\t\t\tgl.bindTexture( boundTexture.type, null );\n\n\t\t\tboundTexture.type = undefined;\n\t\t\tboundTexture.texture = undefined;\n\n\t\t}\n\n\t}\n\n\tfunction compressedTexImage2D() {\n\n\t\ttry {\n\n\t\t\tgl.compressedTexImage2D.apply( gl, arguments );\n\n\t\t} catch ( error ) {\n\n\t\t\tconsole.error( 'THREE.WebGLState:', error );\n\n\t\t}\n\n\t}\n\n\tfunction compressedTexImage3D() {\n\n\t\ttry {\n\n\t\t\tgl.compressedTexImage3D.apply( gl, arguments );\n\n\t\t} catch ( error ) {\n\n\t\t\tconsole.error( 'THREE.WebGLState:', error );\n\n\t\t}\n\n\t}\n\n\tfunction texSubImage2D() {\n\n\t\ttry {\n\n\t\t\tgl.texSubImage2D.apply( gl, arguments );\n\n\t\t} catch ( error ) {\n\n\t\t\tconsole.error( 'THREE.WebGLState:', error );\n\n\t\t}\n\n\t}\n\n\tfunction texSubImage3D() {\n\n\t\ttry {\n\n\t\t\tgl.texSubImage3D.apply( gl, arguments );\n\n\t\t} catch ( error ) {\n\n\t\t\tconsole.error( 'THREE.WebGLState:', error );\n\n\t\t}\n\n\t}\n\n\tfunction compressedTexSubImage2D() {\n\n\t\ttry {\n\n\t\t\tgl.compressedTexSubImage2D.apply( gl, arguments );\n\n\t\t} catch ( error ) {\n\n\t\t\tconsole.error( 'THREE.WebGLState:', error );\n\n\t\t}\n\n\t}\n\n\tfunction compressedTexSubImage3D() {\n\n\t\ttry {\n\n\t\t\tgl.compressedTexSubImage3D.apply( gl, arguments );\n\n\t\t} catch ( error ) {\n\n\t\t\tconsole.error( 'THREE.WebGLState:', error );\n\n\t\t}\n\n\t}\n\n\tfunction texStorage2D() {\n\n\t\ttry {\n\n\t\t\tgl.texStorage2D.apply( gl, arguments );\n\n\t\t} catch ( error ) {\n\n\t\t\tconsole.error( 'THREE.WebGLState:', error );\n\n\t\t}\n\n\t}\n\n\tfunction texStorage3D() {\n\n\t\ttry {\n\n\t\t\tgl.texStorage3D.apply( gl, arguments );\n\n\t\t} catch ( error ) {\n\n\t\t\tconsole.error( 'THREE.WebGLState:', error );\n\n\t\t}\n\n\t}\n\n\tfunction texImage2D() {\n\n\t\ttry {\n\n\t\t\tgl.texImage2D.apply( gl, arguments );\n\n\t\t} catch ( error ) {\n\n\t\t\tconsole.error( 'THREE.WebGLState:', error );\n\n\t\t}\n\n\t}\n\n\tfunction texImage3D() {\n\n\t\ttry {\n\n\t\t\tgl.texImage3D.apply( gl, arguments );\n\n\t\t} catch ( error ) {\n\n\t\t\tconsole.error( 'THREE.WebGLState:', error );\n\n\t\t}\n\n\t}\n\n\t//\n\n\tfunction scissor( scissor ) {\n\n\t\tif ( currentScissor.equals( scissor ) === false ) {\n\n\t\t\tgl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );\n\t\t\tcurrentScissor.copy( scissor );\n\n\t\t}\n\n\t}\n\n\tfunction viewport( viewport ) {\n\n\t\tif ( currentViewport.equals( viewport ) === false ) {\n\n\t\t\tgl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );\n\t\t\tcurrentViewport.copy( viewport );\n\n\t\t}\n\n\t}\n\n\tfunction updateUBOMapping( uniformsGroup, program ) {\n\n\t\tlet mapping = uboProgramMap.get( program );\n\n\t\tif ( mapping === undefined ) {\n\n\t\t\tmapping = new WeakMap();\n\n\t\t\tuboProgramMap.set( program, mapping );\n\n\t\t}\n\n\t\tlet blockIndex = mapping.get( uniformsGroup );\n\n\t\tif ( blockIndex === undefined ) {\n\n\t\t\tblockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );\n\n\t\t\tmapping.set( uniformsGroup, blockIndex );\n\n\t\t}\n\n\t}\n\n\tfunction uniformBlockBinding( uniformsGroup, program ) {\n\n\t\tconst mapping = uboProgramMap.get( program );\n\t\tconst blockIndex = mapping.get( uniformsGroup );\n\n\t\tif ( uboBindings.get( program ) !== blockIndex ) {\n\n\t\t\t// bind shader specific block index to global block point\n\t\t\tgl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );\n\n\t\t\tuboBindings.set( program, blockIndex );\n\n\t\t}\n\n\t}\n\n\t//\n\n\tfunction reset() {\n\n\t\t// reset state\n\n\t\tgl.disable( gl.BLEND );\n\t\tgl.disable( gl.CULL_FACE );\n\t\tgl.disable( gl.DEPTH_TEST );\n\t\tgl.disable( gl.POLYGON_OFFSET_FILL );\n\t\tgl.disable( gl.SCISSOR_TEST );\n\t\tgl.disable( gl.STENCIL_TEST );\n\t\tgl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );\n\n\t\tgl.blendEquation( gl.FUNC_ADD );\n\t\tgl.blendFunc( gl.ONE, gl.ZERO );\n\t\tgl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );\n\n\t\tgl.colorMask( true, true, true, true );\n\t\tgl.clearColor( 0, 0, 0, 0 );\n\n\t\tgl.depthMask( true );\n\t\tgl.depthFunc( gl.LESS );\n\t\tgl.clearDepth( 1 );\n\n\t\tgl.stencilMask( 0xffffffff );\n\t\tgl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );\n\t\tgl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );\n\t\tgl.clearStencil( 0 );\n\n\t\tgl.cullFace( gl.BACK );\n\t\tgl.frontFace( gl.CCW );\n\n\t\tgl.polygonOffset( 0, 0 );\n\n\t\tgl.activeTexture( gl.TEXTURE0 );\n\n\t\tgl.bindFramebuffer( gl.FRAMEBUFFER, null );\n\n\t\tif ( isWebGL2 === true ) {\n\n\t\t\tgl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );\n\t\t\tgl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );\n\n\t\t}\n\n\t\tgl.useProgram( null );\n\n\t\tgl.lineWidth( 1 );\n\n\t\tgl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );\n\t\tgl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );\n\n\t\t// reset internals\n\n\t\tenabledCapabilities = {};\n\n\t\tcurrentTextureSlot = null;\n\t\tcurrentBoundTextures = {};\n\n\t\tcurrentBoundFramebuffers = {};\n\t\tcurrentDrawbuffers = new WeakMap();\n\t\tdefaultDrawbuffers = [];\n\n\t\tcurrentProgram = null;\n\n\t\tcurrentBlendingEnabled = false;\n\t\tcurrentBlending = null;\n\t\tcurrentBlendEquation = null;\n\t\tcurrentBlendSrc = null;\n\t\tcurrentBlendDst = null;\n\t\tcurrentBlendEquationAlpha = null;\n\t\tcurrentBlendSrcAlpha = null;\n\t\tcurrentBlendDstAlpha = null;\n\t\tcurrentPremultipledAlpha = false;\n\n\t\tcurrentFlipSided = null;\n\t\tcurrentCullFace = null;\n\n\t\tcurrentLineWidth = null;\n\n\t\tcurrentPolygonOffsetFactor = null;\n\t\tcurrentPolygonOffsetUnits = null;\n\n\t\tcurrentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );\n\t\tcurrentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );\n\n\t\tcolorBuffer.reset();\n\t\tdepthBuffer.reset();\n\t\tstencilBuffer.reset();\n\n\t}\n\n\treturn {\n\n\t\tbuffers: {\n\t\t\tcolor: colorBuffer,\n\t\t\tdepth: depthBuffer,\n\t\t\tstencil: stencilBuffer\n\t\t},\n\n\t\tenable: enable,\n\t\tdisable: disable,\n\n\t\tbindFramebuffer: bindFramebuffer,\n\t\tdrawBuffers: drawBuffers,\n\n\t\tuseProgram: useProgram,\n\n\t\tsetBlending: setBlending,\n\t\tsetMaterial: setMaterial,\n\n\t\tsetFlipSided: setFlipSided,\n\t\tsetCullFace: setCullFace,\n\n\t\tsetLineWidth: setLineWidth,\n\t\tsetPolygonOffset: setPolygonOffset,\n\n\t\tsetScissorTest: setScissorTest,\n\n\t\tactiveTexture: activeTexture,\n\t\tbindTexture: bindTexture,\n\t\tunbindTexture: unbindTexture,\n\t\tcompressedTexImage2D: compressedTexImage2D,\n\t\tcompressedTexImage3D: compressedTexImage3D,\n\t\ttexImage2D: texImage2D,\n\t\ttexImage3D: texImage3D,\n\n\t\tupdateUBOMapping: updateUBOMapping,\n\t\tuniformBlockBinding: uniformBlockBinding,\n\n\t\ttexStorage2D: texStorage2D,\n\t\ttexStorage3D: texStorage3D,\n\t\ttexSubImage2D: texSubImage2D,\n\t\ttexSubImage3D: texSubImage3D,\n\t\tcompressedTexSubImage2D: compressedTexSubImage2D,\n\t\tcompressedTexSubImage3D: compressedTexSubImage3D,\n\n\t\tscissor: scissor,\n\t\tviewport: viewport,\n\n\t\treset: reset\n\n\t};\n\n}\n\nfunction WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {\n\n\tconst isWebGL2 = capabilities.isWebGL2;\n\tconst maxTextures = capabilities.maxTextures;\n\tconst maxCubemapSize = capabilities.maxCubemapSize;\n\tconst maxTextureSize = capabilities.maxTextureSize;\n\tconst maxSamples = capabilities.maxSamples;\n\tconst multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;\n\tconst supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );\n\n\tconst _videoTextures = new WeakMap();\n\tlet _canvas;\n\n\tconst _sources = new WeakMap(); // maps WebglTexture objects to instances of Source\n\n\t// cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,\n\t// also OffscreenCanvas.getContext(\"webgl\"), but not OffscreenCanvas.getContext(\"2d\")!\n\t// Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).\n\n\tlet useOffscreenCanvas = false;\n\n\ttry {\n\n\t\tuseOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'\n\t\t\t// eslint-disable-next-line compat/compat\n\t\t\t&& ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;\n\n\t} catch ( err ) {\n\n\t\t// Ignore any errors\n\n\t}\n\n\tfunction createCanvas( width, height ) {\n\n\t\t// Use OffscreenCanvas when available. Specially needed in web workers\n\n\t\treturn useOffscreenCanvas ?\n\t\t\t// eslint-disable-next-line compat/compat\n\t\t\tnew OffscreenCanvas( width, height ) : createElementNS( 'canvas' );\n\n\t}\n\n\tfunction resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {\n\n\t\tlet scale = 1;\n\n\t\t// handle case if texture exceeds max size\n\n\t\tif ( image.width > maxSize || image.height > maxSize ) {\n\n\t\t\tscale = maxSize / Math.max( image.width, image.height );\n\n\t\t}\n\n\t\t// only perform resize if necessary\n\n\t\tif ( scale < 1 || needsPowerOfTwo === true ) {\n\n\t\t\t// only perform resize for certain image types\n\n\t\t\tif ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||\n\t\t\t\t( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||\n\t\t\t\t( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {\n\n\t\t\t\tconst floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;\n\n\t\t\t\tconst width = floor( scale * image.width );\n\t\t\t\tconst height = floor( scale * image.height );\n\n\t\t\t\tif ( _canvas === undefined ) _canvas = createCanvas( width, height );\n\n\t\t\t\t// cube textures can't reuse the same canvas\n\n\t\t\t\tconst canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;\n\n\t\t\t\tcanvas.width = width;\n\t\t\t\tcanvas.height = height;\n\n\t\t\t\tconst context = canvas.getContext( '2d' );\n\t\t\t\tcontext.drawImage( image, 0, 0, width, height );\n\n\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );\n\n\t\t\t\treturn canvas;\n\n\t\t\t} else {\n\n\t\t\t\tif ( 'data' in image ) {\n\n\t\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );\n\n\t\t\t\t}\n\n\t\t\t\treturn image;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn image;\n\n\t}\n\n\tfunction isPowerOfTwo$1( image ) {\n\n\t\treturn isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );\n\n\t}\n\n\tfunction textureNeedsPowerOfTwo( texture ) {\n\n\t\tif ( isWebGL2 ) return false;\n\n\t\treturn ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||\n\t\t\t( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );\n\n\t}\n\n\tfunction textureNeedsGenerateMipmaps( texture, supportsMips ) {\n\n\t\treturn texture.generateMipmaps && supportsMips &&\n\t\t\ttexture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;\n\n\t}\n\n\tfunction generateMipmap( target ) {\n\n\t\t_gl.generateMipmap( target );\n\n\t}\n\n\tfunction getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {\n\n\t\tif ( isWebGL2 === false ) return glFormat;\n\n\t\tif ( internalFormatName !== null ) {\n\n\t\t\tif ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];\n\n\t\t\tconsole.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \\'' + internalFormatName + '\\'' );\n\n\t\t}\n\n\t\tlet internalFormat = glFormat;\n\n\t\tif ( glFormat === _gl.RED ) {\n\n\t\t\tif ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;\n\t\t\tif ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;\n\t\t\tif ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;\n\n\t\t}\n\n\t\tif ( glFormat === _gl.RG ) {\n\n\t\t\tif ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;\n\t\t\tif ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;\n\t\t\tif ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;\n\n\t\t}\n\n\t\tif ( glFormat === _gl.RGBA ) {\n\n\t\t\tif ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;\n\t\t\tif ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;\n\t\t\tif ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;\n\t\t\tif ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;\n\t\t\tif ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;\n\n\t\t}\n\n\t\tif ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||\n\t\t\tinternalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||\n\t\t\tinternalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {\n\n\t\t\textensions.get( 'EXT_color_buffer_float' );\n\n\t\t}\n\n\t\treturn internalFormat;\n\n\t}\n\n\tfunction getMipLevels( texture, image, supportsMips ) {\n\n\t\tif ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {\n\n\t\t\treturn Math.log2( Math.max( image.width, image.height ) ) + 1;\n\n\t\t} else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {\n\n\t\t\t// user-defined mipmaps\n\n\t\t\treturn texture.mipmaps.length;\n\n\t\t} else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {\n\n\t\t\treturn image.mipmaps.length;\n\n\t\t} else {\n\n\t\t\t// texture without mipmaps (only base level)\n\n\t\t\treturn 1;\n\n\t\t}\n\n\t}\n\n\t// Fallback filters for non-power-of-2 textures\n\n\tfunction filterFallback( f ) {\n\n\t\tif ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {\n\n\t\t\treturn _gl.NEAREST;\n\n\t\t}\n\n\t\treturn _gl.LINEAR;\n\n\t}\n\n\t//\n\n\tfunction onTextureDispose( event ) {\n\n\t\tconst texture = event.target;\n\n\t\ttexture.removeEventListener( 'dispose', onTextureDispose );\n\n\t\tdeallocateTexture( texture );\n\n\t\tif ( texture.isVideoTexture ) {\n\n\t\t\t_videoTextures.delete( texture );\n\n\t\t}\n\n\t}\n\n\tfunction onRenderTargetDispose( event ) {\n\n\t\tconst renderTarget = event.target;\n\n\t\trenderTarget.removeEventListener( 'dispose', onRenderTargetDispose );\n\n\t\tdeallocateRenderTarget( renderTarget );\n\n\t}\n\n\t//\n\n\tfunction deallocateTexture( texture ) {\n\n\t\tconst textureProperties = properties.get( texture );\n\n\t\tif ( textureProperties.__webglInit === undefined ) return;\n\n\t\t// check if it's necessary to remove the WebGLTexture object\n\n\t\tconst source = texture.source;\n\t\tconst webglTextures = _sources.get( source );\n\n\t\tif ( webglTextures ) {\n\n\t\t\tconst webglTexture = webglTextures[ textureProperties.__cacheKey ];\n\t\t\twebglTexture.usedTimes --;\n\n\t\t\t// the WebGLTexture object is not used anymore, remove it\n\n\t\t\tif ( webglTexture.usedTimes === 0 ) {\n\n\t\t\t\tdeleteTexture( texture );\n\n\t\t\t}\n\n\t\t\t// remove the weak map entry if no WebGLTexture uses the source anymore\n\n\t\t\tif ( Object.keys( webglTextures ).length === 0 ) {\n\n\t\t\t\t_sources.delete( source );\n\n\t\t\t}\n\n\t\t}\n\n\t\tproperties.remove( texture );\n\n\t}\n\n\tfunction deleteTexture( texture ) {\n\n\t\tconst textureProperties = properties.get( texture );\n\t\t_gl.deleteTexture( textureProperties.__webglTexture );\n\n\t\tconst source = texture.source;\n\t\tconst webglTextures = _sources.get( source );\n\t\tdelete webglTextures[ textureProperties.__cacheKey ];\n\n\t\tinfo.memory.textures --;\n\n\t}\n\n\tfunction deallocateRenderTarget( renderTarget ) {\n\n\t\tconst texture = renderTarget.texture;\n\n\t\tconst renderTargetProperties = properties.get( renderTarget );\n\t\tconst textureProperties = properties.get( texture );\n\n\t\tif ( textureProperties.__webglTexture !== undefined ) {\n\n\t\t\t_gl.deleteTexture( textureProperties.__webglTexture );\n\n\t\t\tinfo.memory.textures --;\n\n\t\t}\n\n\t\tif ( renderTarget.depthTexture ) {\n\n\t\t\trenderTarget.depthTexture.dispose();\n\n\t\t}\n\n\t\tif ( renderTarget.isWebGLCubeRenderTarget ) {\n\n\t\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\t\t_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );\n\t\t\t\tif ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\t_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );\n\t\t\tif ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );\n\t\t\tif ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );\n\n\t\t\tif ( renderTargetProperties.__webglColorRenderbuffer ) {\n\n\t\t\t\tfor ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {\n\n\t\t\t\t\tif ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );\n\n\t\t}\n\n\t\tif ( renderTarget.isWebGLMultipleRenderTargets ) {\n\n\t\t\tfor ( let i = 0, il = texture.length; i < il; i ++ ) {\n\n\t\t\t\tconst attachmentProperties = properties.get( texture[ i ] );\n\n\t\t\t\tif ( attachmentProperties.__webglTexture ) {\n\n\t\t\t\t\t_gl.deleteTexture( attachmentProperties.__webglTexture );\n\n\t\t\t\t\tinfo.memory.textures --;\n\n\t\t\t\t}\n\n\t\t\t\tproperties.remove( texture[ i ] );\n\n\t\t\t}\n\n\t\t}\n\n\t\tproperties.remove( texture );\n\t\tproperties.remove( renderTarget );\n\n\t}\n\n\t//\n\n\tlet textureUnits = 0;\n\n\tfunction resetTextureUnits() {\n\n\t\ttextureUnits = 0;\n\n\t}\n\n\tfunction allocateTextureUnit() {\n\n\t\tconst textureUnit = textureUnits;\n\n\t\tif ( textureUnit >= maxTextures ) {\n\n\t\t\tconsole.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );\n\n\t\t}\n\n\t\ttextureUnits += 1;\n\n\t\treturn textureUnit;\n\n\t}\n\n\tfunction getTextureCacheKey( texture ) {\n\n\t\tconst array = [];\n\n\t\tarray.push( texture.wrapS );\n\t\tarray.push( texture.wrapT );\n\t\tarray.push( texture.wrapR || 0 );\n\t\tarray.push( texture.magFilter );\n\t\tarray.push( texture.minFilter );\n\t\tarray.push( texture.anisotropy );\n\t\tarray.push( texture.internalFormat );\n\t\tarray.push( texture.format );\n\t\tarray.push( texture.type );\n\t\tarray.push( texture.generateMipmaps );\n\t\tarray.push( texture.premultiplyAlpha );\n\t\tarray.push( texture.flipY );\n\t\tarray.push( texture.unpackAlignment );\n\t\tarray.push( texture.colorSpace );\n\n\t\treturn array.join();\n\n\t}\n\n\t//\n\n\tfunction setTexture2D( texture, slot ) {\n\n\t\tconst textureProperties = properties.get( texture );\n\n\t\tif ( texture.isVideoTexture ) updateVideoTexture( texture );\n\n\t\tif ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {\n\n\t\t\tconst image = texture.image;\n\n\t\t\tif ( image === null ) {\n\n\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );\n\n\t\t\t} else if ( image.complete === false ) {\n\n\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );\n\n\t\t\t} else {\n\n\t\t\t\tuploadTexture( textureProperties, texture, slot );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t}\n\n\t\tstate.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );\n\n\t}\n\n\tfunction setTexture2DArray( texture, slot ) {\n\n\t\tconst textureProperties = properties.get( texture );\n\n\t\tif ( texture.version > 0 && textureProperties.__version !== texture.version ) {\n\n\t\t\tuploadTexture( textureProperties, texture, slot );\n\t\t\treturn;\n\n\t\t}\n\n\t\tstate.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );\n\n\t}\n\n\tfunction setTexture3D( texture, slot ) {\n\n\t\tconst textureProperties = properties.get( texture );\n\n\t\tif ( texture.version > 0 && textureProperties.__version !== texture.version ) {\n\n\t\t\tuploadTexture( textureProperties, texture, slot );\n\t\t\treturn;\n\n\t\t}\n\n\t\tstate.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );\n\n\t}\n\n\tfunction setTextureCube( texture, slot ) {\n\n\t\tconst textureProperties = properties.get( texture );\n\n\t\tif ( texture.version > 0 && textureProperties.__version !== texture.version ) {\n\n\t\t\tuploadCubeTexture( textureProperties, texture, slot );\n\t\t\treturn;\n\n\t\t}\n\n\t\tstate.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );\n\n\t}\n\n\tconst wrappingToGL = {\n\t\t[ RepeatWrapping ]: _gl.REPEAT,\n\t\t[ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,\n\t\t[ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT\n\t};\n\n\tconst filterToGL = {\n\t\t[ NearestFilter ]: _gl.NEAREST,\n\t\t[ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,\n\t\t[ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,\n\n\t\t[ LinearFilter ]: _gl.LINEAR,\n\t\t[ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,\n\t\t[ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR\n\t};\n\n\tfunction setTextureParameters( textureType, texture, supportsMips ) {\n\n\t\tif ( supportsMips ) {\n\n\t\t\t_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );\n\t\t\t_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );\n\n\t\t\tif ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {\n\n\t\t\t\t_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );\n\n\t\t\t}\n\n\t\t\t_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );\n\t\t\t_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );\n\n\t\t} else {\n\n\t\t\t_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );\n\t\t\t_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );\n\n\t\t\tif ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {\n\n\t\t\t\t_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );\n\n\t\t\t}\n\n\t\t\tif ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {\n\n\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );\n\n\t\t\t}\n\n\t\t\t_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );\n\t\t\t_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );\n\n\t\t\tif ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {\n\n\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {\n\n\t\t\tconst extension = extensions.get( 'EXT_texture_filter_anisotropic' );\n\n\t\t\tif ( texture.magFilter === NearestFilter ) return;\n\t\t\tif ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;\n\t\t\tif ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2\n\t\t\tif ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only\n\n\t\t\tif ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {\n\n\t\t\t\t_gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );\n\t\t\t\tproperties.get( texture ).__currentAnisotropy = texture.anisotropy;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tfunction initTexture( textureProperties, texture ) {\n\n\t\tlet forceUpload = false;\n\n\t\tif ( textureProperties.__webglInit === undefined ) {\n\n\t\t\ttextureProperties.__webglInit = true;\n\n\t\t\ttexture.addEventListener( 'dispose', onTextureDispose );\n\n\t\t}\n\n\t\t// create Source <-> WebGLTextures mapping if necessary\n\n\t\tconst source = texture.source;\n\t\tlet webglTextures = _sources.get( source );\n\n\t\tif ( webglTextures === undefined ) {\n\n\t\t\twebglTextures = {};\n\t\t\t_sources.set( source, webglTextures );\n\n\t\t}\n\n\t\t// check if there is already a WebGLTexture object for the given texture parameters\n\n\t\tconst textureCacheKey = getTextureCacheKey( texture );\n\n\t\tif ( textureCacheKey !== textureProperties.__cacheKey ) {\n\n\t\t\t// if not, create a new instance of WebGLTexture\n\n\t\t\tif ( webglTextures[ textureCacheKey ] === undefined ) {\n\n\t\t\t\t// create new entry\n\n\t\t\t\twebglTextures[ textureCacheKey ] = {\n\t\t\t\t\ttexture: _gl.createTexture(),\n\t\t\t\t\tusedTimes: 0\n\t\t\t\t};\n\n\t\t\t\tinfo.memory.textures ++;\n\n\t\t\t\t// when a new instance of WebGLTexture was created, a texture upload is required\n\t\t\t\t// even if the image contents are identical\n\n\t\t\t\tforceUpload = true;\n\n\t\t\t}\n\n\t\t\twebglTextures[ textureCacheKey ].usedTimes ++;\n\n\t\t\t// every time the texture cache key changes, it's necessary to check if an instance of\n\t\t\t// WebGLTexture can be deleted in order to avoid a memory leak.\n\n\t\t\tconst webglTexture = webglTextures[ textureProperties.__cacheKey ];\n\n\t\t\tif ( webglTexture !== undefined ) {\n\n\t\t\t\twebglTextures[ textureProperties.__cacheKey ].usedTimes --;\n\n\t\t\t\tif ( webglTexture.usedTimes === 0 ) {\n\n\t\t\t\t\tdeleteTexture( texture );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// store references to cache key and WebGLTexture object\n\n\t\t\ttextureProperties.__cacheKey = textureCacheKey;\n\t\t\ttextureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;\n\n\t\t}\n\n\t\treturn forceUpload;\n\n\t}\n\n\tfunction uploadTexture( textureProperties, texture, slot ) {\n\n\t\tlet textureType = _gl.TEXTURE_2D;\n\n\t\tif ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;\n\t\tif ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;\n\n\t\tconst forceUpload = initTexture( textureProperties, texture );\n\t\tconst source = texture.source;\n\n\t\tstate.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );\n\n\t\tconst sourceProperties = properties.get( source );\n\n\t\tif ( source.version !== sourceProperties.__version || forceUpload === true ) {\n\n\t\t\tstate.activeTexture( _gl.TEXTURE0 + slot );\n\n\t\t\t_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );\n\n\t\t\tconst needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;\n\t\t\tlet image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );\n\t\t\timage = verifyColorSpace( texture, image );\n\n\t\t\tconst supportsMips = isPowerOfTwo$1( image ) || isWebGL2,\n\t\t\t\tglFormat = utils.convert( texture.format, texture.colorSpace );\n\n\t\t\tlet glType = utils.convert( texture.type ),\n\t\t\t\tglInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );\n\n\t\t\tsetTextureParameters( textureType, texture, supportsMips );\n\n\t\t\tlet mipmap;\n\t\t\tconst mipmaps = texture.mipmaps;\n\n\t\t\tconst useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );\n\t\t\tconst allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );\n\t\t\tconst levels = getMipLevels( texture, image, supportsMips );\n\n\t\t\tif ( texture.isDepthTexture ) {\n\n\t\t\t\t// populate depth texture with dummy data\n\n\t\t\t\tglInternalFormat = _gl.DEPTH_COMPONENT;\n\n\t\t\t\tif ( isWebGL2 ) {\n\n\t\t\t\t\tif ( texture.type === FloatType ) {\n\n\t\t\t\t\t\tglInternalFormat = _gl.DEPTH_COMPONENT32F;\n\n\t\t\t\t\t} else if ( texture.type === UnsignedIntType ) {\n\n\t\t\t\t\t\tglInternalFormat = _gl.DEPTH_COMPONENT24;\n\n\t\t\t\t\t} else if ( texture.type === UnsignedInt248Type ) {\n\n\t\t\t\t\t\tglInternalFormat = _gl.DEPTH24_STENCIL8;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tglInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\tif ( texture.type === FloatType ) {\n\n\t\t\t\t\t\tconsole.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\t// validation checks for WebGL 1\n\n\t\t\t\tif ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {\n\n\t\t\t\t\t// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are\n\t\t\t\t\t// DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT\n\t\t\t\t\t// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)\n\t\t\t\t\tif ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {\n\n\t\t\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );\n\n\t\t\t\t\t\ttexture.type = UnsignedIntType;\n\t\t\t\t\t\tglType = utils.convert( texture.type );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {\n\n\t\t\t\t\t// Depth stencil textures need the DEPTH_STENCIL internal format\n\t\t\t\t\t// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)\n\t\t\t\t\tglInternalFormat = _gl.DEPTH_STENCIL;\n\n\t\t\t\t\t// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are\n\t\t\t\t\t// DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.\n\t\t\t\t\t// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)\n\t\t\t\t\tif ( texture.type !== UnsignedInt248Type ) {\n\n\t\t\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );\n\n\t\t\t\t\t\ttexture.type = UnsignedInt248Type;\n\t\t\t\t\t\tglType = utils.convert( texture.type );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\t//\n\n\t\t\t\tif ( allocateMemory ) {\n\n\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\tstate.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tstate.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} else if ( texture.isDataTexture ) {\n\n\t\t\t\t// use manually created mipmaps if available\n\t\t\t\t// if there are no manual mipmaps\n\t\t\t\t// set 0 level mipmap and then use GL to generate other mipmap levels\n\n\t\t\t\tif ( mipmaps.length > 0 && supportsMips ) {\n\n\t\t\t\t\tif ( useTexStorage && allocateMemory ) {\n\n\t\t\t\t\t\tstate.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfor ( let i = 0, il = mipmaps.length; i < il; i ++ ) {\n\n\t\t\t\t\t\tmipmap = mipmaps[ i ];\n\n\t\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\t\tstate.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tstate.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\ttexture.generateMipmaps = false;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\tif ( allocateMemory ) {\n\n\t\t\t\t\t\t\tstate.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstate.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tstate.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} else if ( texture.isCompressedTexture ) {\n\n\t\t\t\tif ( texture.isCompressedArrayTexture ) {\n\n\t\t\t\t\tif ( useTexStorage && allocateMemory ) {\n\n\t\t\t\t\t\tstate.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfor ( let i = 0, il = mipmaps.length; i < il; i ++ ) {\n\n\t\t\t\t\t\tmipmap = mipmaps[ i ];\n\n\t\t\t\t\t\tif ( texture.format !== RGBAFormat ) {\n\n\t\t\t\t\t\t\tif ( glFormat !== null ) {\n\n\t\t\t\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\t\t\t\tstate.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );\n\n\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\tstate.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\t\t\tstate.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tstate.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\tif ( useTexStorage && allocateMemory ) {\n\n\t\t\t\t\t\tstate.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfor ( let i = 0, il = mipmaps.length; i < il; i ++ ) {\n\n\t\t\t\t\t\tmipmap = mipmaps[ i ];\n\n\t\t\t\t\t\tif ( texture.format !== RGBAFormat ) {\n\n\t\t\t\t\t\t\tif ( glFormat !== null ) {\n\n\t\t\t\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\t\t\t\tstate.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );\n\n\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\tstate.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\t\t\tstate.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tstate.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} else if ( texture.isDataArrayTexture ) {\n\n\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\tif ( allocateMemory ) {\n\n\t\t\t\t\t\tstate.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tstate.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tstate.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );\n\n\t\t\t\t}\n\n\t\t\t} else if ( texture.isData3DTexture ) {\n\n\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\tif ( allocateMemory ) {\n\n\t\t\t\t\t\tstate.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tstate.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tstate.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );\n\n\t\t\t\t}\n\n\t\t\t} else if ( texture.isFramebufferTexture ) {\n\n\t\t\t\tif ( allocateMemory ) {\n\n\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\tstate.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tlet width = image.width, height = image.height;\n\n\t\t\t\t\t\tfor ( let i = 0; i < levels; i ++ ) {\n\n\t\t\t\t\t\t\tstate.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );\n\n\t\t\t\t\t\t\twidth >>= 1;\n\t\t\t\t\t\t\theight >>= 1;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\t// regular Texture (image, video, canvas)\n\n\t\t\t\t// use manually created mipmaps if available\n\t\t\t\t// if there are no manual mipmaps\n\t\t\t\t// set 0 level mipmap and then use GL to generate other mipmap levels\n\n\t\t\t\tif ( mipmaps.length > 0 && supportsMips ) {\n\n\t\t\t\t\tif ( useTexStorage && allocateMemory ) {\n\n\t\t\t\t\t\tstate.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfor ( let i = 0, il = mipmaps.length; i < il; i ++ ) {\n\n\t\t\t\t\t\tmipmap = mipmaps[ i ];\n\n\t\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\t\tstate.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tstate.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\ttexture.generateMipmaps = false;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\tif ( allocateMemory ) {\n\n\t\t\t\t\t\t\tstate.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstate.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tstate.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {\n\n\t\t\t\tgenerateMipmap( textureType );\n\n\t\t\t}\n\n\t\t\tsourceProperties.__version = source.version;\n\n\t\t\tif ( texture.onUpdate ) texture.onUpdate( texture );\n\n\t\t}\n\n\t\ttextureProperties.__version = texture.version;\n\n\t}\n\n\tfunction uploadCubeTexture( textureProperties, texture, slot ) {\n\n\t\tif ( texture.image.length !== 6 ) return;\n\n\t\tconst forceUpload = initTexture( textureProperties, texture );\n\t\tconst source = texture.source;\n\n\t\tstate.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );\n\n\t\tconst sourceProperties = properties.get( source );\n\n\t\tif ( source.version !== sourceProperties.__version || forceUpload === true ) {\n\n\t\t\tstate.activeTexture( _gl.TEXTURE0 + slot );\n\n\t\t\t_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );\n\n\t\t\tconst isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );\n\t\t\tconst isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );\n\n\t\t\tconst cubeImage = [];\n\n\t\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\t\tif ( ! isCompressed && ! isDataTexture ) {\n\n\t\t\t\t\tcubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tcubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];\n\n\t\t\t\t}\n\n\t\t\t\tcubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );\n\n\t\t\t}\n\n\t\t\tconst image = cubeImage[ 0 ],\n\t\t\t\tsupportsMips = isPowerOfTwo$1( image ) || isWebGL2,\n\t\t\t\tglFormat = utils.convert( texture.format, texture.colorSpace ),\n\t\t\t\tglType = utils.convert( texture.type ),\n\t\t\t\tglInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );\n\n\t\t\tconst useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );\n\t\t\tconst allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );\n\t\t\tlet levels = getMipLevels( texture, image, supportsMips );\n\n\t\t\tsetTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );\n\n\t\t\tlet mipmaps;\n\n\t\t\tif ( isCompressed ) {\n\n\t\t\t\tif ( useTexStorage && allocateMemory ) {\n\n\t\t\t\t\tstate.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );\n\n\t\t\t\t}\n\n\t\t\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\t\t\tmipmaps = cubeImage[ i ].mipmaps;\n\n\t\t\t\t\tfor ( let j = 0; j < mipmaps.length; j ++ ) {\n\n\t\t\t\t\t\tconst mipmap = mipmaps[ j ];\n\n\t\t\t\t\t\tif ( texture.format !== RGBAFormat ) {\n\n\t\t\t\t\t\t\tif ( glFormat !== null ) {\n\n\t\t\t\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\t\t\t\tstate.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );\n\n\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\tstate.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\t\t\tstate.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tstate.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tmipmaps = texture.mipmaps;\n\n\t\t\t\tif ( useTexStorage && allocateMemory ) {\n\n\t\t\t\t\t// TODO: Uniformly handle mipmap definitions\n\t\t\t\t\t// Normal textures and compressed cube textures define base level + mips with their mipmap array\n\t\t\t\t\t// Uncompressed cube textures use their mipmap array only for mips (no base level)\n\n\t\t\t\t\tif ( mipmaps.length > 0 ) levels ++;\n\n\t\t\t\t\tstate.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );\n\n\t\t\t\t}\n\n\t\t\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\t\t\tif ( isDataTexture ) {\n\n\t\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\t\tstate.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tstate.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor ( let j = 0; j < mipmaps.length; j ++ ) {\n\n\t\t\t\t\t\t\tconst mipmap = mipmaps[ j ];\n\t\t\t\t\t\t\tconst mipmapImage = mipmap.image[ i ].image;\n\n\t\t\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\t\t\tstate.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tstate.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\t\tstate.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tstate.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor ( let j = 0; j < mipmaps.length; j ++ ) {\n\n\t\t\t\t\t\t\tconst mipmap = mipmaps[ j ];\n\n\t\t\t\t\t\t\tif ( useTexStorage ) {\n\n\t\t\t\t\t\t\t\tstate.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tstate.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {\n\n\t\t\t\t// We assume images for cube map have the same size.\n\t\t\t\tgenerateMipmap( _gl.TEXTURE_CUBE_MAP );\n\n\t\t\t}\n\n\t\t\tsourceProperties.__version = source.version;\n\n\t\t\tif ( texture.onUpdate ) texture.onUpdate( texture );\n\n\t\t}\n\n\t\ttextureProperties.__version = texture.version;\n\n\t}\n\n\t// Render targets\n\n\t// Setup storage for target texture and bind it to correct framebuffer\n\tfunction setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {\n\n\t\tconst glFormat = utils.convert( texture.format, texture.colorSpace );\n\t\tconst glType = utils.convert( texture.type );\n\t\tconst glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );\n\t\tconst renderTargetProperties = properties.get( renderTarget );\n\n\t\tif ( ! renderTargetProperties.__hasExternalTextures ) {\n\n\t\t\tif ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {\n\n\t\t\t\tstate.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );\n\n\t\t\t} else {\n\n\t\t\t\tstate.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );\n\n\t\t\t}\n\n\t\t}\n\n\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );\n\n\t\tif ( useMultisampledRTT( renderTarget ) ) {\n\n\t\t\tmultisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );\n\n\t\t} else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753\n\n\t\t\t_gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );\n\n\t\t}\n\n\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, null );\n\n\t}\n\n\n\t// Setup storage for internal depth/stencil buffers and bind to correct framebuffer\n\tfunction setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {\n\n\t\t_gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );\n\n\t\tif ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {\n\n\t\t\tlet glInternalFormat = _gl.DEPTH_COMPONENT16;\n\n\t\t\tif ( isMultisample || useMultisampledRTT( renderTarget ) ) {\n\n\t\t\t\tconst depthTexture = renderTarget.depthTexture;\n\n\t\t\t\tif ( depthTexture && depthTexture.isDepthTexture ) {\n\n\t\t\t\t\tif ( depthTexture.type === FloatType ) {\n\n\t\t\t\t\t\tglInternalFormat = _gl.DEPTH_COMPONENT32F;\n\n\t\t\t\t\t} else if ( depthTexture.type === UnsignedIntType ) {\n\n\t\t\t\t\t\tglInternalFormat = _gl.DEPTH_COMPONENT24;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tconst samples = getRenderTargetSamples( renderTarget );\n\n\t\t\t\tif ( useMultisampledRTT( renderTarget ) ) {\n\n\t\t\t\t\tmultisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t_gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\t_gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );\n\n\t\t\t}\n\n\t\t\t_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );\n\n\t\t} else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {\n\n\t\t\tconst samples = getRenderTargetSamples( renderTarget );\n\n\t\t\tif ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {\n\n\t\t\t\t_gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );\n\n\t\t\t} else if ( useMultisampledRTT( renderTarget ) ) {\n\n\t\t\t\tmultisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );\n\n\t\t\t} else {\n\n\t\t\t\t_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );\n\n\t\t\t}\n\n\n\t\t\t_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );\n\n\t\t} else {\n\n\t\t\tconst textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];\n\n\t\t\tfor ( let i = 0; i < textures.length; i ++ ) {\n\n\t\t\t\tconst texture = textures[ i ];\n\n\t\t\t\tconst glFormat = utils.convert( texture.format, texture.colorSpace );\n\t\t\t\tconst glType = utils.convert( texture.type );\n\t\t\t\tconst glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );\n\t\t\t\tconst samples = getRenderTargetSamples( renderTarget );\n\n\t\t\t\tif ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {\n\n\t\t\t\t\t_gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );\n\n\t\t\t\t} else if ( useMultisampledRTT( renderTarget ) ) {\n\n\t\t\t\t\tmultisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t_gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\t_gl.bindRenderbuffer( _gl.RENDERBUFFER, null );\n\n\t}\n\n\t// Setup resources for a Depth Texture for a FBO (needs an extension)\n\tfunction setupDepthTexture( framebuffer, renderTarget ) {\n\n\t\tconst isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );\n\t\tif ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );\n\n\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );\n\n\t\tif ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {\n\n\t\t\tthrow new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );\n\n\t\t}\n\n\t\t// upload an empty depth texture with framebuffer size\n\t\tif ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||\n\t\t\t\trenderTarget.depthTexture.image.width !== renderTarget.width ||\n\t\t\t\trenderTarget.depthTexture.image.height !== renderTarget.height ) {\n\n\t\t\trenderTarget.depthTexture.image.width = renderTarget.width;\n\t\t\trenderTarget.depthTexture.image.height = renderTarget.height;\n\t\t\trenderTarget.depthTexture.needsUpdate = true;\n\n\t\t}\n\n\t\tsetTexture2D( renderTarget.depthTexture, 0 );\n\n\t\tconst webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;\n\t\tconst samples = getRenderTargetSamples( renderTarget );\n\n\t\tif ( renderTarget.depthTexture.format === DepthFormat ) {\n\n\t\t\tif ( useMultisampledRTT( renderTarget ) ) {\n\n\t\t\t\tmultisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );\n\n\t\t\t} else {\n\n\t\t\t\t_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );\n\n\t\t\t}\n\n\t\t} else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {\n\n\t\t\tif ( useMultisampledRTT( renderTarget ) ) {\n\n\t\t\t\tmultisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );\n\n\t\t\t} else {\n\n\t\t\t\t_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tthrow new Error( 'Unknown depthTexture format' );\n\n\t\t}\n\n\t}\n\n\t// Setup GL resources for a non-texture depth buffer\n\tfunction setupDepthRenderbuffer( renderTarget ) {\n\n\t\tconst renderTargetProperties = properties.get( renderTarget );\n\t\tconst isCube = ( renderTarget.isWebGLCubeRenderTarget === true );\n\n\t\tif ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {\n\n\t\t\tif ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );\n\n\t\t\tsetupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );\n\n\t\t} else {\n\n\t\t\tif ( isCube ) {\n\n\t\t\t\trenderTargetProperties.__webglDepthbuffer = [];\n\n\t\t\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\t\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );\n\t\t\t\t\trenderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();\n\t\t\t\t\tsetupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );\n\t\t\t\trenderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();\n\t\t\t\tsetupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );\n\n\t\t\t}\n\n\t\t}\n\n\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, null );\n\n\t}\n\n\t// rebind framebuffer with external textures\n\tfunction rebindTextures( renderTarget, colorTexture, depthTexture ) {\n\n\t\tconst renderTargetProperties = properties.get( renderTarget );\n\n\t\tif ( colorTexture !== undefined ) {\n\n\t\t\tsetupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );\n\n\t\t}\n\n\t\tif ( depthTexture !== undefined ) {\n\n\t\t\tsetupDepthRenderbuffer( renderTarget );\n\n\t\t}\n\n\t}\n\n\t// Set up GL resources for the render target\n\tfunction setupRenderTarget( renderTarget ) {\n\n\t\tconst texture = renderTarget.texture;\n\n\t\tconst renderTargetProperties = properties.get( renderTarget );\n\t\tconst textureProperties = properties.get( texture );\n\n\t\trenderTarget.addEventListener( 'dispose', onRenderTargetDispose );\n\n\t\tif ( renderTarget.isWebGLMultipleRenderTargets !== true ) {\n\n\t\t\tif ( textureProperties.__webglTexture === undefined ) {\n\n\t\t\t\ttextureProperties.__webglTexture = _gl.createTexture();\n\n\t\t\t}\n\n\t\t\ttextureProperties.__version = texture.version;\n\t\t\tinfo.memory.textures ++;\n\n\t\t}\n\n\t\tconst isCube = ( renderTarget.isWebGLCubeRenderTarget === true );\n\t\tconst isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );\n\t\tconst supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;\n\n\t\t// Setup framebuffer\n\n\t\tif ( isCube ) {\n\n\t\t\trenderTargetProperties.__webglFramebuffer = [];\n\n\t\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\t\trenderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\trenderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();\n\n\t\t\tif ( isMultipleRenderTargets ) {\n\n\t\t\t\tif ( capabilities.drawBuffers ) {\n\n\t\t\t\t\tconst textures = renderTarget.texture;\n\n\t\t\t\t\tfor ( let i = 0, il = textures.length; i < il; i ++ ) {\n\n\t\t\t\t\t\tconst attachmentProperties = properties.get( textures[ i ] );\n\n\t\t\t\t\t\tif ( attachmentProperties.__webglTexture === undefined ) {\n\n\t\t\t\t\t\t\tattachmentProperties.__webglTexture = _gl.createTexture();\n\n\t\t\t\t\t\t\tinfo.memory.textures ++;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {\n\n\t\t\t\tconst textures = isMultipleRenderTargets ? texture : [ texture ];\n\n\t\t\t\trenderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();\n\t\t\t\trenderTargetProperties.__webglColorRenderbuffer = [];\n\n\t\t\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );\n\n\t\t\t\tfor ( let i = 0; i < textures.length; i ++ ) {\n\n\t\t\t\t\tconst texture = textures[ i ];\n\t\t\t\t\trenderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();\n\n\t\t\t\t\t_gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );\n\n\t\t\t\t\tconst glFormat = utils.convert( texture.format, texture.colorSpace );\n\t\t\t\t\tconst glType = utils.convert( texture.type );\n\t\t\t\t\tconst glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );\n\t\t\t\t\tconst samples = getRenderTargetSamples( renderTarget );\n\t\t\t\t\t_gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );\n\n\t\t\t\t\t_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );\n\n\t\t\t\t}\n\n\t\t\t\t_gl.bindRenderbuffer( _gl.RENDERBUFFER, null );\n\n\t\t\t\tif ( renderTarget.depthBuffer ) {\n\n\t\t\t\t\trenderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();\n\t\t\t\t\tsetupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );\n\n\t\t\t\t}\n\n\t\t\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, null );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// Setup color buffer\n\n\t\tif ( isCube ) {\n\n\t\t\tstate.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );\n\t\t\tsetTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );\n\n\t\t\tfor ( let i = 0; i < 6; i ++ ) {\n\n\t\t\t\tsetupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );\n\n\t\t\t}\n\n\t\t\tif ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {\n\n\t\t\t\tgenerateMipmap( _gl.TEXTURE_CUBE_MAP );\n\n\t\t\t}\n\n\t\t\tstate.unbindTexture();\n\n\t\t} else if ( isMultipleRenderTargets ) {\n\n\t\t\tconst textures = renderTarget.texture;\n\n\t\t\tfor ( let i = 0, il = textures.length; i < il; i ++ ) {\n\n\t\t\t\tconst attachment = textures[ i ];\n\t\t\t\tconst attachmentProperties = properties.get( attachment );\n\n\t\t\t\tstate.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );\n\t\t\t\tsetTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips );\n\t\t\t\tsetupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D );\n\n\t\t\t\tif ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {\n\n\t\t\t\t\tgenerateMipmap( _gl.TEXTURE_2D );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tstate.unbindTexture();\n\n\t\t} else {\n\n\t\t\tlet glTextureType = _gl.TEXTURE_2D;\n\n\t\t\tif ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {\n\n\t\t\t\tif ( isWebGL2 ) {\n\n\t\t\t\t\tglTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tconsole.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tstate.bindTexture( glTextureType, textureProperties.__webglTexture );\n\t\t\tsetTextureParameters( glTextureType, texture, supportsMips );\n\t\t\tsetupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType );\n\n\t\t\tif ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {\n\n\t\t\t\tgenerateMipmap( glTextureType );\n\n\t\t\t}\n\n\t\t\tstate.unbindTexture();\n\n\t\t}\n\n\t\t// Setup depth and stencil buffers\n\n\t\tif ( renderTarget.depthBuffer ) {\n\n\t\t\tsetupDepthRenderbuffer( renderTarget );\n\n\t\t}\n\n\t}\n\n\tfunction updateRenderTargetMipmap( renderTarget ) {\n\n\t\tconst supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;\n\n\t\tconst textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];\n\n\t\tfor ( let i = 0, il = textures.length; i < il; i ++ ) {\n\n\t\t\tconst texture = textures[ i ];\n\n\t\t\tif ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {\n\n\t\t\t\tconst target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;\n\t\t\t\tconst webglTexture = properties.get( texture ).__webglTexture;\n\n\t\t\t\tstate.bindTexture( target, webglTexture );\n\t\t\t\tgenerateMipmap( target );\n\t\t\t\tstate.unbindTexture();\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tfunction updateMultisampleRenderTarget( renderTarget ) {\n\n\t\tif ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {\n\n\t\t\tconst textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];\n\t\t\tconst width = renderTarget.width;\n\t\t\tconst height = renderTarget.height;\n\t\t\tlet mask = _gl.COLOR_BUFFER_BIT;\n\t\t\tconst invalidationArray = [];\n\t\t\tconst depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;\n\t\t\tconst renderTargetProperties = properties.get( renderTarget );\n\t\t\tconst isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );\n\n\t\t\t// If MRT we need to remove FBO attachments\n\t\t\tif ( isMultipleRenderTargets ) {\n\n\t\t\t\tfor ( let i = 0; i < textures.length; i ++ ) {\n\n\t\t\t\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );\n\t\t\t\t\t_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );\n\n\t\t\t\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );\n\t\t\t\t\t_gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tstate.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );\n\t\t\tstate.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );\n\n\t\t\tfor ( let i = 0; i < textures.length; i ++ ) {\n\n\t\t\t\tinvalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );\n\n\t\t\t\tif ( renderTarget.depthBuffer ) {\n\n\t\t\t\t\tinvalidationArray.push( depthStyle );\n\n\t\t\t\t}\n\n\t\t\t\tconst ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;\n\n\t\t\t\tif ( ignoreDepthValues === false ) {\n\n\t\t\t\t\tif ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;\n\t\t\t\t\tif ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;\n\n\t\t\t\t}\n\n\t\t\t\tif ( isMultipleRenderTargets ) {\n\n\t\t\t\t\t_gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );\n\n\t\t\t\t}\n\n\t\t\t\tif ( ignoreDepthValues === true ) {\n\n\t\t\t\t\t_gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );\n\t\t\t\t\t_gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );\n\n\t\t\t\t}\n\n\t\t\t\tif ( isMultipleRenderTargets ) {\n\n\t\t\t\t\tconst webglTexture = properties.get( textures[ i ] ).__webglTexture;\n\t\t\t\t\t_gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );\n\n\t\t\t\t}\n\n\t\t\t\t_gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );\n\n\t\t\t\tif ( supportsInvalidateFramebuffer ) {\n\n\t\t\t\t\t_gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );\n\n\t\t\t\t}\n\n\n\t\t\t}\n\n\t\t\tstate.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );\n\t\t\tstate.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );\n\n\t\t\t// If MRT since pre-blit we removed the FBO we need to reconstruct the attachments\n\t\t\tif ( isMultipleRenderTargets ) {\n\n\t\t\t\tfor ( let i = 0; i < textures.length; i ++ ) {\n\n\t\t\t\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );\n\t\t\t\t\t_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );\n\n\t\t\t\t\tconst webglTexture = properties.get( textures[ i ] ).__webglTexture;\n\n\t\t\t\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );\n\t\t\t\t\t_gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tstate.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );\n\n\t\t}\n\n\t}\n\n\tfunction getRenderTargetSamples( renderTarget ) {\n\n\t\treturn Math.min( maxSamples, renderTarget.samples );\n\n\t}\n\n\tfunction useMultisampledRTT( renderTarget ) {\n\n\t\tconst renderTargetProperties = properties.get( renderTarget );\n\n\t\treturn isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;\n\n\t}\n\n\tfunction updateVideoTexture( texture ) {\n\n\t\tconst frame = info.render.frame;\n\n\t\t// Check the last frame we updated the VideoTexture\n\n\t\tif ( _videoTextures.get( texture ) !== frame ) {\n\n\t\t\t_videoTextures.set( texture, frame );\n\t\t\ttexture.update();\n\n\t\t}\n\n\t}\n\n\tfunction verifyColorSpace( texture, image ) {\n\n\t\tconst colorSpace = texture.colorSpace;\n\t\tconst format = texture.format;\n\t\tconst type = texture.type;\n\n\t\tif ( texture.isCompressedTexture === true || texture.format === _SRGBAFormat ) return image;\n\n\t\tif ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {\n\n\t\t\t// sRGB\n\n\t\t\tif ( colorSpace === SRGBColorSpace ) {\n\n\t\t\t\tif ( isWebGL2 === false ) {\n\n\t\t\t\t\t// in WebGL 1, try to use EXT_sRGB extension and unsized formats\n\n\t\t\t\t\tif ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {\n\n\t\t\t\t\t\ttexture.format = _SRGBAFormat;\n\n\t\t\t\t\t\t// it's not possible to generate mips in WebGL 1 with this extension\n\n\t\t\t\t\t\ttexture.minFilter = LinearFilter;\n\t\t\t\t\t\ttexture.generateMipmaps = false;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t// slow fallback (CPU decode)\n\n\t\t\t\t\t\timage = ImageUtils.sRGBToLinear( image );\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format\n\n\t\t\t\t\tif ( format !== RGBAFormat || type !== UnsignedByteType ) {\n\n\t\t\t\t\t\tconsole.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tconsole.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn image;\n\n\t}\n\n\t//\n\n\tthis.allocateTextureUnit = allocateTextureUnit;\n\tthis.resetTextureUnits = resetTextureUnits;\n\n\tthis.setTexture2D = setTexture2D;\n\tthis.setTexture2DArray = setTexture2DArray;\n\tthis.setTexture3D = setTexture3D;\n\tthis.setTextureCube = setTextureCube;\n\tthis.rebindTextures = rebindTextures;\n\tthis.setupRenderTarget = setupRenderTarget;\n\tthis.updateRenderTargetMipmap = updateRenderTargetMipmap;\n\tthis.updateMultisampleRenderTarget = updateMultisampleRenderTarget;\n\tthis.setupDepthRenderbuffer = setupDepthRenderbuffer;\n\tthis.setupFrameBufferTexture = setupFrameBufferTexture;\n\tthis.useMultisampledRTT = useMultisampledRTT;\n\n}\n\nfunction WebGLUtils( gl, extensions, capabilities ) {\n\n\tconst isWebGL2 = capabilities.isWebGL2;\n\n\tfunction convert( p, colorSpace = NoColorSpace ) {\n\n\t\tlet extension;\n\n\t\tif ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;\n\t\tif ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;\n\t\tif ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;\n\n\t\tif ( p === ByteType ) return gl.BYTE;\n\t\tif ( p === ShortType ) return gl.SHORT;\n\t\tif ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;\n\t\tif ( p === IntType ) return gl.INT;\n\t\tif ( p === UnsignedIntType ) return gl.UNSIGNED_INT;\n\t\tif ( p === FloatType ) return gl.FLOAT;\n\n\t\tif ( p === HalfFloatType ) {\n\n\t\t\tif ( isWebGL2 ) return gl.HALF_FLOAT;\n\n\t\t\textension = extensions.get( 'OES_texture_half_float' );\n\n\t\t\tif ( extension !== null ) {\n\n\t\t\t\treturn extension.HALF_FLOAT_OES;\n\n\t\t\t} else {\n\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( p === AlphaFormat ) return gl.ALPHA;\n\t\tif ( p === RGBAFormat ) return gl.RGBA;\n\t\tif ( p === LuminanceFormat ) return gl.LUMINANCE;\n\t\tif ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;\n\t\tif ( p === DepthFormat ) return gl.DEPTH_COMPONENT;\n\t\tif ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;\n\n\t\t// WebGL 1 sRGB fallback\n\n\t\tif ( p === _SRGBAFormat ) {\n\n\t\t\textension = extensions.get( 'EXT_sRGB' );\n\n\t\t\tif ( extension !== null ) {\n\n\t\t\t\treturn extension.SRGB_ALPHA_EXT;\n\n\t\t\t} else {\n\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// WebGL2 formats.\n\n\t\tif ( p === RedFormat ) return gl.RED;\n\t\tif ( p === RedIntegerFormat ) return gl.RED_INTEGER;\n\t\tif ( p === RGFormat ) return gl.RG;\n\t\tif ( p === RGIntegerFormat ) return gl.RG_INTEGER;\n\t\tif ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;\n\n\t\t// S3TC\n\n\t\tif ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {\n\n\t\t\tif ( colorSpace === SRGBColorSpace ) {\n\n\t\t\t\textension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );\n\n\t\t\t\tif ( extension !== null ) {\n\n\t\t\t\t\tif ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;\n\t\t\t\t\tif ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;\n\t\t\t\t\tif ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;\n\t\t\t\t\tif ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;\n\n\t\t\t\t} else {\n\n\t\t\t\t\treturn null;\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\textension = extensions.get( 'WEBGL_compressed_texture_s3tc' );\n\n\t\t\t\tif ( extension !== null ) {\n\n\t\t\t\t\tif ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;\n\t\t\t\t\tif ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;\n\t\t\t\t\tif ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;\n\t\t\t\t\tif ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;\n\n\t\t\t\t} else {\n\n\t\t\t\t\treturn null;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\t// PVRTC\n\n\t\tif ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {\n\n\t\t\textension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );\n\n\t\t\tif ( extension !== null ) {\n\n\t\t\t\tif ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;\n\t\t\t\tif ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;\n\t\t\t\tif ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;\n\t\t\t\tif ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;\n\n\t\t\t} else {\n\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// ETC1\n\n\t\tif ( p === RGB_ETC1_Format ) {\n\n\t\t\textension = extensions.get( 'WEBGL_compressed_texture_etc1' );\n\n\t\t\tif ( extension !== null ) {\n\n\t\t\t\treturn extension.COMPRESSED_RGB_ETC1_WEBGL;\n\n\t\t\t} else {\n\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// ETC2\n\n\t\tif ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {\n\n\t\t\textension = extensions.get( 'WEBGL_compressed_texture_etc' );\n\n\t\t\tif ( extension !== null ) {\n\n\t\t\t\tif ( p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;\n\t\t\t\tif ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;\n\n\t\t\t} else {\n\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// ASTC\n\n\t\tif ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||\n\t\t\tp === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||\n\t\t\tp === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||\n\t\t\tp === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||\n\t\t\tp === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {\n\n\t\t\textension = extensions.get( 'WEBGL_compressed_texture_astc' );\n\n\t\t\tif ( extension !== null ) {\n\n\t\t\t\tif ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;\n\t\t\t\tif ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;\n\n\t\t\t} else {\n\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// BPTC\n\n\t\tif ( p === RGBA_BPTC_Format ) {\n\n\t\t\textension = extensions.get( 'EXT_texture_compression_bptc' );\n\n\t\t\tif ( extension !== null ) {\n\n\t\t\t\tif ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;\n\n\t\t\t} else {\n\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// RGTC\n\n\t\tif ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {\n\n\t\t\textension = extensions.get( 'EXT_texture_compression_rgtc' );\n\n\t\t\tif ( extension !== null ) {\n\n\t\t\t\tif ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;\n\t\t\t\tif ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;\n\t\t\t\tif ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;\n\t\t\t\tif ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;\n\n\t\t\t} else {\n\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t}\n\n\t\t//\n\n\t\tif ( p === UnsignedInt248Type ) {\n\n\t\t\tif ( isWebGL2 ) return gl.UNSIGNED_INT_24_8;\n\n\t\t\textension = extensions.get( 'WEBGL_depth_texture' );\n\n\t\t\tif ( extension !== null ) {\n\n\t\t\t\treturn extension.UNSIGNED_INT_24_8_WEBGL;\n\n\t\t\t} else {\n\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// if \"p\" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)\n\n\t\treturn ( gl[ p ] !== undefined ) ? gl[ p ] : null;\n\n\t}\n\n\treturn { convert: convert };\n\n}\n\nclass ArrayCamera extends PerspectiveCamera {\n\n\tconstructor( array = [] ) {\n\n\t\tsuper();\n\n\t\tthis.isArrayCamera = true;\n\n\t\tthis.cameras = array;\n\n\t}\n\n}\n\nclass Group extends Object3D {\n\n\tconstructor() {\n\n\t\tsuper();\n\n\t\tthis.isGroup = true;\n\n\t\tthis.type = 'Group';\n\n\t}\n\n}\n\nconst _moveEvent = { type: 'move' };\n\nclass WebXRController {\n\n\tconstructor() {\n\n\t\tthis._targetRay = null;\n\t\tthis._grip = null;\n\t\tthis._hand = null;\n\n\t}\n\n\tgetHandSpace() {\n\n\t\tif ( this._hand === null ) {\n\n\t\t\tthis._hand = new Group();\n\t\t\tthis._hand.matrixAutoUpdate = false;\n\t\t\tthis._hand.visible = false;\n\n\t\t\tthis._hand.joints = {};\n\t\t\tthis._hand.inputState = { pinching: false };\n\n\t\t}\n\n\t\treturn this._hand;\n\n\t}\n\n\tgetTargetRaySpace() {\n\n\t\tif ( this._targetRay === null ) {\n\n\t\t\tthis._targetRay = new Group();\n\t\t\tthis._targetRay.matrixAutoUpdate = false;\n\t\t\tthis._targetRay.visible = false;\n\t\t\tthis._targetRay.hasLinearVelocity = false;\n\t\t\tthis._targetRay.linearVelocity = new Vector3();\n\t\t\tthis._targetRay.hasAngularVelocity = false;\n\t\t\tthis._targetRay.angularVelocity = new Vector3();\n\n\t\t}\n\n\t\treturn this._targetRay;\n\n\t}\n\n\tgetGripSpace() {\n\n\t\tif ( this._grip === null ) {\n\n\t\t\tthis._grip = new Group();\n\t\t\tthis._grip.matrixAutoUpdate = false;\n\t\t\tthis._grip.visible = false;\n\t\t\tthis._grip.hasLinearVelocity = false;\n\t\t\tthis._grip.linearVelocity = new Vector3();\n\t\t\tthis._grip.hasAngularVelocity = false;\n\t\t\tthis._grip.angularVelocity = new Vector3();\n\n\t\t}\n\n\t\treturn this._grip;\n\n\t}\n\n\tdispatchEvent( event ) {\n\n\t\tif ( this._targetRay !== null ) {\n\n\t\t\tthis._targetRay.dispatchEvent( event );\n\n\t\t}\n\n\t\tif ( this._grip !== null ) {\n\n\t\t\tthis._grip.dispatchEvent( event );\n\n\t\t}\n\n\t\tif ( this._hand !== null ) {\n\n\t\t\tthis._hand.dispatchEvent( event );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tconnect( inputSource ) {\n\n\t\tif ( inputSource && inputSource.hand ) {\n\n\t\t\tconst hand = this._hand;\n\n\t\t\tif ( hand ) {\n\n\t\t\t\tfor ( const inputjoint of inputSource.hand.values() ) {\n\n\t\t\t\t\t// Initialize hand with joints when connected\n\t\t\t\t\tthis._getHandJoint( hand, inputjoint );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tthis.dispatchEvent( { type: 'connected', data: inputSource } );\n\n\t\treturn this;\n\n\t}\n\n\tdisconnect( inputSource ) {\n\n\t\tthis.dispatchEvent( { type: 'disconnected', data: inputSource } );\n\n\t\tif ( this._targetRay !== null ) {\n\n\t\t\tthis._targetRay.visible = false;\n\n\t\t}\n\n\t\tif ( this._grip !== null ) {\n\n\t\t\tthis._grip.visible = false;\n\n\t\t}\n\n\t\tif ( this._hand !== null ) {\n\n\t\t\tthis._hand.visible = false;\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tupdate( inputSource, frame, referenceSpace ) {\n\n\t\tlet inputPose = null;\n\t\tlet gripPose = null;\n\t\tlet handPose = null;\n\n\t\tconst targetRay = this._targetRay;\n\t\tconst grip = this._grip;\n\t\tconst hand = this._hand;\n\n\t\tif ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {\n\n\t\t\tif ( hand && inputSource.hand ) {\n\n\t\t\t\thandPose = true;\n\n\t\t\t\tfor ( const inputjoint of inputSource.hand.values() ) {\n\n\t\t\t\t\t// Update the joints groups with the XRJoint poses\n\t\t\t\t\tconst jointPose = frame.getJointPose( inputjoint, referenceSpace );\n\n\t\t\t\t\t// The transform of this joint will be updated with the joint pose on each frame\n\t\t\t\t\tconst joint = this._getHandJoint( hand, inputjoint );\n\n\t\t\t\t\tif ( jointPose !== null ) {\n\n\t\t\t\t\t\tjoint.matrix.fromArray( jointPose.transform.matrix );\n\t\t\t\t\t\tjoint.matrix.decompose( joint.position, joint.rotation, joint.scale );\n\t\t\t\t\t\tjoint.matrixWorldNeedsUpdate = true;\n\t\t\t\t\t\tjoint.jointRadius = jointPose.radius;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tjoint.visible = jointPose !== null;\n\n\t\t\t\t}\n\n\t\t\t\t// Custom events\n\n\t\t\t\t// Check pinchz\n\t\t\t\tconst indexTip = hand.joints[ 'index-finger-tip' ];\n\t\t\t\tconst thumbTip = hand.joints[ 'thumb-tip' ];\n\t\t\t\tconst distance = indexTip.position.distanceTo( thumbTip.position );\n\n\t\t\t\tconst distanceToPinch = 0.02;\n\t\t\t\tconst threshold = 0.005;\n\n\t\t\t\tif ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {\n\n\t\t\t\t\thand.inputState.pinching = false;\n\t\t\t\t\tthis.dispatchEvent( {\n\t\t\t\t\t\ttype: 'pinchend',\n\t\t\t\t\t\thandedness: inputSource.handedness,\n\t\t\t\t\t\ttarget: this\n\t\t\t\t\t} );\n\n\t\t\t\t} else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {\n\n\t\t\t\t\thand.inputState.pinching = true;\n\t\t\t\t\tthis.dispatchEvent( {\n\t\t\t\t\t\ttype: 'pinchstart',\n\t\t\t\t\t\thandedness: inputSource.handedness,\n\t\t\t\t\t\ttarget: this\n\t\t\t\t\t} );\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tif ( grip !== null && inputSource.gripSpace ) {\n\n\t\t\t\t\tgripPose = frame.getPose( inputSource.gripSpace, referenceSpace );\n\n\t\t\t\t\tif ( gripPose !== null ) {\n\n\t\t\t\t\t\tgrip.matrix.fromArray( gripPose.transform.matrix );\n\t\t\t\t\t\tgrip.matrix.decompose( grip.position, grip.rotation, grip.scale );\n\t\t\t\t\t\tgrip.matrixWorldNeedsUpdate = true;\n\n\t\t\t\t\t\tif ( gripPose.linearVelocity ) {\n\n\t\t\t\t\t\t\tgrip.hasLinearVelocity = true;\n\t\t\t\t\t\t\tgrip.linearVelocity.copy( gripPose.linearVelocity );\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tgrip.hasLinearVelocity = false;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ( gripPose.angularVelocity ) {\n\n\t\t\t\t\t\t\tgrip.hasAngularVelocity = true;\n\t\t\t\t\t\t\tgrip.angularVelocity.copy( gripPose.angularVelocity );\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tgrip.hasAngularVelocity = false;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( targetRay !== null ) {\n\n\t\t\t\tinputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );\n\n\t\t\t\t// Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it\n\t\t\t\tif ( inputPose === null && gripPose !== null ) {\n\n\t\t\t\t\tinputPose = gripPose;\n\n\t\t\t\t}\n\n\t\t\t\tif ( inputPose !== null ) {\n\n\t\t\t\t\ttargetRay.matrix.fromArray( inputPose.transform.matrix );\n\t\t\t\t\ttargetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );\n\t\t\t\t\ttargetRay.matrixWorldNeedsUpdate = true;\n\n\t\t\t\t\tif ( inputPose.linearVelocity ) {\n\n\t\t\t\t\t\ttargetRay.hasLinearVelocity = true;\n\t\t\t\t\t\ttargetRay.linearVelocity.copy( inputPose.linearVelocity );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\ttargetRay.hasLinearVelocity = false;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( inputPose.angularVelocity ) {\n\n\t\t\t\t\t\ttargetRay.hasAngularVelocity = true;\n\t\t\t\t\t\ttargetRay.angularVelocity.copy( inputPose.angularVelocity );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\ttargetRay.hasAngularVelocity = false;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.dispatchEvent( _moveEvent );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\t\t}\n\n\t\tif ( targetRay !== null ) {\n\n\t\t\ttargetRay.visible = ( inputPose !== null );\n\n\t\t}\n\n\t\tif ( grip !== null ) {\n\n\t\t\tgrip.visible = ( gripPose !== null );\n\n\t\t}\n\n\t\tif ( hand !== null ) {\n\n\t\t\thand.visible = ( handPose !== null );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t// private method\n\n\t_getHandJoint( hand, inputjoint ) {\n\n\t\tif ( hand.joints[ inputjoint.jointName ] === undefined ) {\n\n\t\t\tconst joint = new Group();\n\t\t\tjoint.matrixAutoUpdate = false;\n\t\t\tjoint.visible = false;\n\t\t\thand.joints[ inputjoint.jointName ] = joint;\n\n\t\t\thand.add( joint );\n\n\t\t}\n\n\t\treturn hand.joints[ inputjoint.jointName ];\n\n\t}\n\n}\n\nclass DepthTexture extends Texture {\n\n\tconstructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {\n\n\t\tformat = format !== undefined ? format : DepthFormat;\n\n\t\tif ( format !== DepthFormat && format !== DepthStencilFormat ) {\n\n\t\t\tthrow new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );\n\n\t\t}\n\n\t\tif ( type === undefined && format === DepthFormat ) type = UnsignedIntType;\n\t\tif ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;\n\n\t\tsuper( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );\n\n\t\tthis.isDepthTexture = true;\n\n\t\tthis.image = { width: width, height: height };\n\n\t\tthis.magFilter = magFilter !== undefined ? magFilter : NearestFilter;\n\t\tthis.minFilter = minFilter !== undefined ? minFilter : NearestFilter;\n\n\t\tthis.flipY = false;\n\t\tthis.generateMipmaps = false;\n\n\t}\n\n\n}\n\nclass WebXRManager extends EventDispatcher {\n\n\tconstructor( renderer, gl ) {\n\n\t\tsuper();\n\n\t\tconst scope = this;\n\n\t\tlet session = null;\n\n\t\tlet framebufferScaleFactor = 1.0;\n\n\t\tlet referenceSpace = null;\n\t\tlet referenceSpaceType = 'local-floor';\n\t\t// Set default foveation to maximum.\n\t\tlet foveation = 1.0;\n\t\tlet customReferenceSpace = null;\n\n\t\tlet pose = null;\n\t\tlet glBinding = null;\n\t\tlet glProjLayer = null;\n\t\tlet glBaseLayer = null;\n\t\tlet xrFrame = null;\n\t\tconst attributes = gl.getContextAttributes();\n\t\tlet initialRenderTarget = null;\n\t\tlet newRenderTarget = null;\n\n\t\tconst controllers = [];\n\t\tconst controllerInputSources = [];\n\n\t\tconst planes = new Set();\n\t\tconst planesLastChangedTimes = new Map();\n\n\t\t//\n\n\t\tconst cameraL = new PerspectiveCamera();\n\t\tcameraL.layers.enable( 1 );\n\t\tcameraL.viewport = new Vector4();\n\n\t\tconst cameraR = new PerspectiveCamera();\n\t\tcameraR.layers.enable( 2 );\n\t\tcameraR.viewport = new Vector4();\n\n\t\tconst cameras = [ cameraL, cameraR ];\n\n\t\tconst cameraVR = new ArrayCamera();\n\t\tcameraVR.layers.enable( 1 );\n\t\tcameraVR.layers.enable( 2 );\n\n\t\tlet _currentDepthNear = null;\n\t\tlet _currentDepthFar = null;\n\n\t\t//\n\n\t\tthis.cameraAutoUpdate = true;\n\t\tthis.enabled = false;\n\n\t\tthis.isPresenting = false;\n\n\t\tthis.getController = function ( index ) {\n\n\t\t\tlet controller = controllers[ index ];\n\n\t\t\tif ( controller === undefined ) {\n\n\t\t\t\tcontroller = new WebXRController();\n\t\t\t\tcontrollers[ index ] = controller;\n\n\t\t\t}\n\n\t\t\treturn controller.getTargetRaySpace();\n\n\t\t};\n\n\t\tthis.getControllerGrip = function ( index ) {\n\n\t\t\tlet controller = controllers[ index ];\n\n\t\t\tif ( controller === undefined ) {\n\n\t\t\t\tcontroller = new WebXRController();\n\t\t\t\tcontrollers[ index ] = controller;\n\n\t\t\t}\n\n\t\t\treturn controller.getGripSpace();\n\n\t\t};\n\n\t\tthis.getHand = function ( index ) {\n\n\t\t\tlet controller = controllers[ index ];\n\n\t\t\tif ( controller === undefined ) {\n\n\t\t\t\tcontroller = new WebXRController();\n\t\t\t\tcontrollers[ index ] = controller;\n\n\t\t\t}\n\n\t\t\treturn controller.getHandSpace();\n\n\t\t};\n\n\t\t//\n\n\t\tfunction onSessionEvent( event ) {\n\n\t\t\tconst controllerIndex = controllerInputSources.indexOf( event.inputSource );\n\n\t\t\tif ( controllerIndex === - 1 ) {\n\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tconst controller = controllers[ controllerIndex ];\n\n\t\t\tif ( controller !== undefined ) {\n\n\t\t\t\tcontroller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );\n\t\t\t\tcontroller.dispatchEvent( { type: event.type, data: event.inputSource } );\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction onSessionEnd() {\n\n\t\t\tsession.removeEventListener( 'select', onSessionEvent );\n\t\t\tsession.removeEventListener( 'selectstart', onSessionEvent );\n\t\t\tsession.removeEventListener( 'selectend', onSessionEvent );\n\t\t\tsession.removeEventListener( 'squeeze', onSessionEvent );\n\t\t\tsession.removeEventListener( 'squeezestart', onSessionEvent );\n\t\t\tsession.removeEventListener( 'squeezeend', onSessionEvent );\n\t\t\tsession.removeEventListener( 'end', onSessionEnd );\n\t\t\tsession.removeEventListener( 'inputsourceschange', onInputSourcesChange );\n\n\t\t\tfor ( let i = 0; i < controllers.length; i ++ ) {\n\n\t\t\t\tconst inputSource = controllerInputSources[ i ];\n\n\t\t\t\tif ( inputSource === null ) continue;\n\n\t\t\t\tcontrollerInputSources[ i ] = null;\n\n\t\t\t\tcontrollers[ i ].disconnect( inputSource );\n\n\t\t\t}\n\n\t\t\t_currentDepthNear = null;\n\t\t\t_currentDepthFar = null;\n\n\t\t\t// restore framebuffer/rendering state\n\n\t\t\trenderer.setRenderTarget( initialRenderTarget );\n\n\t\t\tglBaseLayer = null;\n\t\t\tglProjLayer = null;\n\t\t\tglBinding = null;\n\t\t\tsession = null;\n\t\t\tnewRenderTarget = null;\n\n\t\t\t//\n\n\t\t\tanimation.stop();\n\n\t\t\tscope.isPresenting = false;\n\n\t\t\tscope.dispatchEvent( { type: 'sessionend' } );\n\n\t\t}\n\n\t\tthis.setFramebufferScaleFactor = function ( value ) {\n\n\t\t\tframebufferScaleFactor = value;\n\n\t\t\tif ( scope.isPresenting === true ) {\n\n\t\t\t\tconsole.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );\n\n\t\t\t}\n\n\t\t};\n\n\t\tthis.setReferenceSpaceType = function ( value ) {\n\n\t\t\treferenceSpaceType = value;\n\n\t\t\tif ( scope.isPresenting === true ) {\n\n\t\t\t\tconsole.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );\n\n\t\t\t}\n\n\t\t};\n\n\t\tthis.getReferenceSpace = function () {\n\n\t\t\treturn customReferenceSpace || referenceSpace;\n\n\t\t};\n\n\t\tthis.setReferenceSpace = function ( space ) {\n\n\t\t\tcustomReferenceSpace = space;\n\n\t\t};\n\n\t\tthis.getBaseLayer = function () {\n\n\t\t\treturn glProjLayer !== null ? glProjLayer : glBaseLayer;\n\n\t\t};\n\n\t\tthis.getBinding = function () {\n\n\t\t\treturn glBinding;\n\n\t\t};\n\n\t\tthis.getFrame = function () {\n\n\t\t\treturn xrFrame;\n\n\t\t};\n\n\t\tthis.getSession = function () {\n\n\t\t\treturn session;\n\n\t\t};\n\n\t\tthis.setSession = async function ( value ) {\n\n\t\t\tsession = value;\n\n\t\t\tif ( session !== null ) {\n\n\t\t\t\tinitialRenderTarget = renderer.getRenderTarget();\n\n\t\t\t\tsession.addEventListener( 'select', onSessionEvent );\n\t\t\t\tsession.addEventListener( 'selectstart', onSessionEvent );\n\t\t\t\tsession.addEventListener( 'selectend', onSessionEvent );\n\t\t\t\tsession.addEventListener( 'squeeze', onSessionEvent );\n\t\t\t\tsession.addEventListener( 'squeezestart', onSessionEvent );\n\t\t\t\tsession.addEventListener( 'squeezeend', onSessionEvent );\n\t\t\t\tsession.addEventListener( 'end', onSessionEnd );\n\t\t\t\tsession.addEventListener( 'inputsourceschange', onInputSourcesChange );\n\n\t\t\t\tif ( attributes.xrCompatible !== true ) {\n\n\t\t\t\t\tawait gl.makeXRCompatible();\n\n\t\t\t\t}\n\n\t\t\t\tif ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {\n\n\t\t\t\t\tconst layerInit = {\n\t\t\t\t\t\tantialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,\n\t\t\t\t\t\talpha: true,\n\t\t\t\t\t\tdepth: attributes.depth,\n\t\t\t\t\t\tstencil: attributes.stencil,\n\t\t\t\t\t\tframebufferScaleFactor: framebufferScaleFactor\n\t\t\t\t\t};\n\n\t\t\t\t\tglBaseLayer = new XRWebGLLayer( session, gl, layerInit );\n\n\t\t\t\t\tsession.updateRenderState( { baseLayer: glBaseLayer } );\n\n\t\t\t\t\tnewRenderTarget = new WebGLRenderTarget(\n\t\t\t\t\t\tglBaseLayer.framebufferWidth,\n\t\t\t\t\t\tglBaseLayer.framebufferHeight,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tformat: RGBAFormat,\n\t\t\t\t\t\t\ttype: UnsignedByteType,\n\t\t\t\t\t\t\tcolorSpace: renderer.outputColorSpace,\n\t\t\t\t\t\t\tstencilBuffer: attributes.stencil\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\n\t\t\t\t} else {\n\n\t\t\t\t\tlet depthFormat = null;\n\t\t\t\t\tlet depthType = null;\n\t\t\t\t\tlet glDepthFormat = null;\n\n\t\t\t\t\tif ( attributes.depth ) {\n\n\t\t\t\t\t\tglDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;\n\t\t\t\t\t\tdepthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;\n\t\t\t\t\t\tdepthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tconst projectionlayerInit = {\n\t\t\t\t\t\tcolorFormat: gl.RGBA8,\n\t\t\t\t\t\tdepthFormat: glDepthFormat,\n\t\t\t\t\t\tscaleFactor: framebufferScaleFactor\n\t\t\t\t\t};\n\n\t\t\t\t\tglBinding = new XRWebGLBinding( session, gl );\n\n\t\t\t\t\tglProjLayer = glBinding.createProjectionLayer( projectionlayerInit );\n\n\t\t\t\t\tsession.updateRenderState( { layers: [ glProjLayer ] } );\n\n\t\t\t\t\tnewRenderTarget = new WebGLRenderTarget(\n\t\t\t\t\t\tglProjLayer.textureWidth,\n\t\t\t\t\t\tglProjLayer.textureHeight,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tformat: RGBAFormat,\n\t\t\t\t\t\t\ttype: UnsignedByteType,\n\t\t\t\t\t\t\tdepthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),\n\t\t\t\t\t\t\tstencilBuffer: attributes.stencil,\n\t\t\t\t\t\t\tcolorSpace: renderer.outputColorSpace,\n\t\t\t\t\t\t\tsamples: attributes.antialias ? 4 : 0\n\t\t\t\t\t\t} );\n\n\t\t\t\t\tconst renderTargetProperties = renderer.properties.get( newRenderTarget );\n\t\t\t\t\trenderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;\n\n\t\t\t\t}\n\n\t\t\t\tnewRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278\n\n\t\t\t\tthis.setFoveation( foveation );\n\n\t\t\t\tcustomReferenceSpace = null;\n\t\t\t\treferenceSpace = await session.requestReferenceSpace( referenceSpaceType );\n\n\t\t\t\tanimation.setContext( session );\n\t\t\t\tanimation.start();\n\n\t\t\t\tscope.isPresenting = true;\n\n\t\t\t\tscope.dispatchEvent( { type: 'sessionstart' } );\n\n\t\t\t}\n\n\t\t};\n\n\t\tthis.getEnvironmentBlendMode = function () {\n\n\t\t\tif ( session !== null ) {\n\n\t\t\t\treturn session.environmentBlendMode;\n\n\t\t\t}\n\n\t\t};\n\n\t\tfunction onInputSourcesChange( event ) {\n\n\t\t\t// Notify disconnected\n\n\t\t\tfor ( let i = 0; i < event.removed.length; i ++ ) {\n\n\t\t\t\tconst inputSource = event.removed[ i ];\n\t\t\t\tconst index = controllerInputSources.indexOf( inputSource );\n\n\t\t\t\tif ( index >= 0 ) {\n\n\t\t\t\t\tcontrollerInputSources[ index ] = null;\n\t\t\t\t\tcontrollers[ index ].disconnect( inputSource );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// Notify connected\n\n\t\t\tfor ( let i = 0; i < event.added.length; i ++ ) {\n\n\t\t\t\tconst inputSource = event.added[ i ];\n\n\t\t\t\tlet controllerIndex = controllerInputSources.indexOf( inputSource );\n\n\t\t\t\tif ( controllerIndex === - 1 ) {\n\n\t\t\t\t\t// Assign input source a controller that currently has no input source\n\n\t\t\t\t\tfor ( let i = 0; i < controllers.length; i ++ ) {\n\n\t\t\t\t\t\tif ( i >= controllerInputSources.length ) {\n\n\t\t\t\t\t\t\tcontrollerInputSources.push( inputSource );\n\t\t\t\t\t\t\tcontrollerIndex = i;\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t} else if ( controllerInputSources[ i ] === null ) {\n\n\t\t\t\t\t\t\tcontrollerInputSources[ i ] = inputSource;\n\t\t\t\t\t\t\tcontrollerIndex = i;\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// If all controllers do currently receive input we ignore new ones\n\n\t\t\t\t\tif ( controllerIndex === - 1 ) break;\n\n\t\t\t\t}\n\n\t\t\t\tconst controller = controllers[ controllerIndex ];\n\n\t\t\t\tif ( controller ) {\n\n\t\t\t\t\tcontroller.connect( inputSource );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\t//\n\n\t\tconst cameraLPos = new Vector3();\n\t\tconst cameraRPos = new Vector3();\n\n\t\t/**\n\t\t * Assumes 2 cameras that are parallel and share an X-axis, and that\n\t\t * the cameras' projection and world matrices have already been set.\n\t\t * And that near and far planes are identical for both cameras.\n\t\t * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765\n\t\t */\n\t\tfunction setProjectionFromUnion( camera, cameraL, cameraR ) {\n\n\t\t\tcameraLPos.setFromMatrixPosition( cameraL.matrixWorld );\n\t\t\tcameraRPos.setFromMatrixPosition( cameraR.matrixWorld );\n\n\t\t\tconst ipd = cameraLPos.distanceTo( cameraRPos );\n\n\t\t\tconst projL = cameraL.projectionMatrix.elements;\n\t\t\tconst projR = cameraR.projectionMatrix.elements;\n\n\t\t\t// VR systems will have identical far and near planes, and\n\t\t\t// most likely identical top and bottom frustum extents.\n\t\t\t// Use the left camera for these values.\n\t\t\tconst near = projL[ 14 ] / ( projL[ 10 ] - 1 );\n\t\t\tconst far = projL[ 14 ] / ( projL[ 10 ] + 1 );\n\t\t\tconst topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];\n\t\t\tconst bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];\n\n\t\t\tconst leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];\n\t\t\tconst rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];\n\t\t\tconst left = near * leftFov;\n\t\t\tconst right = near * rightFov;\n\n\t\t\t// Calculate the new camera's position offset from the\n\t\t\t// left camera. xOffset should be roughly half `ipd`.\n\t\t\tconst zOffset = ipd / ( - leftFov + rightFov );\n\t\t\tconst xOffset = zOffset * - leftFov;\n\n\t\t\t// TODO: Better way to apply this offset?\n\t\t\tcameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );\n\t\t\tcamera.translateX( xOffset );\n\t\t\tcamera.translateZ( zOffset );\n\t\t\tcamera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );\n\t\t\tcamera.matrixWorldInverse.copy( camera.matrixWorld ).invert();\n\n\t\t\t// Find the union of the frustum values of the cameras and scale\n\t\t\t// the values so that the near plane's position does not change in world space,\n\t\t\t// although must now be relative to the new union camera.\n\t\t\tconst near2 = near + zOffset;\n\t\t\tconst far2 = far + zOffset;\n\t\t\tconst left2 = left - xOffset;\n\t\t\tconst right2 = right + ( ipd - xOffset );\n\t\t\tconst top2 = topFov * far / far2 * near2;\n\t\t\tconst bottom2 = bottomFov * far / far2 * near2;\n\n\t\t\tcamera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );\n\t\t\tcamera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();\n\n\t\t}\n\n\t\tfunction updateCamera( camera, parent ) {\n\n\t\t\tif ( parent === null ) {\n\n\t\t\t\tcamera.matrixWorld.copy( camera.matrix );\n\n\t\t\t} else {\n\n\t\t\t\tcamera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );\n\n\t\t\t}\n\n\t\t\tcamera.matrixWorldInverse.copy( camera.matrixWorld ).invert();\n\n\t\t}\n\n\t\tthis.updateCamera = function ( camera ) {\n\n\t\t\tif ( session === null ) return;\n\n\t\t\tcameraVR.near = cameraR.near = cameraL.near = camera.near;\n\t\t\tcameraVR.far = cameraR.far = cameraL.far = camera.far;\n\n\t\t\tif ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {\n\n\t\t\t\t// Note that the new renderState won't apply until the next frame. See #18320\n\n\t\t\t\tsession.updateRenderState( {\n\t\t\t\t\tdepthNear: cameraVR.near,\n\t\t\t\t\tdepthFar: cameraVR.far\n\t\t\t\t} );\n\n\t\t\t\t_currentDepthNear = cameraVR.near;\n\t\t\t\t_currentDepthFar = cameraVR.far;\n\n\t\t\t}\n\n\t\t\tconst parent = camera.parent;\n\t\t\tconst cameras = cameraVR.cameras;\n\n\t\t\tupdateCamera( cameraVR, parent );\n\n\t\t\tfor ( let i = 0; i < cameras.length; i ++ ) {\n\n\t\t\t\tupdateCamera( cameras[ i ], parent );\n\n\t\t\t}\n\n\t\t\t// update projection matrix for proper view frustum culling\n\n\t\t\tif ( cameras.length === 2 ) {\n\n\t\t\t\tsetProjectionFromUnion( cameraVR, cameraL, cameraR );\n\n\t\t\t} else {\n\n\t\t\t\t// assume single camera setup (AR)\n\n\t\t\t\tcameraVR.projectionMatrix.copy( cameraL.projectionMatrix );\n\n\t\t\t}\n\n\t\t\t// update user camera and its children\n\n\t\t\tupdateUserCamera( camera, cameraVR, parent );\n\n\t\t};\n\n\t\tfunction updateUserCamera( camera, cameraVR, parent ) {\n\n\t\t\tif ( parent === null ) {\n\n\t\t\t\tcamera.matrix.copy( cameraVR.matrixWorld );\n\n\t\t\t} else {\n\n\t\t\t\tcamera.matrix.copy( parent.matrixWorld );\n\t\t\t\tcamera.matrix.invert();\n\t\t\t\tcamera.matrix.multiply( cameraVR.matrixWorld );\n\n\t\t\t}\n\n\t\t\tcamera.matrix.decompose( camera.position, camera.quaternion, camera.scale );\n\t\t\tcamera.updateMatrixWorld( true );\n\n\t\t\tconst children = camera.children;\n\n\t\t\tfor ( let i = 0, l = children.length; i < l; i ++ ) {\n\n\t\t\t\tchildren[ i ].updateMatrixWorld( true );\n\n\t\t\t}\n\n\t\t\tcamera.projectionMatrix.copy( cameraVR.projectionMatrix );\n\t\t\tcamera.projectionMatrixInverse.copy( cameraVR.projectionMatrixInverse );\n\n\t\t\tif ( camera.isPerspectiveCamera ) {\n\n\t\t\t\tcamera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );\n\t\t\t\tcamera.zoom = 1;\n\n\t\t\t}\n\n\t\t}\n\n\t\tthis.getCamera = function () {\n\n\t\t\treturn cameraVR;\n\n\t\t};\n\n\t\tthis.getFoveation = function () {\n\n\t\t\tif ( glProjLayer === null && glBaseLayer === null ) {\n\n\t\t\t\treturn undefined;\n\n\t\t\t}\n\n\t\t\treturn foveation;\n\n\t\t};\n\n\t\tthis.setFoveation = function ( value ) {\n\n\t\t\t// 0 = no foveation = full resolution\n\t\t\t// 1 = maximum foveation = the edges render at lower resolution\n\n\t\t\tfoveation = value;\n\n\t\t\tif ( glProjLayer !== null ) {\n\n\t\t\t\tglProjLayer.fixedFoveation = value;\n\n\t\t\t}\n\n\t\t\tif ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {\n\n\t\t\t\tglBaseLayer.fixedFoveation = value;\n\n\t\t\t}\n\n\t\t};\n\n\t\tthis.getPlanes = function () {\n\n\t\t\treturn planes;\n\n\t\t};\n\n\t\t// Animation Loop\n\n\t\tlet onAnimationFrameCallback = null;\n\n\t\tfunction onAnimationFrame( time, frame ) {\n\n\t\t\tpose = frame.getViewerPose( customReferenceSpace || referenceSpace );\n\t\t\txrFrame = frame;\n\n\t\t\tif ( pose !== null ) {\n\n\t\t\t\tconst views = pose.views;\n\n\t\t\t\tif ( glBaseLayer !== null ) {\n\n\t\t\t\t\trenderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );\n\t\t\t\t\trenderer.setRenderTarget( newRenderTarget );\n\n\t\t\t\t}\n\n\t\t\t\tlet cameraVRNeedsUpdate = false;\n\n\t\t\t\t// check if it's necessary to rebuild cameraVR's camera list\n\n\t\t\t\tif ( views.length !== cameraVR.cameras.length ) {\n\n\t\t\t\t\tcameraVR.cameras.length = 0;\n\t\t\t\t\tcameraVRNeedsUpdate = true;\n\n\t\t\t\t}\n\n\t\t\t\tfor ( let i = 0; i < views.length; i ++ ) {\n\n\t\t\t\t\tconst view = views[ i ];\n\n\t\t\t\t\tlet viewport = null;\n\n\t\t\t\t\tif ( glBaseLayer !== null ) {\n\n\t\t\t\t\t\tviewport = glBaseLayer.getViewport( view );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tconst glSubImage = glBinding.getViewSubImage( glProjLayer, view );\n\t\t\t\t\t\tviewport = glSubImage.viewport;\n\n\t\t\t\t\t\t// For side-by-side projection, we only produce a single texture for both eyes.\n\t\t\t\t\t\tif ( i === 0 ) {\n\n\t\t\t\t\t\t\trenderer.setRenderTargetTextures(\n\t\t\t\t\t\t\t\tnewRenderTarget,\n\t\t\t\t\t\t\t\tglSubImage.colorTexture,\n\t\t\t\t\t\t\t\tglProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );\n\n\t\t\t\t\t\t\trenderer.setRenderTarget( newRenderTarget );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tlet camera = cameras[ i ];\n\n\t\t\t\t\tif ( camera === undefined ) {\n\n\t\t\t\t\t\tcamera = new PerspectiveCamera();\n\t\t\t\t\t\tcamera.layers.enable( i );\n\t\t\t\t\t\tcamera.viewport = new Vector4();\n\t\t\t\t\t\tcameras[ i ] = camera;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tcamera.matrix.fromArray( view.transform.matrix );\n\t\t\t\t\tcamera.matrix.decompose( camera.position, camera.quaternion, camera.scale );\n\t\t\t\t\tcamera.projectionMatrix.fromArray( view.projectionMatrix );\n\t\t\t\t\tcamera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();\n\t\t\t\t\tcamera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );\n\n\t\t\t\t\tif ( i === 0 ) {\n\n\t\t\t\t\t\tcameraVR.matrix.copy( camera.matrix );\n\t\t\t\t\t\tcameraVR.matrix.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( cameraVRNeedsUpdate === true ) {\n\n\t\t\t\t\t\tcameraVR.cameras.push( camera );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t//\n\n\t\t\tfor ( let i = 0; i < controllers.length; i ++ ) {\n\n\t\t\t\tconst inputSource = controllerInputSources[ i ];\n\t\t\t\tconst controller = controllers[ i ];\n\n\t\t\t\tif ( inputSource !== null && controller !== undefined ) {\n\n\t\t\t\t\tcontroller.update( inputSource, frame, customReferenceSpace || referenceSpace );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );\n\n\t\t\tif ( frame.detectedPlanes ) {\n\n\t\t\t\tscope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } );\n\n\t\t\t\tlet planesToRemove = null;\n\n\t\t\t\tfor ( const plane of planes ) {\n\n\t\t\t\t\tif ( ! frame.detectedPlanes.has( plane ) ) {\n\n\t\t\t\t\t\tif ( planesToRemove === null ) {\n\n\t\t\t\t\t\t\tplanesToRemove = [];\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tplanesToRemove.push( plane );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif ( planesToRemove !== null ) {\n\n\t\t\t\t\tfor ( const plane of planesToRemove ) {\n\n\t\t\t\t\t\tplanes.delete( plane );\n\t\t\t\t\t\tplanesLastChangedTimes.delete( plane );\n\t\t\t\t\t\tscope.dispatchEvent( { type: 'planeremoved', data: plane } );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tfor ( const plane of frame.detectedPlanes ) {\n\n\t\t\t\t\tif ( ! planes.has( plane ) ) {\n\n\t\t\t\t\t\tplanes.add( plane );\n\t\t\t\t\t\tplanesLastChangedTimes.set( plane, frame.lastChangedTime );\n\t\t\t\t\t\tscope.dispatchEvent( { type: 'planeadded', data: plane } );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tconst lastKnownTime = planesLastChangedTimes.get( plane );\n\n\t\t\t\t\t\tif ( plane.lastChangedTime > lastKnownTime ) {\n\n\t\t\t\t\t\t\tplanesLastChangedTimes.set( plane, plane.lastChangedTime );\n\t\t\t\t\t\t\tscope.dispatchEvent( { type: 'planechanged', data: plane } );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\txrFrame = null;\n\n\t\t}\n\n\t\tconst animation = new WebGLAnimation();\n\n\t\tanimation.setAnimationLoop( onAnimationFrame );\n\n\t\tthis.setAnimationLoop = function ( callback ) {\n\n\t\t\tonAnimationFrameCallback = callback;\n\n\t\t};\n\n\t\tthis.dispose = function () {};\n\n\t}\n\n}\n\nfunction WebGLMaterials( renderer, properties ) {\n\n\tfunction refreshTransformUniform( map, uniform ) {\n\n\t\tif ( map.matrixAutoUpdate === true ) {\n\n\t\t\tmap.updateMatrix();\n\n\t\t}\n\n\t\tuniform.value.copy( map.matrix );\n\n\t}\n\n\tfunction refreshFogUniforms( uniforms, fog ) {\n\n\t\tfog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );\n\n\t\tif ( fog.isFog ) {\n\n\t\t\tuniforms.fogNear.value = fog.near;\n\t\t\tuniforms.fogFar.value = fog.far;\n\n\t\t} else if ( fog.isFogExp2 ) {\n\n\t\t\tuniforms.fogDensity.value = fog.density;\n\n\t\t}\n\n\t}\n\n\tfunction refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {\n\n\t\tif ( material.isMeshBasicMaterial ) {\n\n\t\t\trefreshUniformsCommon( uniforms, material );\n\n\t\t} else if ( material.isMeshLambertMaterial ) {\n\n\t\t\trefreshUniformsCommon( uniforms, material );\n\n\t\t} else if ( material.isMeshToonMaterial ) {\n\n\t\t\trefreshUniformsCommon( uniforms, material );\n\t\t\trefreshUniformsToon( uniforms, material );\n\n\t\t} else if ( material.isMeshPhongMaterial ) {\n\n\t\t\trefreshUniformsCommon( uniforms, material );\n\t\t\trefreshUniformsPhong( uniforms, material );\n\n\t\t} else if ( material.isMeshStandardMaterial ) {\n\n\t\t\trefreshUniformsCommon( uniforms, material );\n\t\t\trefreshUniformsStandard( uniforms, material );\n\n\t\t\tif ( material.isMeshPhysicalMaterial ) {\n\n\t\t\t\trefreshUniformsPhysical( uniforms, material, transmissionRenderTarget );\n\n\t\t\t}\n\n\t\t} else if ( material.isMeshMatcapMaterial ) {\n\n\t\t\trefreshUniformsCommon( uniforms, material );\n\t\t\trefreshUniformsMatcap( uniforms, material );\n\n\t\t} else if ( material.isMeshDepthMaterial ) {\n\n\t\t\trefreshUniformsCommon( uniforms, material );\n\n\t\t} else if ( material.isMeshDistanceMaterial ) {\n\n\t\t\trefreshUniformsCommon( uniforms, material );\n\t\t\trefreshUniformsDistance( uniforms, material );\n\n\t\t} else if ( material.isMeshNormalMaterial ) {\n\n\t\t\trefreshUniformsCommon( uniforms, material );\n\n\t\t} else if ( material.isLineBasicMaterial ) {\n\n\t\t\trefreshUniformsLine( uniforms, material );\n\n\t\t\tif ( material.isLineDashedMaterial ) {\n\n\t\t\t\trefreshUniformsDash( uniforms, material );\n\n\t\t\t}\n\n\t\t} else if ( material.isPointsMaterial ) {\n\n\t\t\trefreshUniformsPoints( uniforms, material, pixelRatio, height );\n\n\t\t} else if ( material.isSpriteMaterial ) {\n\n\t\t\trefreshUniformsSprites( uniforms, material );\n\n\t\t} else if ( material.isShadowMaterial ) {\n\n\t\t\tuniforms.color.value.copy( material.color );\n\t\t\tuniforms.opacity.value = material.opacity;\n\n\t\t} else if ( material.isShaderMaterial ) {\n\n\t\t\tmaterial.uniformsNeedUpdate = false; // #15581\n\n\t\t}\n\n\t}\n\n\tfunction refreshUniformsCommon( uniforms, material ) {\n\n\t\tuniforms.opacity.value = material.opacity;\n\n\t\tif ( material.color ) {\n\n\t\t\tuniforms.diffuse.value.copy( material.color );\n\n\t\t}\n\n\t\tif ( material.emissive ) {\n\n\t\t\tuniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );\n\n\t\t}\n\n\t\tif ( material.map ) {\n\n\t\t\tuniforms.map.value = material.map;\n\n\t\t\trefreshTransformUniform( material.map, uniforms.mapTransform );\n\n\t\t}\n\n\t\tif ( material.alphaMap ) {\n\n\t\t\tuniforms.alphaMap.value = material.alphaMap;\n\n\t\t\trefreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );\n\n\t\t}\n\n\t\tif ( material.bumpMap ) {\n\n\t\t\tuniforms.bumpMap.value = material.bumpMap;\n\n\t\t\trefreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );\n\n\t\t\tuniforms.bumpScale.value = material.bumpScale;\n\n\t\t\tif ( material.side === BackSide ) {\n\n\t\t\t\tuniforms.bumpScale.value *= - 1;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( material.normalMap ) {\n\n\t\t\tuniforms.normalMap.value = material.normalMap;\n\n\t\t\trefreshTransformUniform( material.normalMap, uniforms.normalMapTransform );\n\n\t\t\tuniforms.normalScale.value.copy( material.normalScale );\n\n\t\t\tif ( material.side === BackSide ) {\n\n\t\t\t\tuniforms.normalScale.value.negate();\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( material.displacementMap ) {\n\n\t\t\tuniforms.displacementMap.value = material.displacementMap;\n\n\t\t\trefreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );\n\n\t\t\tuniforms.displacementScale.value = material.displacementScale;\n\t\t\tuniforms.displacementBias.value = material.displacementBias;\n\n\t\t}\n\n\t\tif ( material.emissiveMap ) {\n\n\t\t\tuniforms.emissiveMap.value = material.emissiveMap;\n\n\t\t\trefreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );\n\n\t\t}\n\n\t\tif ( material.specularMap ) {\n\n\t\t\tuniforms.specularMap.value = material.specularMap;\n\n\t\t\trefreshTransformUniform( material.specularMap, uniforms.specularMapTransform );\n\n\t\t}\n\n\t\tif ( material.alphaTest > 0 ) {\n\n\t\t\tuniforms.alphaTest.value = material.alphaTest;\n\n\t\t}\n\n\t\tconst envMap = properties.get( material ).envMap;\n\n\t\tif ( envMap ) {\n\n\t\t\tuniforms.envMap.value = envMap;\n\n\t\t\tuniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;\n\n\t\t\tuniforms.reflectivity.value = material.reflectivity;\n\t\t\tuniforms.ior.value = material.ior;\n\t\t\tuniforms.refractionRatio.value = material.refractionRatio;\n\n\t\t}\n\n\t\tif ( material.lightMap ) {\n\n\t\t\tuniforms.lightMap.value = material.lightMap;\n\n\t\t\t// artist-friendly light intensity scaling factor\n\t\t\tconst scaleFactor = ( renderer.useLegacyLights === true ) ? Math.PI : 1;\n\n\t\t\tuniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;\n\n\t\t\trefreshTransformUniform( material.lightMap, uniforms.lightMapTransform );\n\n\t\t}\n\n\t\tif ( material.aoMap ) {\n\n\t\t\tuniforms.aoMap.value = material.aoMap;\n\t\t\tuniforms.aoMapIntensity.value = material.aoMapIntensity;\n\n\t\t\trefreshTransformUniform( material.aoMap, uniforms.aoMapTransform );\n\n\t\t}\n\n\t}\n\n\tfunction refreshUniformsLine( uniforms, material ) {\n\n\t\tuniforms.diffuse.value.copy( material.color );\n\t\tuniforms.opacity.value = material.opacity;\n\n\t\tif ( material.map ) {\n\n\t\t\tuniforms.map.value = material.map;\n\n\t\t\trefreshTransformUniform( material.map, uniforms.mapTransform );\n\n\t\t}\n\n\t}\n\n\tfunction refreshUniformsDash( uniforms, material ) {\n\n\t\tuniforms.dashSize.value = material.dashSize;\n\t\tuniforms.totalSize.value = material.dashSize + material.gapSize;\n\t\tuniforms.scale.value = material.scale;\n\n\t}\n\n\tfunction refreshUniformsPoints( uniforms, material, pixelRatio, height ) {\n\n\t\tuniforms.diffuse.value.copy( material.color );\n\t\tuniforms.opacity.value = material.opacity;\n\t\tuniforms.size.value = material.size * pixelRatio;\n\t\tuniforms.scale.value = height * 0.5;\n\n\t\tif ( material.map ) {\n\n\t\t\tuniforms.map.value = material.map;\n\n\t\t\trefreshTransformUniform( material.map, uniforms.uvTransform );\n\n\t\t}\n\n\t\tif ( material.alphaMap ) {\n\n\t\t\tuniforms.alphaMap.value = material.alphaMap;\n\n\t\t}\n\n\t\tif ( material.alphaTest > 0 ) {\n\n\t\t\tuniforms.alphaTest.value = material.alphaTest;\n\n\t\t}\n\n\t}\n\n\tfunction refreshUniformsSprites( uniforms, material ) {\n\n\t\tuniforms.diffuse.value.copy( material.color );\n\t\tuniforms.opacity.value = material.opacity;\n\t\tuniforms.rotation.value = material.rotation;\n\n\t\tif ( material.map ) {\n\n\t\t\tuniforms.map.value = material.map;\n\n\t\t\trefreshTransformUniform( material.map, uniforms.mapTransform );\n\n\t\t}\n\n\t\tif ( material.alphaMap ) {\n\n\t\t\tuniforms.alphaMap.value = material.alphaMap;\n\n\t\t}\n\n\t\tif ( material.alphaTest > 0 ) {\n\n\t\t\tuniforms.alphaTest.value = material.alphaTest;\n\n\t\t}\n\n\t}\n\n\tfunction refreshUniformsPhong( uniforms, material ) {\n\n\t\tuniforms.specular.value.copy( material.specular );\n\t\tuniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )\n\n\t}\n\n\tfunction refreshUniformsToon( uniforms, material ) {\n\n\t\tif ( material.gradientMap ) {\n\n\t\t\tuniforms.gradientMap.value = material.gradientMap;\n\n\t\t}\n\n\t}\n\n\tfunction refreshUniformsStandard( uniforms, material ) {\n\n\t\tuniforms.metalness.value = material.metalness;\n\n\t\tif ( material.metalnessMap ) {\n\n\t\t\tuniforms.metalnessMap.value = material.metalnessMap;\n\n\t\t\trefreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );\n\n\t\t}\n\n\t\tuniforms.roughness.value = material.roughness;\n\n\t\tif ( material.roughnessMap ) {\n\n\t\t\tuniforms.roughnessMap.value = material.roughnessMap;\n\n\t\t\trefreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );\n\n\t\t}\n\n\t\tconst envMap = properties.get( material ).envMap;\n\n\t\tif ( envMap ) {\n\n\t\t\t//uniforms.envMap.value = material.envMap; // part of uniforms common\n\t\t\tuniforms.envMapIntensity.value = material.envMapIntensity;\n\n\t\t}\n\n\t}\n\n\tfunction refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {\n\n\t\tuniforms.ior.value = material.ior; // also part of uniforms common\n\n\t\tif ( material.sheen > 0 ) {\n\n\t\t\tuniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );\n\n\t\t\tuniforms.sheenRoughness.value = material.sheenRoughness;\n\n\t\t\tif ( material.sheenColorMap ) {\n\n\t\t\t\tuniforms.sheenColorMap.value = material.sheenColorMap;\n\n\t\t\t\trefreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );\n\n\t\t\t}\n\n\t\t\tif ( material.sheenRoughnessMap ) {\n\n\t\t\t\tuniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;\n\n\t\t\t\trefreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( material.clearcoat > 0 ) {\n\n\t\t\tuniforms.clearcoat.value = material.clearcoat;\n\t\t\tuniforms.clearcoatRoughness.value = material.clearcoatRoughness;\n\n\t\t\tif ( material.clearcoatMap ) {\n\n\t\t\t\tuniforms.clearcoatMap.value = material.clearcoatMap;\n\n\t\t\t\trefreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );\n\n\t\t\t}\n\n\t\t\tif ( material.clearcoatRoughnessMap ) {\n\n\t\t\t\tuniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;\n\n\t\t\t\trefreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );\n\n\t\t\t}\n\n\t\t\tif ( material.clearcoatNormalMap ) {\n\n\t\t\t\tuniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;\n\n\t\t\t\trefreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );\n\n\t\t\t\tuniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );\n\n\t\t\t\tif ( material.side === BackSide ) {\n\n\t\t\t\t\tuniforms.clearcoatNormalScale.value.negate();\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( material.iridescence > 0 ) {\n\n\t\t\tuniforms.iridescence.value = material.iridescence;\n\t\t\tuniforms.iridescenceIOR.value = material.iridescenceIOR;\n\t\t\tuniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];\n\t\t\tuniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];\n\n\t\t\tif ( material.iridescenceMap ) {\n\n\t\t\t\tuniforms.iridescenceMap.value = material.iridescenceMap;\n\n\t\t\t\trefreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );\n\n\t\t\t}\n\n\t\t\tif ( material.iridescenceThicknessMap ) {\n\n\t\t\t\tuniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;\n\n\t\t\t\trefreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( material.transmission > 0 ) {\n\n\t\t\tuniforms.transmission.value = material.transmission;\n\t\t\tuniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;\n\t\t\tuniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );\n\n\t\t\tif ( material.transmissionMap ) {\n\n\t\t\t\tuniforms.transmissionMap.value = material.transmissionMap;\n\n\t\t\t\trefreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );\n\n\t\t\t}\n\n\t\t\tuniforms.thickness.value = material.thickness;\n\n\t\t\tif ( material.thicknessMap ) {\n\n\t\t\t\tuniforms.thicknessMap.value = material.thicknessMap;\n\n\t\t\t\trefreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );\n\n\t\t\t}\n\n\t\t\tuniforms.attenuationDistance.value = material.attenuationDistance;\n\t\t\tuniforms.attenuationColor.value.copy( material.attenuationColor );\n\n\t\t}\n\n\t\tuniforms.specularIntensity.value = material.specularIntensity;\n\t\tuniforms.specularColor.value.copy( material.specularColor );\n\n\t\tif ( material.specularColorMap ) {\n\n\t\t\tuniforms.specularColorMap.value = material.specularColorMap;\n\n\t\t\trefreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );\n\n\t\t}\n\n\t\tif ( material.specularIntensityMap ) {\n\n\t\t\tuniforms.specularIntensityMap.value = material.specularIntensityMap;\n\n\t\t\trefreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );\n\n\t\t}\n\n\t}\n\n\tfunction refreshUniformsMatcap( uniforms, material ) {\n\n\t\tif ( material.matcap ) {\n\n\t\t\tuniforms.matcap.value = material.matcap;\n\n\t\t}\n\n\t}\n\n\tfunction refreshUniformsDistance( uniforms, material ) {\n\n\t\tconst light = properties.get( material ).light;\n\n\t\tuniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );\n\t\tuniforms.nearDistance.value = light.shadow.camera.near;\n\t\tuniforms.farDistance.value = light.shadow.camera.far;\n\n\t}\n\n\treturn {\n\t\trefreshFogUniforms: refreshFogUniforms,\n\t\trefreshMaterialUniforms: refreshMaterialUniforms\n\t};\n\n}\n\nfunction WebGLUniformsGroups( gl, info, capabilities, state ) {\n\n\tlet buffers = {};\n\tlet updateList = {};\n\tlet allocatedBindingPoints = [];\n\n\tconst maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program\n\n\tfunction bind( uniformsGroup, program ) {\n\n\t\tconst webglProgram = program.program;\n\t\tstate.uniformBlockBinding( uniformsGroup, webglProgram );\n\n\t}\n\n\tfunction update( uniformsGroup, program ) {\n\n\t\tlet buffer = buffers[ uniformsGroup.id ];\n\n\t\tif ( buffer === undefined ) {\n\n\t\t\tprepareUniformsGroup( uniformsGroup );\n\n\t\t\tbuffer = createBuffer( uniformsGroup );\n\t\t\tbuffers[ uniformsGroup.id ] = buffer;\n\n\t\t\tuniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );\n\n\t\t}\n\n\t\t// ensure to update the binding points/block indices mapping for this program\n\n\t\tconst webglProgram = program.program;\n\t\tstate.updateUBOMapping( uniformsGroup, webglProgram );\n\n\t\t// update UBO once per frame\n\n\t\tconst frame = info.render.frame;\n\n\t\tif ( updateList[ uniformsGroup.id ] !== frame ) {\n\n\t\t\tupdateBufferData( uniformsGroup );\n\n\t\t\tupdateList[ uniformsGroup.id ] = frame;\n\n\t\t}\n\n\t}\n\n\tfunction createBuffer( uniformsGroup ) {\n\n\t\t// the setup of an UBO is independent of a particular shader program but global\n\n\t\tconst bindingPointIndex = allocateBindingPointIndex();\n\t\tuniformsGroup.__bindingPointIndex = bindingPointIndex;\n\n\t\tconst buffer = gl.createBuffer();\n\t\tconst size = uniformsGroup.__size;\n\t\tconst usage = uniformsGroup.usage;\n\n\t\tgl.bindBuffer( gl.UNIFORM_BUFFER, buffer );\n\t\tgl.bufferData( gl.UNIFORM_BUFFER, size, usage );\n\t\tgl.bindBuffer( gl.UNIFORM_BUFFER, null );\n\t\tgl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );\n\n\t\treturn buffer;\n\n\t}\n\n\tfunction allocateBindingPointIndex() {\n\n\t\tfor ( let i = 0; i < maxBindingPoints; i ++ ) {\n\n\t\t\tif ( allocatedBindingPoints.indexOf( i ) === - 1 ) {\n\n\t\t\t\tallocatedBindingPoints.push( i );\n\t\t\t\treturn i;\n\n\t\t\t}\n\n\t\t}\n\n\t\tconsole.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );\n\n\t\treturn 0;\n\n\t}\n\n\tfunction updateBufferData( uniformsGroup ) {\n\n\t\tconst buffer = buffers[ uniformsGroup.id ];\n\t\tconst uniforms = uniformsGroup.uniforms;\n\t\tconst cache = uniformsGroup.__cache;\n\n\t\tgl.bindBuffer( gl.UNIFORM_BUFFER, buffer );\n\n\t\tfor ( let i = 0, il = uniforms.length; i < il; i ++ ) {\n\n\t\t\tconst uniform = uniforms[ i ];\n\n\t\t\t// partly update the buffer if necessary\n\n\t\t\tif ( hasUniformChanged( uniform, i, cache ) === true ) {\n\n\t\t\t\tconst offset = uniform.__offset;\n\n\t\t\t\tconst values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];\n\n\t\t\t\tlet arrayOffset = 0;\n\n\t\t\t\tfor ( let i = 0; i < values.length; i ++ ) {\n\n\t\t\t\t\tconst value = values[ i ];\n\n\t\t\t\t\tconst info = getUniformSize( value );\n\n\t\t\t\t\tif ( typeof value === 'number' ) {\n\n\t\t\t\t\t\tuniform.__data[ 0 ] = value;\n\t\t\t\t\t\tgl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );\n\n\t\t\t\t\t} else if ( value.isMatrix3 ) {\n\n\t\t\t\t\t\t// manually converting 3x3 to 3x4\n\n\t\t\t\t\t\tuniform.__data[ 0 ] = value.elements[ 0 ];\n\t\t\t\t\t\tuniform.__data[ 1 ] = value.elements[ 1 ];\n\t\t\t\t\t\tuniform.__data[ 2 ] = value.elements[ 2 ];\n\t\t\t\t\t\tuniform.__data[ 3 ] = value.elements[ 0 ];\n\t\t\t\t\t\tuniform.__data[ 4 ] = value.elements[ 3 ];\n\t\t\t\t\t\tuniform.__data[ 5 ] = value.elements[ 4 ];\n\t\t\t\t\t\tuniform.__data[ 6 ] = value.elements[ 5 ];\n\t\t\t\t\t\tuniform.__data[ 7 ] = value.elements[ 0 ];\n\t\t\t\t\t\tuniform.__data[ 8 ] = value.elements[ 6 ];\n\t\t\t\t\t\tuniform.__data[ 9 ] = value.elements[ 7 ];\n\t\t\t\t\t\tuniform.__data[ 10 ] = value.elements[ 8 ];\n\t\t\t\t\t\tuniform.__data[ 11 ] = value.elements[ 0 ];\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tvalue.toArray( uniform.__data, arrayOffset );\n\n\t\t\t\t\t\tarrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tgl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );\n\n\t\t\t}\n\n\t\t}\n\n\t\tgl.bindBuffer( gl.UNIFORM_BUFFER, null );\n\n\t}\n\n\tfunction hasUniformChanged( uniform, index, cache ) {\n\n\t\tconst value = uniform.value;\n\n\t\tif ( cache[ index ] === undefined ) {\n\n\t\t\t// cache entry does not exist so far\n\n\t\t\tif ( typeof value === 'number' ) {\n\n\t\t\t\tcache[ index ] = value;\n\n\t\t\t} else {\n\n\t\t\t\tconst values = Array.isArray( value ) ? value : [ value ];\n\n\t\t\t\tconst tempValues = [];\n\n\t\t\t\tfor ( let i = 0; i < values.length; i ++ ) {\n\n\t\t\t\t\ttempValues.push( values[ i ].clone() );\n\n\t\t\t\t}\n\n\t\t\t\tcache[ index ] = tempValues;\n\n\t\t\t}\n\n\t\t\treturn true;\n\n\t\t} else {\n\n\t\t\t// compare current value with cached entry\n\n\t\t\tif ( typeof value === 'number' ) {\n\n\t\t\t\tif ( cache[ index ] !== value ) {\n\n\t\t\t\t\tcache[ index ] = value;\n\t\t\t\t\treturn true;\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tconst cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];\n\t\t\t\tconst values = Array.isArray( value ) ? value : [ value ];\n\n\t\t\t\tfor ( let i = 0; i < cachedObjects.length; i ++ ) {\n\n\t\t\t\t\tconst cachedObject = cachedObjects[ i ];\n\n\t\t\t\t\tif ( cachedObject.equals( values[ i ] ) === false ) {\n\n\t\t\t\t\t\tcachedObject.copy( values[ i ] );\n\t\t\t\t\t\treturn true;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn false;\n\n\t}\n\n\tfunction prepareUniformsGroup( uniformsGroup ) {\n\n\t\t// determine total buffer size according to the STD140 layout\n\t\t// Hint: STD140 is the only supported layout in WebGL 2\n\n\t\tconst uniforms = uniformsGroup.uniforms;\n\n\t\tlet offset = 0; // global buffer offset in bytes\n\t\tconst chunkSize = 16; // size of a chunk in bytes\n\t\tlet chunkOffset = 0; // offset within a single chunk in bytes\n\n\t\tfor ( let i = 0, l = uniforms.length; i < l; i ++ ) {\n\n\t\t\tconst uniform = uniforms[ i ];\n\n\t\t\tconst infos = {\n\t\t\t\tboundary: 0, // bytes\n\t\t\t\tstorage: 0 // bytes\n\t\t\t};\n\n\t\t\tconst values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];\n\n\t\t\tfor ( let j = 0, jl = values.length; j < jl; j ++ ) {\n\n\t\t\t\tconst value = values[ j ];\n\n\t\t\t\tconst info = getUniformSize( value );\n\n\t\t\t\tinfos.boundary += info.boundary;\n\t\t\t\tinfos.storage += info.storage;\n\n\t\t\t}\n\n\t\t\t// the following two properties will be used for partial buffer updates\n\n\t\t\tuniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );\n\t\t\tuniform.__offset = offset;\n\n\t\t\t//\n\n\t\t\tif ( i > 0 ) {\n\n\t\t\t\tchunkOffset = offset % chunkSize;\n\n\t\t\t\tconst remainingSizeInChunk = chunkSize - chunkOffset;\n\n\t\t\t\t// check for chunk overflow\n\n\t\t\t\tif ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {\n\n\t\t\t\t\t// add padding and adjust offset\n\n\t\t\t\t\toffset += ( chunkSize - chunkOffset );\n\t\t\t\t\tuniform.__offset = offset;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\toffset += infos.storage;\n\n\t\t}\n\n\t\t// ensure correct final padding\n\n\t\tchunkOffset = offset % chunkSize;\n\n\t\tif ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );\n\n\t\t//\n\n\t\tuniformsGroup.__size = offset;\n\t\tuniformsGroup.__cache = {};\n\n\t\treturn this;\n\n\t}\n\n\tfunction getUniformSize( value ) {\n\n\t\tconst info = {\n\t\t\tboundary: 0, // bytes\n\t\t\tstorage: 0 // bytes\n\t\t};\n\n\t\t// determine sizes according to STD140\n\n\t\tif ( typeof value === 'number' ) {\n\n\t\t\t// float/int\n\n\t\t\tinfo.boundary = 4;\n\t\t\tinfo.storage = 4;\n\n\t\t} else if ( value.isVector2 ) {\n\n\t\t\t// vec2\n\n\t\t\tinfo.boundary = 8;\n\t\t\tinfo.storage = 8;\n\n\t\t} else if ( value.isVector3 || value.isColor ) {\n\n\t\t\t// vec3\n\n\t\t\tinfo.boundary = 16;\n\t\t\tinfo.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes\n\n\t\t} else if ( value.isVector4 ) {\n\n\t\t\t// vec4\n\n\t\t\tinfo.boundary = 16;\n\t\t\tinfo.storage = 16;\n\n\t\t} else if ( value.isMatrix3 ) {\n\n\t\t\t// mat3 (in STD140 a 3x3 matrix is represented as 3x4)\n\n\t\t\tinfo.boundary = 48;\n\t\t\tinfo.storage = 48;\n\n\t\t} else if ( value.isMatrix4 ) {\n\n\t\t\t// mat4\n\n\t\t\tinfo.boundary = 64;\n\t\t\tinfo.storage = 64;\n\n\t\t} else if ( value.isTexture ) {\n\n\t\t\tconsole.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );\n\n\t\t} else {\n\n\t\t\tconsole.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );\n\n\t\t}\n\n\t\treturn info;\n\n\t}\n\n\tfunction onUniformsGroupsDispose( event ) {\n\n\t\tconst uniformsGroup = event.target;\n\n\t\tuniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );\n\n\t\tconst index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );\n\t\tallocatedBindingPoints.splice( index, 1 );\n\n\t\tgl.deleteBuffer( buffers[ uniformsGroup.id ] );\n\n\t\tdelete buffers[ uniformsGroup.id ];\n\t\tdelete updateList[ uniformsGroup.id ];\n\n\t}\n\n\tfunction dispose() {\n\n\t\tfor ( const id in buffers ) {\n\n\t\t\tgl.deleteBuffer( buffers[ id ] );\n\n\t\t}\n\n\t\tallocatedBindingPoints = [];\n\t\tbuffers = {};\n\t\tupdateList = {};\n\n\t}\n\n\treturn {\n\n\t\tbind: bind,\n\t\tupdate: update,\n\n\t\tdispose: dispose\n\n\t};\n\n}\n\nfunction createCanvasElement() {\n\n\tconst canvas = createElementNS( 'canvas' );\n\tcanvas.style.display = 'block';\n\treturn canvas;\n\n}\n\nclass WebGLRenderer {\n\n\tconstructor( parameters = {} ) {\n\n\t\tconst {\n\t\t\tcanvas = createCanvasElement(),\n\t\t\tcontext = null,\n\t\t\tdepth = true,\n\t\t\tstencil = true,\n\t\t\talpha = false,\n\t\t\tantialias = false,\n\t\t\tpremultipliedAlpha = true,\n\t\t\tpreserveDrawingBuffer = false,\n\t\t\tpowerPreference = 'default',\n\t\t\tfailIfMajorPerformanceCaveat = false,\n\t\t} = parameters;\n\n\t\tthis.isWebGLRenderer = true;\n\n\t\tlet _alpha;\n\n\t\tif ( context !== null ) {\n\n\t\t\t_alpha = context.getContextAttributes().alpha;\n\n\t\t} else {\n\n\t\t\t_alpha = alpha;\n\n\t\t}\n\n\t\tlet currentRenderList = null;\n\t\tlet currentRenderState = null;\n\n\t\t// render() can be called from within a callback triggered by another render.\n\t\t// We track this so that the nested render call gets its list and state isolated from the parent render call.\n\n\t\tconst renderListStack = [];\n\t\tconst renderStateStack = [];\n\n\t\t// public properties\n\n\t\tthis.domElement = canvas;\n\n\t\t// Debug configuration container\n\t\tthis.debug = {\n\n\t\t\t/**\n\t\t\t * Enables error checking and reporting when shader programs are being compiled\n\t\t\t * @type {boolean}\n\t\t\t */\n\t\t\tcheckShaderErrors: true,\n\t\t\t/**\n\t\t\t * Callback for custom error reporting.\n\t\t\t * @type {?Function}\n\t\t\t */\n\t\t\tonShaderError: null\n\t\t};\n\n\t\t// clearing\n\n\t\tthis.autoClear = true;\n\t\tthis.autoClearColor = true;\n\t\tthis.autoClearDepth = true;\n\t\tthis.autoClearStencil = true;\n\n\t\t// scene graph\n\n\t\tthis.sortObjects = true;\n\n\t\t// user-defined clipping\n\n\t\tthis.clippingPlanes = [];\n\t\tthis.localClippingEnabled = false;\n\n\t\t// physically based shading\n\n\t\tthis.outputColorSpace = SRGBColorSpace;\n\n\t\t// physical lights\n\n\t\tthis.useLegacyLights = true;\n\n\t\t// tone mapping\n\n\t\tthis.toneMapping = NoToneMapping;\n\t\tthis.toneMappingExposure = 1.0;\n\n\t\t// internal properties\n\n\t\tconst _this = this;\n\n\t\tlet _isContextLost = false;\n\n\t\t// internal state cache\n\n\t\tlet _currentActiveCubeFace = 0;\n\t\tlet _currentActiveMipmapLevel = 0;\n\t\tlet _currentRenderTarget = null;\n\t\tlet _currentMaterialId = - 1;\n\n\t\tlet _currentCamera = null;\n\n\t\tconst _currentViewport = new Vector4();\n\t\tconst _currentScissor = new Vector4();\n\t\tlet _currentScissorTest = null;\n\n\t\t//\n\n\t\tlet _width = canvas.width;\n\t\tlet _height = canvas.height;\n\n\t\tlet _pixelRatio = 1;\n\t\tlet _opaqueSort = null;\n\t\tlet _transparentSort = null;\n\n\t\tconst _viewport = new Vector4( 0, 0, _width, _height );\n\t\tconst _scissor = new Vector4( 0, 0, _width, _height );\n\t\tlet _scissorTest = false;\n\n\t\t// frustum\n\n\t\tconst _frustum = new Frustum();\n\n\t\t// clipping\n\n\t\tlet _clippingEnabled = false;\n\t\tlet _localClippingEnabled = false;\n\n\t\t// transmission\n\n\t\tlet _transmissionRenderTarget = null;\n\n\t\t// camera matrices cache\n\n\t\tconst _projScreenMatrix = new Matrix4();\n\n\t\tconst _vector3 = new Vector3();\n\n\t\tconst _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };\n\n\t\tfunction getTargetPixelRatio() {\n\n\t\t\treturn _currentRenderTarget === null ? _pixelRatio : 1;\n\n\t\t}\n\n\t\t// initialize\n\n\t\tlet _gl = context;\n\n\t\tfunction getContext( contextNames, contextAttributes ) {\n\n\t\t\tfor ( let i = 0; i < contextNames.length; i ++ ) {\n\n\t\t\t\tconst contextName = contextNames[ i ];\n\t\t\t\tconst context = canvas.getContext( contextName, contextAttributes );\n\t\t\t\tif ( context !== null ) return context;\n\n\t\t\t}\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\ttry {\n\n\t\t\tconst contextAttributes = {\n\t\t\t\talpha: true,\n\t\t\t\tdepth,\n\t\t\t\tstencil,\n\t\t\t\tantialias,\n\t\t\t\tpremultipliedAlpha,\n\t\t\t\tpreserveDrawingBuffer,\n\t\t\t\tpowerPreference,\n\t\t\t\tfailIfMajorPerformanceCaveat,\n\t\t\t};\n\n\t\t\t// OffscreenCanvas does not have setAttribute, see #22811\n\t\t\tif ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );\n\n\t\t\t// event listeners must be registered before WebGL context is created, see #12753\n\t\t\tcanvas.addEventListener( 'webglcontextlost', onContextLost, false );\n\t\t\tcanvas.addEventListener( 'webglcontextrestored', onContextRestore, false );\n\t\t\tcanvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );\n\n\t\t\tif ( _gl === null ) {\n\n\t\t\t\tconst contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];\n\n\t\t\t\tif ( _this.isWebGL1Renderer === true ) {\n\n\t\t\t\t\tcontextNames.shift();\n\n\t\t\t\t}\n\n\t\t\t\t_gl = getContext( contextNames, contextAttributes );\n\n\t\t\t\tif ( _gl === null ) {\n\n\t\t\t\t\tif ( getContext( contextNames ) ) {\n\n\t\t\t\t\t\tthrow new Error( 'Error creating WebGL context with your selected attributes.' );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tthrow new Error( 'Error creating WebGL context.' );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// Some experimental-webgl implementations do not have getShaderPrecisionFormat\n\n\t\t\tif ( _gl.getShaderPrecisionFormat === undefined ) {\n\n\t\t\t\t_gl.getShaderPrecisionFormat = function () {\n\n\t\t\t\t\treturn { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };\n\n\t\t\t\t};\n\n\t\t\t}\n\n\t\t} catch ( error ) {\n\n\t\t\tconsole.error( 'THREE.WebGLRenderer: ' + error.message );\n\t\t\tthrow error;\n\n\t\t}\n\n\t\tlet extensions, capabilities, state, info;\n\t\tlet properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;\n\t\tlet programCache, materials, renderLists, renderStates, clipping, shadowMap;\n\n\t\tlet background, morphtargets, bufferRenderer, indexedBufferRenderer;\n\n\t\tlet utils, bindingStates, uniformsGroups;\n\n\t\tfunction initGLContext() {\n\n\t\t\textensions = new WebGLExtensions( _gl );\n\n\t\t\tcapabilities = new WebGLCapabilities( _gl, extensions, parameters );\n\n\t\t\textensions.init( capabilities );\n\n\t\t\tutils = new WebGLUtils( _gl, extensions, capabilities );\n\n\t\t\tstate = new WebGLState( _gl, extensions, capabilities );\n\n\t\t\tinfo = new WebGLInfo( _gl );\n\t\t\tproperties = new WebGLProperties();\n\t\t\ttextures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );\n\t\t\tcubemaps = new WebGLCubeMaps( _this );\n\t\t\tcubeuvmaps = new WebGLCubeUVMaps( _this );\n\t\t\tattributes = new WebGLAttributes( _gl, capabilities );\n\t\t\tbindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );\n\t\t\tgeometries = new WebGLGeometries( _gl, attributes, info, bindingStates );\n\t\t\tobjects = new WebGLObjects( _gl, geometries, attributes, info );\n\t\t\tmorphtargets = new WebGLMorphtargets( _gl, capabilities, textures );\n\t\t\tclipping = new WebGLClipping( properties );\n\t\t\tprogramCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );\n\t\t\tmaterials = new WebGLMaterials( _this, properties );\n\t\t\trenderLists = new WebGLRenderLists();\n\t\t\trenderStates = new WebGLRenderStates( extensions, capabilities );\n\t\t\tbackground = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );\n\t\t\tshadowMap = new WebGLShadowMap( _this, objects, capabilities );\n\t\t\tuniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );\n\n\t\t\tbufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );\n\t\t\tindexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );\n\n\t\t\tinfo.programs = programCache.programs;\n\n\t\t\t_this.capabilities = capabilities;\n\t\t\t_this.extensions = extensions;\n\t\t\t_this.properties = properties;\n\t\t\t_this.renderLists = renderLists;\n\t\t\t_this.shadowMap = shadowMap;\n\t\t\t_this.state = state;\n\t\t\t_this.info = info;\n\n\t\t}\n\n\t\tinitGLContext();\n\n\t\t// xr\n\n\t\tconst xr = new WebXRManager( _this, _gl );\n\n\t\tthis.xr = xr;\n\n\t\t// API\n\n\t\tthis.getContext = function () {\n\n\t\t\treturn _gl;\n\n\t\t};\n\n\t\tthis.getContextAttributes = function () {\n\n\t\t\treturn _gl.getContextAttributes();\n\n\t\t};\n\n\t\tthis.forceContextLoss = function () {\n\n\t\t\tconst extension = extensions.get( 'WEBGL_lose_context' );\n\t\t\tif ( extension ) extension.loseContext();\n\n\t\t};\n\n\t\tthis.forceContextRestore = function () {\n\n\t\t\tconst extension = extensions.get( 'WEBGL_lose_context' );\n\t\t\tif ( extension ) extension.restoreContext();\n\n\t\t};\n\n\t\tthis.getPixelRatio = function () {\n\n\t\t\treturn _pixelRatio;\n\n\t\t};\n\n\t\tthis.setPixelRatio = function ( value ) {\n\n\t\t\tif ( value === undefined ) return;\n\n\t\t\t_pixelRatio = value;\n\n\t\t\tthis.setSize( _width, _height, false );\n\n\t\t};\n\n\t\tthis.getSize = function ( target ) {\n\n\t\t\treturn target.set( _width, _height );\n\n\t\t};\n\n\t\tthis.setSize = function ( width, height, updateStyle = true ) {\n\n\t\t\tif ( xr.isPresenting ) {\n\n\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Can\\'t change size while VR device is presenting.' );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\t_width = width;\n\t\t\t_height = height;\n\n\t\t\tcanvas.width = Math.floor( width * _pixelRatio );\n\t\t\tcanvas.height = Math.floor( height * _pixelRatio );\n\n\t\t\tif ( updateStyle === true ) {\n\n\t\t\t\tcanvas.style.width = width + 'px';\n\t\t\t\tcanvas.style.height = height + 'px';\n\n\t\t\t}\n\n\t\t\tthis.setViewport( 0, 0, width, height );\n\n\t\t};\n\n\t\tthis.getDrawingBufferSize = function ( target ) {\n\n\t\t\treturn target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();\n\n\t\t};\n\n\t\tthis.setDrawingBufferSize = function ( width, height, pixelRatio ) {\n\n\t\t\t_width = width;\n\t\t\t_height = height;\n\n\t\t\t_pixelRatio = pixelRatio;\n\n\t\t\tcanvas.width = Math.floor( width * pixelRatio );\n\t\t\tcanvas.height = Math.floor( height * pixelRatio );\n\n\t\t\tthis.setViewport( 0, 0, width, height );\n\n\t\t};\n\n\t\tthis.getCurrentViewport = function ( target ) {\n\n\t\t\treturn target.copy( _currentViewport );\n\n\t\t};\n\n\t\tthis.getViewport = function ( target ) {\n\n\t\t\treturn target.copy( _viewport );\n\n\t\t};\n\n\t\tthis.setViewport = function ( x, y, width, height ) {\n\n\t\t\tif ( x.isVector4 ) {\n\n\t\t\t\t_viewport.set( x.x, x.y, x.z, x.w );\n\n\t\t\t} else {\n\n\t\t\t\t_viewport.set( x, y, width, height );\n\n\t\t\t}\n\n\t\t\tstate.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );\n\n\t\t};\n\n\t\tthis.getScissor = function ( target ) {\n\n\t\t\treturn target.copy( _scissor );\n\n\t\t};\n\n\t\tthis.setScissor = function ( x, y, width, height ) {\n\n\t\t\tif ( x.isVector4 ) {\n\n\t\t\t\t_scissor.set( x.x, x.y, x.z, x.w );\n\n\t\t\t} else {\n\n\t\t\t\t_scissor.set( x, y, width, height );\n\n\t\t\t}\n\n\t\t\tstate.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );\n\n\t\t};\n\n\t\tthis.getScissorTest = function () {\n\n\t\t\treturn _scissorTest;\n\n\t\t};\n\n\t\tthis.setScissorTest = function ( boolean ) {\n\n\t\t\tstate.setScissorTest( _scissorTest = boolean );\n\n\t\t};\n\n\t\tthis.setOpaqueSort = function ( method ) {\n\n\t\t\t_opaqueSort = method;\n\n\t\t};\n\n\t\tthis.setTransparentSort = function ( method ) {\n\n\t\t\t_transparentSort = method;\n\n\t\t};\n\n\t\t// Clearing\n\n\t\tthis.getClearColor = function ( target ) {\n\n\t\t\treturn target.copy( background.getClearColor() );\n\n\t\t};\n\n\t\tthis.setClearColor = function () {\n\n\t\t\tbackground.setClearColor.apply( background, arguments );\n\n\t\t};\n\n\t\tthis.getClearAlpha = function () {\n\n\t\t\treturn background.getClearAlpha();\n\n\t\t};\n\n\t\tthis.setClearAlpha = function () {\n\n\t\t\tbackground.setClearAlpha.apply( background, arguments );\n\n\t\t};\n\n\t\tthis.clear = function ( color = true, depth = true, stencil = true ) {\n\n\t\t\tlet bits = 0;\n\n\t\t\tif ( color ) bits |= _gl.COLOR_BUFFER_BIT;\n\t\t\tif ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;\n\t\t\tif ( stencil ) bits |= _gl.STENCIL_BUFFER_BIT;\n\n\t\t\t_gl.clear( bits );\n\n\t\t};\n\n\t\tthis.clearColor = function () {\n\n\t\t\tthis.clear( true, false, false );\n\n\t\t};\n\n\t\tthis.clearDepth = function () {\n\n\t\t\tthis.clear( false, true, false );\n\n\t\t};\n\n\t\tthis.clearStencil = function () {\n\n\t\t\tthis.clear( false, false, true );\n\n\t\t};\n\n\t\t//\n\n\t\tthis.dispose = function () {\n\n\t\t\tcanvas.removeEventListener( 'webglcontextlost', onContextLost, false );\n\t\t\tcanvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );\n\t\t\tcanvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );\n\n\t\t\trenderLists.dispose();\n\t\t\trenderStates.dispose();\n\t\t\tproperties.dispose();\n\t\t\tcubemaps.dispose();\n\t\t\tcubeuvmaps.dispose();\n\t\t\tobjects.dispose();\n\t\t\tbindingStates.dispose();\n\t\t\tuniformsGroups.dispose();\n\t\t\tprogramCache.dispose();\n\n\t\t\txr.dispose();\n\n\t\t\txr.removeEventListener( 'sessionstart', onXRSessionStart );\n\t\t\txr.removeEventListener( 'sessionend', onXRSessionEnd );\n\n\t\t\tif ( _transmissionRenderTarget ) {\n\n\t\t\t\t_transmissionRenderTarget.dispose();\n\t\t\t\t_transmissionRenderTarget = null;\n\n\t\t\t}\n\n\t\t\tanimation.stop();\n\n\t\t};\n\n\t\t// Events\n\n\t\tfunction onContextLost( event ) {\n\n\t\t\tevent.preventDefault();\n\n\t\t\tconsole.log( 'THREE.WebGLRenderer: Context Lost.' );\n\n\t\t\t_isContextLost = true;\n\n\t\t}\n\n\t\tfunction onContextRestore( /* event */ ) {\n\n\t\t\tconsole.log( 'THREE.WebGLRenderer: Context Restored.' );\n\n\t\t\t_isContextLost = false;\n\n\t\t\tconst infoAutoReset = info.autoReset;\n\t\t\tconst shadowMapEnabled = shadowMap.enabled;\n\t\t\tconst shadowMapAutoUpdate = shadowMap.autoUpdate;\n\t\t\tconst shadowMapNeedsUpdate = shadowMap.needsUpdate;\n\t\t\tconst shadowMapType = shadowMap.type;\n\n\t\t\tinitGLContext();\n\n\t\t\tinfo.autoReset = infoAutoReset;\n\t\t\tshadowMap.enabled = shadowMapEnabled;\n\t\t\tshadowMap.autoUpdate = shadowMapAutoUpdate;\n\t\t\tshadowMap.needsUpdate = shadowMapNeedsUpdate;\n\t\t\tshadowMap.type = shadowMapType;\n\n\t\t}\n\n\t\tfunction onContextCreationError( event ) {\n\n\t\t\tconsole.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );\n\n\t\t}\n\n\t\tfunction onMaterialDispose( event ) {\n\n\t\t\tconst material = event.target;\n\n\t\t\tmaterial.removeEventListener( 'dispose', onMaterialDispose );\n\n\t\t\tdeallocateMaterial( material );\n\n\t\t}\n\n\t\t// Buffer deallocation\n\n\t\tfunction deallocateMaterial( material ) {\n\n\t\t\treleaseMaterialProgramReferences( material );\n\n\t\t\tproperties.remove( material );\n\n\t\t}\n\n\n\t\tfunction releaseMaterialProgramReferences( material ) {\n\n\t\t\tconst programs = properties.get( material ).programs;\n\n\t\t\tif ( programs !== undefined ) {\n\n\t\t\t\tprograms.forEach( function ( program ) {\n\n\t\t\t\t\tprogramCache.releaseProgram( program );\n\n\t\t\t\t} );\n\n\t\t\t\tif ( material.isShaderMaterial ) {\n\n\t\t\t\t\tprogramCache.releaseShaderCache( material );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\t// Buffer rendering\n\n\t\tthis.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {\n\n\t\t\tif ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)\n\n\t\t\tconst frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );\n\n\t\t\tconst program = setProgram( camera, scene, geometry, material, object );\n\n\t\t\tstate.setMaterial( material, frontFaceCW );\n\n\t\t\t//\n\n\t\t\tlet index = geometry.index;\n\t\t\tlet rangeFactor = 1;\n\n\t\t\tif ( material.wireframe === true ) {\n\n\t\t\t\tindex = geometries.getWireframeAttribute( geometry );\n\t\t\t\trangeFactor = 2;\n\n\t\t\t}\n\n\t\t\t//\n\n\t\t\tconst drawRange = geometry.drawRange;\n\t\t\tconst position = geometry.attributes.position;\n\n\t\t\tlet drawStart = drawRange.start * rangeFactor;\n\t\t\tlet drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;\n\n\t\t\tif ( group !== null ) {\n\n\t\t\t\tdrawStart = Math.max( drawStart, group.start * rangeFactor );\n\t\t\t\tdrawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );\n\n\t\t\t}\n\n\t\t\tif ( index !== null ) {\n\n\t\t\t\tdrawStart = Math.max( drawStart, 0 );\n\t\t\t\tdrawEnd = Math.min( drawEnd, index.count );\n\n\t\t\t} else if ( position !== undefined && position !== null ) {\n\n\t\t\t\tdrawStart = Math.max( drawStart, 0 );\n\t\t\t\tdrawEnd = Math.min( drawEnd, position.count );\n\n\t\t\t}\n\n\t\t\tconst drawCount = drawEnd - drawStart;\n\n\t\t\tif ( drawCount < 0 || drawCount === Infinity ) return;\n\n\t\t\t//\n\n\t\t\tbindingStates.setup( object, material, program, geometry, index );\n\n\t\t\tlet attribute;\n\t\t\tlet renderer = bufferRenderer;\n\n\t\t\tif ( index !== null ) {\n\n\t\t\t\tattribute = attributes.get( index );\n\n\t\t\t\trenderer = indexedBufferRenderer;\n\t\t\t\trenderer.setIndex( attribute );\n\n\t\t\t}\n\n\t\t\t//\n\n\t\t\tif ( object.isMesh ) {\n\n\t\t\t\tif ( material.wireframe === true ) {\n\n\t\t\t\t\tstate.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );\n\t\t\t\t\trenderer.setMode( _gl.LINES );\n\n\t\t\t\t} else {\n\n\t\t\t\t\trenderer.setMode( _gl.TRIANGLES );\n\n\t\t\t\t}\n\n\t\t\t} else if ( object.isLine ) {\n\n\t\t\t\tlet lineWidth = material.linewidth;\n\n\t\t\t\tif ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material\n\n\t\t\t\tstate.setLineWidth( lineWidth * getTargetPixelRatio() );\n\n\t\t\t\tif ( object.isLineSegments ) {\n\n\t\t\t\t\trenderer.setMode( _gl.LINES );\n\n\t\t\t\t} else if ( object.isLineLoop ) {\n\n\t\t\t\t\trenderer.setMode( _gl.LINE_LOOP );\n\n\t\t\t\t} else {\n\n\t\t\t\t\trenderer.setMode( _gl.LINE_STRIP );\n\n\t\t\t\t}\n\n\t\t\t} else if ( object.isPoints ) {\n\n\t\t\t\trenderer.setMode( _gl.POINTS );\n\n\t\t\t} else if ( object.isSprite ) {\n\n\t\t\t\trenderer.setMode( _gl.TRIANGLES );\n\n\t\t\t}\n\n\t\t\tif ( object.isInstancedMesh ) {\n\n\t\t\t\trenderer.renderInstances( drawStart, drawCount, object.count );\n\n\t\t\t} else if ( geometry.isInstancedBufferGeometry ) {\n\n\t\t\t\tconst maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;\n\t\t\t\tconst instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );\n\n\t\t\t\trenderer.renderInstances( drawStart, drawCount, instanceCount );\n\n\t\t\t} else {\n\n\t\t\t\trenderer.render( drawStart, drawCount );\n\n\t\t\t}\n\n\t\t};\n\n\t\t// Compile\n\n\t\tthis.compile = function ( scene, camera ) {\n\n\t\t\tfunction prepare( material, scene, object ) {\n\n\t\t\t\tif ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {\n\n\t\t\t\t\tmaterial.side = BackSide;\n\t\t\t\t\tmaterial.needsUpdate = true;\n\t\t\t\t\tgetProgram( material, scene, object );\n\n\t\t\t\t\tmaterial.side = FrontSide;\n\t\t\t\t\tmaterial.needsUpdate = true;\n\t\t\t\t\tgetProgram( material, scene, object );\n\n\t\t\t\t\tmaterial.side = DoubleSide;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tgetProgram( material, scene, object );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tcurrentRenderState = renderStates.get( scene );\n\t\t\tcurrentRenderState.init();\n\n\t\t\trenderStateStack.push( currentRenderState );\n\n\t\t\tscene.traverseVisible( function ( object ) {\n\n\t\t\t\tif ( object.isLight && object.layers.test( camera.layers ) ) {\n\n\t\t\t\t\tcurrentRenderState.pushLight( object );\n\n\t\t\t\t\tif ( object.castShadow ) {\n\n\t\t\t\t\t\tcurrentRenderState.pushShadow( object );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} );\n\n\t\t\tcurrentRenderState.setupLights( _this.useLegacyLights );\n\n\t\t\tscene.traverse( function ( object ) {\n\n\t\t\t\tconst material = object.material;\n\n\t\t\t\tif ( material ) {\n\n\t\t\t\t\tif ( Array.isArray( material ) ) {\n\n\t\t\t\t\t\tfor ( let i = 0; i < material.length; i ++ ) {\n\n\t\t\t\t\t\t\tconst material2 = material[ i ];\n\n\t\t\t\t\t\t\tprepare( material2, scene, object );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tprepare( material, scene, object );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} );\n\n\t\t\trenderStateStack.pop();\n\t\t\tcurrentRenderState = null;\n\n\t\t};\n\n\t\t// Animation Loop\n\n\t\tlet onAnimationFrameCallback = null;\n\n\t\tfunction onAnimationFrame( time ) {\n\n\t\t\tif ( onAnimationFrameCallback ) onAnimationFrameCallback( time );\n\n\t\t}\n\n\t\tfunction onXRSessionStart() {\n\n\t\t\tanimation.stop();\n\n\t\t}\n\n\t\tfunction onXRSessionEnd() {\n\n\t\t\tanimation.start();\n\n\t\t}\n\n\t\tconst animation = new WebGLAnimation();\n\t\tanimation.setAnimationLoop( onAnimationFrame );\n\n\t\tif ( typeof self !== 'undefined' ) animation.setContext( self );\n\n\t\tthis.setAnimationLoop = function ( callback ) {\n\n\t\t\tonAnimationFrameCallback = callback;\n\t\t\txr.setAnimationLoop( callback );\n\n\t\t\t( callback === null ) ? animation.stop() : animation.start();\n\n\t\t};\n\n\t\txr.addEventListener( 'sessionstart', onXRSessionStart );\n\t\txr.addEventListener( 'sessionend', onXRSessionEnd );\n\n\t\t// Rendering\n\n\t\tthis.render = function ( scene, camera ) {\n\n\t\t\tif ( camera !== undefined && camera.isCamera !== true ) {\n\n\t\t\t\tconsole.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tif ( _isContextLost === true ) return;\n\n\t\t\t// update scene graph\n\n\t\t\tif ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();\n\n\t\t\t// update camera matrices and frustum\n\n\t\t\tif ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();\n\n\t\t\tif ( xr.enabled === true && xr.isPresenting === true ) {\n\n\t\t\t\tif ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );\n\n\t\t\t\tcamera = xr.getCamera(); // use XR camera for rendering\n\n\t\t\t}\n\n\t\t\t//\n\t\t\tif ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );\n\n\t\t\tcurrentRenderState = renderStates.get( scene, renderStateStack.length );\n\t\t\tcurrentRenderState.init();\n\n\t\t\trenderStateStack.push( currentRenderState );\n\n\t\t\t_projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );\n\t\t\t_frustum.setFromProjectionMatrix( _projScreenMatrix );\n\n\t\t\t_localClippingEnabled = this.localClippingEnabled;\n\t\t\t_clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );\n\n\t\t\tcurrentRenderList = renderLists.get( scene, renderListStack.length );\n\t\t\tcurrentRenderList.init();\n\n\t\t\trenderListStack.push( currentRenderList );\n\n\t\t\tprojectObject( scene, camera, 0, _this.sortObjects );\n\n\t\t\tcurrentRenderList.finish();\n\n\t\t\tif ( _this.sortObjects === true ) {\n\n\t\t\t\tcurrentRenderList.sort( _opaqueSort, _transparentSort );\n\n\t\t\t}\n\n\t\t\t//\n\n\t\t\tif ( _clippingEnabled === true ) clipping.beginShadows();\n\n\t\t\tconst shadowsArray = currentRenderState.state.shadowsArray;\n\n\t\t\tshadowMap.render( shadowsArray, scene, camera );\n\n\t\t\tif ( _clippingEnabled === true ) clipping.endShadows();\n\n\t\t\t//\n\n\t\t\tif ( this.info.autoReset === true ) this.info.reset();\n\n\t\t\t//\n\n\t\t\tbackground.render( currentRenderList, scene );\n\n\t\t\t// render scene\n\n\t\t\tcurrentRenderState.setupLights( _this.useLegacyLights );\n\n\t\t\tif ( camera.isArrayCamera ) {\n\n\t\t\t\tconst cameras = camera.cameras;\n\n\t\t\t\tfor ( let i = 0, l = cameras.length; i < l; i ++ ) {\n\n\t\t\t\t\tconst camera2 = cameras[ i ];\n\n\t\t\t\t\trenderScene( currentRenderList, scene, camera2, camera2.viewport );\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\trenderScene( currentRenderList, scene, camera );\n\n\t\t\t}\n\n\t\t\t//\n\n\t\t\tif ( _currentRenderTarget !== null ) {\n\n\t\t\t\t// resolve multisample renderbuffers to a single-sample texture if necessary\n\n\t\t\t\ttextures.updateMultisampleRenderTarget( _currentRenderTarget );\n\n\t\t\t\t// Generate mipmap if we're using any kind of mipmap filtering\n\n\t\t\t\ttextures.updateRenderTargetMipmap( _currentRenderTarget );\n\n\t\t\t}\n\n\t\t\t//\n\n\t\t\tif ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );\n\n\t\t\t// _gl.finish();\n\n\t\t\tbindingStates.resetDefaultState();\n\t\t\t_currentMaterialId = - 1;\n\t\t\t_currentCamera = null;\n\n\t\t\trenderStateStack.pop();\n\n\t\t\tif ( renderStateStack.length > 0 ) {\n\n\t\t\t\tcurrentRenderState = renderStateStack[ renderStateStack.length - 1 ];\n\n\t\t\t} else {\n\n\t\t\t\tcurrentRenderState = null;\n\n\t\t\t}\n\n\t\t\trenderListStack.pop();\n\n\t\t\tif ( renderListStack.length > 0 ) {\n\n\t\t\t\tcurrentRenderList = renderListStack[ renderListStack.length - 1 ];\n\n\t\t\t} else {\n\n\t\t\t\tcurrentRenderList = null;\n\n\t\t\t}\n\n\t\t};\n\n\t\tfunction projectObject( object, camera, groupOrder, sortObjects ) {\n\n\t\t\tif ( object.visible === false ) return;\n\n\t\t\tconst visible = object.layers.test( camera.layers );\n\n\t\t\tif ( visible ) {\n\n\t\t\t\tif ( object.isGroup ) {\n\n\t\t\t\t\tgroupOrder = object.renderOrder;\n\n\t\t\t\t} else if ( object.isLOD ) {\n\n\t\t\t\t\tif ( object.autoUpdate === true ) object.update( camera );\n\n\t\t\t\t} else if ( object.isLight ) {\n\n\t\t\t\t\tcurrentRenderState.pushLight( object );\n\n\t\t\t\t\tif ( object.castShadow ) {\n\n\t\t\t\t\t\tcurrentRenderState.pushShadow( object );\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if ( object.isSprite ) {\n\n\t\t\t\t\tif ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {\n\n\t\t\t\t\t\tif ( sortObjects ) {\n\n\t\t\t\t\t\t\t_vector3.setFromMatrixPosition( object.matrixWorld )\n\t\t\t\t\t\t\t\t.applyMatrix4( _projScreenMatrix );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst geometry = objects.update( object );\n\t\t\t\t\t\tconst material = object.material;\n\n\t\t\t\t\t\tif ( material.visible ) {\n\n\t\t\t\t\t\t\tcurrentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if ( object.isMesh || object.isLine || object.isPoints ) {\n\n\t\t\t\t\tif ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {\n\n\t\t\t\t\t\tif ( object.isSkinnedMesh ) {\n\n\t\t\t\t\t\t\t// update skeleton only once in a frame\n\n\t\t\t\t\t\t\tif ( object.skeleton.frame !== info.render.frame ) {\n\n\t\t\t\t\t\t\t\tobject.skeleton.update();\n\t\t\t\t\t\t\t\tobject.skeleton.frame = info.render.frame;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst geometry = objects.update( object );\n\t\t\t\t\t\tconst material = object.material;\n\n\t\t\t\t\t\tif ( sortObjects ) {\n\n\t\t\t\t\t\t\tif ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();\n\n\t\t\t\t\t\t\t_vector3\n\t\t\t\t\t\t\t\t.copy( geometry.boundingSphere.center )\n\t\t\t\t\t\t\t\t.applyMatrix4( object.matrixWorld )\n\t\t\t\t\t\t\t\t.applyMatrix4( _projScreenMatrix );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ( Array.isArray( material ) ) {\n\n\t\t\t\t\t\t\tconst groups = geometry.groups;\n\n\t\t\t\t\t\t\tfor ( let i = 0, l = groups.length; i < l; i ++ ) {\n\n\t\t\t\t\t\t\t\tconst group = groups[ i ];\n\t\t\t\t\t\t\t\tconst groupMaterial = material[ group.materialIndex ];\n\n\t\t\t\t\t\t\t\tif ( groupMaterial && groupMaterial.visible ) {\n\n\t\t\t\t\t\t\t\t\tcurrentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} else if ( material.visible ) {\n\n\t\t\t\t\t\t\tcurrentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tconst children = object.children;\n\n\t\t\tfor ( let i = 0, l = children.length; i < l; i ++ ) {\n\n\t\t\t\tprojectObject( children[ i ], camera, groupOrder, sortObjects );\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction renderScene( currentRenderList, scene, camera, viewport ) {\n\n\t\t\tconst opaqueObjects = currentRenderList.opaque;\n\t\t\tconst transmissiveObjects = currentRenderList.transmissive;\n\t\t\tconst transparentObjects = currentRenderList.transparent;\n\n\t\t\tcurrentRenderState.setupLightsView( camera );\n\n\t\t\tif ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );\n\n\t\t\tif ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );\n\n\t\t\tif ( viewport ) state.viewport( _currentViewport.copy( viewport ) );\n\n\t\t\tif ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );\n\t\t\tif ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );\n\t\t\tif ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );\n\n\t\t\t// Ensure depth buffer writing is enabled so it can be cleared on next render\n\n\t\t\tstate.buffers.depth.setTest( true );\n\t\t\tstate.buffers.depth.setMask( true );\n\t\t\tstate.buffers.color.setMask( true );\n\n\t\t\tstate.setPolygonOffset( false );\n\n\t\t}\n\n\t\tfunction renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {\n\n\t\t\tif ( _transmissionRenderTarget === null ) {\n\n\t\t\t\tconst isWebGL2 = capabilities.isWebGL2;\n\n\t\t\t\t_transmissionRenderTarget = new WebGLRenderTarget( 1024, 1024, {\n\t\t\t\t\tgenerateMipmaps: true,\n\t\t\t\t\ttype: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,\n\t\t\t\t\tminFilter: LinearMipmapLinearFilter,\n\t\t\t\t\tsamples: ( isWebGL2 && antialias === true ) ? 4 : 0\n\t\t\t\t} );\n\n\t\t\t\t// debug\n\n\t\t\t\t/*\n\t\t\t\tconst geometry = new PlaneGeometry();\n\t\t\t\tconst material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );\n\n\t\t\t\tconst mesh = new Mesh( geometry, material );\n\t\t\t\tscene.add( mesh );\n\t\t\t\t*/\n\n\t\t\t}\n\n\t\t\t//\n\n\t\t\tconst currentRenderTarget = _this.getRenderTarget();\n\t\t\t_this.setRenderTarget( _transmissionRenderTarget );\n\t\t\t_this.clear();\n\n\t\t\t// Turn off the features which can affect the frag color for opaque objects pass.\n\t\t\t// Otherwise they are applied twice in opaque objects pass and transmission objects pass.\n\t\t\tconst currentToneMapping = _this.toneMapping;\n\t\t\t_this.toneMapping = NoToneMapping;\n\n\t\t\trenderObjects( opaqueObjects, scene, camera );\n\n\t\t\ttextures.updateMultisampleRenderTarget( _transmissionRenderTarget );\n\t\t\ttextures.updateRenderTargetMipmap( _transmissionRenderTarget );\n\n\t\t\tlet renderTargetNeedsUpdate = false;\n\n\t\t\tfor ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {\n\n\t\t\t\tconst renderItem = transmissiveObjects[ i ];\n\n\t\t\t\tconst object = renderItem.object;\n\t\t\t\tconst geometry = renderItem.geometry;\n\t\t\t\tconst material = renderItem.material;\n\t\t\t\tconst group = renderItem.group;\n\n\t\t\t\tif ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {\n\n\t\t\t\t\tconst currentSide = material.side;\n\n\t\t\t\t\tmaterial.side = BackSide;\n\t\t\t\t\tmaterial.needsUpdate = true;\n\n\t\t\t\t\trenderObject( object, scene, camera, geometry, material, group );\n\n\t\t\t\t\tmaterial.side = currentSide;\n\t\t\t\t\tmaterial.needsUpdate = true;\n\n\t\t\t\t\trenderTargetNeedsUpdate = true;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( renderTargetNeedsUpdate === true ) {\n\n\t\t\t\ttextures.updateMultisampleRenderTarget( _transmissionRenderTarget );\n\t\t\t\ttextures.updateRenderTargetMipmap( _transmissionRenderTarget );\n\n\t\t\t}\n\n\t\t\t_this.setRenderTarget( currentRenderTarget );\n\n\t\t\t_this.toneMapping = currentToneMapping;\n\n\t\t}\n\n\t\tfunction renderObjects( renderList, scene, camera ) {\n\n\t\t\tconst overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;\n\n\t\t\tfor ( let i = 0, l = renderList.length; i < l; i ++ ) {\n\n\t\t\t\tconst renderItem = renderList[ i ];\n\n\t\t\t\tconst object = renderItem.object;\n\t\t\t\tconst geometry = renderItem.geometry;\n\t\t\t\tconst material = overrideMaterial === null ? renderItem.material : overrideMaterial;\n\t\t\t\tconst group = renderItem.group;\n\n\t\t\t\tif ( object.layers.test( camera.layers ) ) {\n\n\t\t\t\t\trenderObject( object, scene, camera, geometry, material, group );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction renderObject( object, scene, camera, geometry, material, group ) {\n\n\t\t\tobject.onBeforeRender( _this, scene, camera, geometry, material, group );\n\n\t\t\tobject.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );\n\t\t\tobject.normalMatrix.getNormalMatrix( object.modelViewMatrix );\n\n\t\t\tmaterial.onBeforeRender( _this, scene, camera, geometry, object, group );\n\n\t\t\tif ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {\n\n\t\t\t\tmaterial.side = BackSide;\n\t\t\t\tmaterial.needsUpdate = true;\n\t\t\t\t_this.renderBufferDirect( camera, scene, geometry, material, object, group );\n\n\t\t\t\tmaterial.side = FrontSide;\n\t\t\t\tmaterial.needsUpdate = true;\n\t\t\t\t_this.renderBufferDirect( camera, scene, geometry, material, object, group );\n\n\t\t\t\tmaterial.side = DoubleSide;\n\n\t\t\t} else {\n\n\t\t\t\t_this.renderBufferDirect( camera, scene, geometry, material, object, group );\n\n\t\t\t}\n\n\t\t\tobject.onAfterRender( _this, scene, camera, geometry, material, group );\n\n\t\t}\n\n\t\tfunction getProgram( material, scene, object ) {\n\n\t\t\tif ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...\n\n\t\t\tconst materialProperties = properties.get( material );\n\n\t\t\tconst lights = currentRenderState.state.lights;\n\t\t\tconst shadowsArray = currentRenderState.state.shadowsArray;\n\n\t\t\tconst lightsStateVersion = lights.state.version;\n\n\t\t\tconst parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );\n\t\t\tconst programCacheKey = programCache.getProgramCacheKey( parameters );\n\n\t\t\tlet programs = materialProperties.programs;\n\n\t\t\t// always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change\n\n\t\t\tmaterialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;\n\t\t\tmaterialProperties.fog = scene.fog;\n\t\t\tmaterialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );\n\n\t\t\tif ( programs === undefined ) {\n\n\t\t\t\t// new material\n\n\t\t\t\tmaterial.addEventListener( 'dispose', onMaterialDispose );\n\n\t\t\t\tprograms = new Map();\n\t\t\t\tmaterialProperties.programs = programs;\n\n\t\t\t}\n\n\t\t\tlet program = programs.get( programCacheKey );\n\n\t\t\tif ( program !== undefined ) {\n\n\t\t\t\t// early out if program and light state is identical\n\n\t\t\t\tif ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {\n\n\t\t\t\t\tupdateCommonMaterialProperties( material, parameters );\n\n\t\t\t\t\treturn program;\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tparameters.uniforms = programCache.getUniforms( material );\n\n\t\t\t\tmaterial.onBuild( object, parameters, _this );\n\n\t\t\t\tmaterial.onBeforeCompile( parameters, _this );\n\n\t\t\t\tprogram = programCache.acquireProgram( parameters, programCacheKey );\n\t\t\t\tprograms.set( programCacheKey, program );\n\n\t\t\t\tmaterialProperties.uniforms = parameters.uniforms;\n\n\t\t\t}\n\n\t\t\tconst uniforms = materialProperties.uniforms;\n\n\t\t\tif ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {\n\n\t\t\t\tuniforms.clippingPlanes = clipping.uniform;\n\n\t\t\t}\n\n\t\t\tupdateCommonMaterialProperties( material, parameters );\n\n\t\t\t// store the light setup it was created for\n\n\t\t\tmaterialProperties.needsLights = materialNeedsLights( material );\n\t\t\tmaterialProperties.lightsStateVersion = lightsStateVersion;\n\n\t\t\tif ( materialProperties.needsLights ) {\n\n\t\t\t\t// wire up the material to this renderer's lighting state\n\n\t\t\t\tuniforms.ambientLightColor.value = lights.state.ambient;\n\t\t\t\tuniforms.lightProbe.value = lights.state.probe;\n\t\t\t\tuniforms.directionalLights.value = lights.state.directional;\n\t\t\t\tuniforms.directionalLightShadows.value = lights.state.directionalShadow;\n\t\t\t\tuniforms.spotLights.value = lights.state.spot;\n\t\t\t\tuniforms.spotLightShadows.value = lights.state.spotShadow;\n\t\t\t\tuniforms.rectAreaLights.value = lights.state.rectArea;\n\t\t\t\tuniforms.ltc_1.value = lights.state.rectAreaLTC1;\n\t\t\t\tuniforms.ltc_2.value = lights.state.rectAreaLTC2;\n\t\t\t\tuniforms.pointLights.value = lights.state.point;\n\t\t\t\tuniforms.pointLightShadows.value = lights.state.pointShadow;\n\t\t\t\tuniforms.hemisphereLights.value = lights.state.hemi;\n\n\t\t\t\tuniforms.directionalShadowMap.value = lights.state.directionalShadowMap;\n\t\t\t\tuniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;\n\t\t\t\tuniforms.spotShadowMap.value = lights.state.spotShadowMap;\n\t\t\t\tuniforms.spotLightMatrix.value = lights.state.spotLightMatrix;\n\t\t\t\tuniforms.spotLightMap.value = lights.state.spotLightMap;\n\t\t\t\tuniforms.pointShadowMap.value = lights.state.pointShadowMap;\n\t\t\t\tuniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;\n\t\t\t\t// TODO (abelnation): add area lights shadow info to uniforms\n\n\t\t\t}\n\n\t\t\tconst progUniforms = program.getUniforms();\n\t\t\tconst uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );\n\n\t\t\tmaterialProperties.currentProgram = program;\n\t\t\tmaterialProperties.uniformsList = uniformsList;\n\n\t\t\treturn program;\n\n\t\t}\n\n\t\tfunction updateCommonMaterialProperties( material, parameters ) {\n\n\t\t\tconst materialProperties = properties.get( material );\n\n\t\t\tmaterialProperties.outputColorSpace = parameters.outputColorSpace;\n\t\t\tmaterialProperties.instancing = parameters.instancing;\n\t\t\tmaterialProperties.skinning = parameters.skinning;\n\t\t\tmaterialProperties.morphTargets = parameters.morphTargets;\n\t\t\tmaterialProperties.morphNormals = parameters.morphNormals;\n\t\t\tmaterialProperties.morphColors = parameters.morphColors;\n\t\t\tmaterialProperties.morphTargetsCount = parameters.morphTargetsCount;\n\t\t\tmaterialProperties.numClippingPlanes = parameters.numClippingPlanes;\n\t\t\tmaterialProperties.numIntersection = parameters.numClipIntersection;\n\t\t\tmaterialProperties.vertexAlphas = parameters.vertexAlphas;\n\t\t\tmaterialProperties.vertexTangents = parameters.vertexTangents;\n\t\t\tmaterialProperties.toneMapping = parameters.toneMapping;\n\n\t\t}\n\n\t\tfunction setProgram( camera, scene, geometry, material, object ) {\n\n\t\t\tif ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...\n\n\t\t\ttextures.resetTextureUnits();\n\n\t\t\tconst fog = scene.fog;\n\t\t\tconst environment = material.isMeshStandardMaterial ? scene.environment : null;\n\t\t\tconst colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );\n\t\t\tconst envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );\n\t\t\tconst vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;\n\t\t\tconst vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;\n\t\t\tconst morphTargets = !! geometry.morphAttributes.position;\n\t\t\tconst morphNormals = !! geometry.morphAttributes.normal;\n\t\t\tconst morphColors = !! geometry.morphAttributes.color;\n\t\t\tconst toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;\n\n\t\t\tconst morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;\n\t\t\tconst morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;\n\n\t\t\tconst materialProperties = properties.get( material );\n\t\t\tconst lights = currentRenderState.state.lights;\n\n\t\t\tif ( _clippingEnabled === true ) {\n\n\t\t\t\tif ( _localClippingEnabled === true || camera !== _currentCamera ) {\n\n\t\t\t\t\tconst useCache =\n\t\t\t\t\t\tcamera === _currentCamera &&\n\t\t\t\t\t\tmaterial.id === _currentMaterialId;\n\n\t\t\t\t\t// we might want to call this function with some ClippingGroup\n\t\t\t\t\t// object instead of the material, once it becomes feasible\n\t\t\t\t\t// (#8465, #8379)\n\t\t\t\t\tclipping.setState( material, camera, useCache );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t//\n\n\t\t\tlet needsProgramChange = false;\n\n\t\t\tif ( material.version === materialProperties.__version ) {\n\n\t\t\t\tif ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( materialProperties.outputColorSpace !== colorSpace ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( object.isInstancedMesh && materialProperties.instancing === false ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( materialProperties.envMap !== envMap ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( material.fog === true && materialProperties.fog !== fog ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( materialProperties.numClippingPlanes !== undefined &&\n\t\t\t\t\t( materialProperties.numClippingPlanes !== clipping.numPlanes ||\n\t\t\t\t\tmaterialProperties.numIntersection !== clipping.numIntersection ) ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( materialProperties.vertexAlphas !== vertexAlphas ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( materialProperties.vertexTangents !== vertexTangents ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( materialProperties.morphTargets !== morphTargets ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( materialProperties.morphNormals !== morphNormals ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( materialProperties.morphColors !== morphColors ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( materialProperties.toneMapping !== toneMapping ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t} else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {\n\n\t\t\t\t\tneedsProgramChange = true;\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tneedsProgramChange = true;\n\t\t\t\tmaterialProperties.__version = material.version;\n\n\t\t\t}\n\n\t\t\t//\n\n\t\t\tlet program = materialProperties.currentProgram;\n\n\t\t\tif ( needsProgramChange === true ) {\n\n\t\t\t\tprogram = getProgram( material, scene, object );\n\n\t\t\t}\n\n\t\t\tlet refreshProgram = false;\n\t\t\tlet refreshMaterial = false;\n\t\t\tlet refreshLights = false;\n\n\t\t\tconst p_uniforms = program.getUniforms(),\n\t\t\t\tm_uniforms = materialProperties.uniforms;\n\n\t\t\tif ( state.useProgram( program.program ) ) {\n\n\t\t\t\trefreshProgram = true;\n\t\t\t\trefreshMaterial = true;\n\t\t\t\trefreshLights = true;\n\n\t\t\t}\n\n\t\t\tif ( material.id !== _currentMaterialId ) {\n\n\t\t\t\t_currentMaterialId = material.id;\n\n\t\t\t\trefreshMaterial = true;\n\n\t\t\t}\n\n\t\t\tif ( refreshProgram || _currentCamera !== camera ) {\n\n\t\t\t\tp_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );\n\n\t\t\t\tif ( capabilities.logarithmicDepthBuffer ) {\n\n\t\t\t\t\tp_uniforms.setValue( _gl, 'logDepthBufFC',\n\t\t\t\t\t\t2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );\n\n\t\t\t\t}\n\n\t\t\t\tif ( _currentCamera !== camera ) {\n\n\t\t\t\t\t_currentCamera = camera;\n\n\t\t\t\t\t// lighting uniforms depend on the camera so enforce an update\n\t\t\t\t\t// now, in case this material supports lights - or later, when\n\t\t\t\t\t// the next material that does gets activated:\n\n\t\t\t\t\trefreshMaterial = true;\t\t// set to true on material change\n\t\t\t\t\trefreshLights = true;\t\t// remains set until update done\n\n\t\t\t\t}\n\n\t\t\t\t// load material specific uniforms\n\t\t\t\t// (shader material also gets them for the sake of genericity)\n\n\t\t\t\tif ( material.isShaderMaterial ||\n\t\t\t\t\tmaterial.isMeshPhongMaterial ||\n\t\t\t\t\tmaterial.isMeshToonMaterial ||\n\t\t\t\t\tmaterial.isMeshStandardMaterial ||\n\t\t\t\t\tmaterial.envMap ) {\n\n\t\t\t\t\tconst uCamPos = p_uniforms.map.cameraPosition;\n\n\t\t\t\t\tif ( uCamPos !== undefined ) {\n\n\t\t\t\t\t\tuCamPos.setValue( _gl,\n\t\t\t\t\t\t\t_vector3.setFromMatrixPosition( camera.matrixWorld ) );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif ( material.isMeshPhongMaterial ||\n\t\t\t\t\tmaterial.isMeshToonMaterial ||\n\t\t\t\t\tmaterial.isMeshLambertMaterial ||\n\t\t\t\t\tmaterial.isMeshBasicMaterial ||\n\t\t\t\t\tmaterial.isMeshStandardMaterial ||\n\t\t\t\t\tmaterial.isShaderMaterial ) {\n\n\t\t\t\t\tp_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );\n\n\t\t\t\t}\n\n\t\t\t\tif ( material.isMeshPhongMaterial ||\n\t\t\t\t\tmaterial.isMeshToonMaterial ||\n\t\t\t\t\tmaterial.isMeshLambertMaterial ||\n\t\t\t\t\tmaterial.isMeshBasicMaterial ||\n\t\t\t\t\tmaterial.isMeshStandardMaterial ||\n\t\t\t\t\tmaterial.isShaderMaterial ||\n\t\t\t\t\tmaterial.isShadowMaterial ||\n\t\t\t\t\tobject.isSkinnedMesh ) {\n\n\t\t\t\t\tp_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// skinning and morph target uniforms must be set even if material didn't change\n\t\t\t// auto-setting of texture unit for bone and morph texture must go before other textures\n\t\t\t// otherwise textures used for skinning and morphing can take over texture units reserved for other material textures\n\n\t\t\tif ( object.isSkinnedMesh ) {\n\n\t\t\t\tp_uniforms.setOptional( _gl, object, 'bindMatrix' );\n\t\t\t\tp_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );\n\n\t\t\t\tconst skeleton = object.skeleton;\n\n\t\t\t\tif ( skeleton ) {\n\n\t\t\t\t\tif ( capabilities.floatVertexTextures ) {\n\n\t\t\t\t\t\tif ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();\n\n\t\t\t\t\t\tp_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );\n\t\t\t\t\t\tp_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tconst morphAttributes = geometry.morphAttributes;\n\n\t\t\tif ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {\n\n\t\t\t\tmorphtargets.update( object, geometry, program );\n\n\t\t\t}\n\n\t\t\tif ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {\n\n\t\t\t\tmaterialProperties.receiveShadow = object.receiveShadow;\n\t\t\t\tp_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );\n\n\t\t\t}\n\n\t\t\t// https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512\n\n\t\t\tif ( material.isMeshGouraudMaterial && material.envMap !== null ) {\n\n\t\t\t\tm_uniforms.envMap.value = envMap;\n\n\t\t\t\tm_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;\n\n\t\t\t}\n\n\t\t\tif ( refreshMaterial ) {\n\n\t\t\t\tp_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );\n\n\t\t\t\tif ( materialProperties.needsLights ) {\n\n\t\t\t\t\t// the current material requires lighting info\n\n\t\t\t\t\t// note: all lighting uniforms are always set correctly\n\t\t\t\t\t// they simply reference the renderer's state for their\n\t\t\t\t\t// values\n\t\t\t\t\t//\n\t\t\t\t\t// use the current material's .needsUpdate flags to set\n\t\t\t\t\t// the GL state when required\n\n\t\t\t\t\tmarkUniformsLightsNeedsUpdate( m_uniforms, refreshLights );\n\n\t\t\t\t}\n\n\t\t\t\t// refresh uniforms common to several materials\n\n\t\t\t\tif ( fog && material.fog === true ) {\n\n\t\t\t\t\tmaterials.refreshFogUniforms( m_uniforms, fog );\n\n\t\t\t\t}\n\n\t\t\t\tmaterials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );\n\n\t\t\t\tWebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );\n\n\t\t\t}\n\n\t\t\tif ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {\n\n\t\t\t\tWebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );\n\t\t\t\tmaterial.uniformsNeedUpdate = false;\n\n\t\t\t}\n\n\t\t\tif ( material.isSpriteMaterial ) {\n\n\t\t\t\tp_uniforms.setValue( _gl, 'center', object.center );\n\n\t\t\t}\n\n\t\t\t// common matrices\n\n\t\t\tp_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );\n\t\t\tp_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );\n\t\t\tp_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );\n\n\t\t\t// UBOs\n\n\t\t\tif ( material.isShaderMaterial || material.isRawShaderMaterial ) {\n\n\t\t\t\tconst groups = material.uniformsGroups;\n\n\t\t\t\tfor ( let i = 0, l = groups.length; i < l; i ++ ) {\n\n\t\t\t\t\tif ( capabilities.isWebGL2 ) {\n\n\t\t\t\t\t\tconst group = groups[ i ];\n\n\t\t\t\t\t\tuniformsGroups.update( group, program );\n\t\t\t\t\t\tuniformsGroups.bind( group, program );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn program;\n\n\t\t}\n\n\t\t// If uniforms are marked as clean, they don't need to be loaded to the GPU.\n\n\t\tfunction markUniformsLightsNeedsUpdate( uniforms, value ) {\n\n\t\t\tuniforms.ambientLightColor.needsUpdate = value;\n\t\t\tuniforms.lightProbe.needsUpdate = value;\n\n\t\t\tuniforms.directionalLights.needsUpdate = value;\n\t\t\tuniforms.directionalLightShadows.needsUpdate = value;\n\t\t\tuniforms.pointLights.needsUpdate = value;\n\t\t\tuniforms.pointLightShadows.needsUpdate = value;\n\t\t\tuniforms.spotLights.needsUpdate = value;\n\t\t\tuniforms.spotLightShadows.needsUpdate = value;\n\t\t\tuniforms.rectAreaLights.needsUpdate = value;\n\t\t\tuniforms.hemisphereLights.needsUpdate = value;\n\n\t\t}\n\n\t\tfunction materialNeedsLights( material ) {\n\n\t\t\treturn material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||\n\t\t\t\tmaterial.isMeshStandardMaterial || material.isShadowMaterial ||\n\t\t\t\t( material.isShaderMaterial && material.lights === true );\n\n\t\t}\n\n\t\tthis.getActiveCubeFace = function () {\n\n\t\t\treturn _currentActiveCubeFace;\n\n\t\t};\n\n\t\tthis.getActiveMipmapLevel = function () {\n\n\t\t\treturn _currentActiveMipmapLevel;\n\n\t\t};\n\n\t\tthis.getRenderTarget = function () {\n\n\t\t\treturn _currentRenderTarget;\n\n\t\t};\n\n\t\tthis.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {\n\n\t\t\tproperties.get( renderTarget.texture ).__webglTexture = colorTexture;\n\t\t\tproperties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;\n\n\t\t\tconst renderTargetProperties = properties.get( renderTarget );\n\t\t\trenderTargetProperties.__hasExternalTextures = true;\n\n\t\t\tif ( renderTargetProperties.__hasExternalTextures ) {\n\n\t\t\t\trenderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;\n\n\t\t\t\tif ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {\n\n\t\t\t\t\t// The multisample_render_to_texture extension doesn't work properly if there\n\t\t\t\t\t// are midframe flushes and an external depth buffer. Disable use of the extension.\n\t\t\t\t\tif ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {\n\n\t\t\t\t\t\tconsole.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );\n\t\t\t\t\t\trenderTargetProperties.__useRenderToTexture = false;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t};\n\n\t\tthis.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {\n\n\t\t\tconst renderTargetProperties = properties.get( renderTarget );\n\t\t\trenderTargetProperties.__webglFramebuffer = defaultFramebuffer;\n\t\t\trenderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;\n\n\t\t};\n\n\t\tthis.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {\n\n\t\t\t_currentRenderTarget = renderTarget;\n\t\t\t_currentActiveCubeFace = activeCubeFace;\n\t\t\t_currentActiveMipmapLevel = activeMipmapLevel;\n\n\t\t\tlet useDefaultFramebuffer = true;\n\t\t\tlet framebuffer = null;\n\t\t\tlet isCube = false;\n\t\t\tlet isRenderTarget3D = false;\n\n\t\t\tif ( renderTarget ) {\n\n\t\t\t\tconst renderTargetProperties = properties.get( renderTarget );\n\n\t\t\t\tif ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {\n\n\t\t\t\t\t// We need to make sure to rebind the framebuffer.\n\t\t\t\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, null );\n\t\t\t\t\tuseDefaultFramebuffer = false;\n\n\t\t\t\t} else if ( renderTargetProperties.__webglFramebuffer === undefined ) {\n\n\t\t\t\t\ttextures.setupRenderTarget( renderTarget );\n\n\t\t\t\t} else if ( renderTargetProperties.__hasExternalTextures ) {\n\n\t\t\t\t\t// Color and depth texture must be rebound in order for the swapchain to update.\n\t\t\t\t\ttextures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );\n\n\t\t\t\t}\n\n\t\t\t\tconst texture = renderTarget.texture;\n\n\t\t\t\tif ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {\n\n\t\t\t\t\tisRenderTarget3D = true;\n\n\t\t\t\t}\n\n\t\t\t\tconst __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;\n\n\t\t\t\tif ( renderTarget.isWebGLCubeRenderTarget ) {\n\n\t\t\t\t\tframebuffer = __webglFramebuffer[ activeCubeFace ];\n\t\t\t\t\tisCube = true;\n\n\t\t\t\t} else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {\n\n\t\t\t\t\tframebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tframebuffer = __webglFramebuffer;\n\n\t\t\t\t}\n\n\t\t\t\t_currentViewport.copy( renderTarget.viewport );\n\t\t\t\t_currentScissor.copy( renderTarget.scissor );\n\t\t\t\t_currentScissorTest = renderTarget.scissorTest;\n\n\t\t\t} else {\n\n\t\t\t\t_currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();\n\t\t\t\t_currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();\n\t\t\t\t_currentScissorTest = _scissorTest;\n\n\t\t\t}\n\n\t\t\tconst framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );\n\n\t\t\tif ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {\n\n\t\t\t\tstate.drawBuffers( renderTarget, framebuffer );\n\n\t\t\t}\n\n\t\t\tstate.viewport( _currentViewport );\n\t\t\tstate.scissor( _currentScissor );\n\t\t\tstate.setScissorTest( _currentScissorTest );\n\n\t\t\tif ( isCube ) {\n\n\t\t\t\tconst textureProperties = properties.get( renderTarget.texture );\n\t\t\t\t_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );\n\n\t\t\t} else if ( isRenderTarget3D ) {\n\n\t\t\t\tconst textureProperties = properties.get( renderTarget.texture );\n\t\t\t\tconst layer = activeCubeFace || 0;\n\t\t\t\t_gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );\n\n\t\t\t}\n\n\t\t\t_currentMaterialId = - 1; // reset current material to ensure correct uniform bindings\n\n\t\t};\n\n\t\tthis.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {\n\n\t\t\tif ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {\n\n\t\t\t\tconsole.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tlet framebuffer = properties.get( renderTarget ).__webglFramebuffer;\n\n\t\t\tif ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {\n\n\t\t\t\tframebuffer = framebuffer[ activeCubeFaceIndex ];\n\n\t\t\t}\n\n\t\t\tif ( framebuffer ) {\n\n\t\t\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );\n\n\t\t\t\ttry {\n\n\t\t\t\t\tconst texture = renderTarget.texture;\n\t\t\t\t\tconst textureFormat = texture.format;\n\t\t\t\t\tconst textureType = texture.type;\n\n\t\t\t\t\tif ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {\n\n\t\t\t\t\t\tconsole.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tconst halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );\n\n\t\t\t\t\tif ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)\n\t\t\t\t\t\t! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox\n\t\t\t\t\t\t! halfFloatSupportedByExt ) {\n\n\t\t\t\t\t\tconsole.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)\n\n\t\t\t\t\tif ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {\n\n\t\t\t\t\t\t_gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );\n\n\t\t\t\t\t}\n\n\t\t\t\t} finally {\n\n\t\t\t\t\t// restore framebuffer of current render target if necessary\n\n\t\t\t\t\tconst framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;\n\t\t\t\t\tstate.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t};\n\n\t\tthis.copyFramebufferToTexture = function ( position, texture, level = 0 ) {\n\n\t\t\tconst levelScale = Math.pow( 2, - level );\n\t\t\tconst width = Math.floor( texture.image.width * levelScale );\n\t\t\tconst height = Math.floor( texture.image.height * levelScale );\n\n\t\t\ttextures.setTexture2D( texture, 0 );\n\n\t\t\t_gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );\n\n\t\t\tstate.unbindTexture();\n\n\t\t};\n\n\t\tthis.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {\n\n\t\t\tconst width = srcTexture.image.width;\n\t\t\tconst height = srcTexture.image.height;\n\t\t\tconst glFormat = utils.convert( dstTexture.format );\n\t\t\tconst glType = utils.convert( dstTexture.type );\n\n\t\t\ttextures.setTexture2D( dstTexture, 0 );\n\n\t\t\t// As another texture upload may have changed pixelStorei\n\t\t\t// parameters, make sure they are correct for the dstTexture\n\t\t\t_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );\n\n\t\t\tif ( srcTexture.isDataTexture ) {\n\n\t\t\t\t_gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );\n\n\t\t\t} else {\n\n\t\t\t\tif ( srcTexture.isCompressedTexture ) {\n\n\t\t\t\t\t_gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t_gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// Generate mipmaps only when copying level 0\n\t\t\tif ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );\n\n\t\t\tstate.unbindTexture();\n\n\t\t};\n\n\t\tthis.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {\n\n\t\t\tif ( _this.isWebGL1Renderer ) {\n\n\t\t\t\tconsole.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tconst width = sourceBox.max.x - sourceBox.min.x + 1;\n\t\t\tconst height = sourceBox.max.y - sourceBox.min.y + 1;\n\t\t\tconst depth = sourceBox.max.z - sourceBox.min.z + 1;\n\t\t\tconst glFormat = utils.convert( dstTexture.format );\n\t\t\tconst glType = utils.convert( dstTexture.type );\n\t\t\tlet glTarget;\n\n\t\t\tif ( dstTexture.isData3DTexture ) {\n\n\t\t\t\ttextures.setTexture3D( dstTexture, 0 );\n\t\t\t\tglTarget = _gl.TEXTURE_3D;\n\n\t\t\t} else if ( dstTexture.isDataArrayTexture ) {\n\n\t\t\t\ttextures.setTexture2DArray( dstTexture, 0 );\n\t\t\t\tglTarget = _gl.TEXTURE_2D_ARRAY;\n\n\t\t\t} else {\n\n\t\t\t\tconsole.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\t_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );\n\n\t\t\tconst unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );\n\t\t\tconst unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );\n\t\t\tconst unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );\n\t\t\tconst unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );\n\t\t\tconst unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );\n\n\t\t\tconst image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;\n\n\t\t\t_gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );\n\n\t\t\tif ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {\n\n\t\t\t\t_gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );\n\n\t\t\t} else {\n\n\t\t\t\tif ( srcTexture.isCompressedArrayTexture ) {\n\n\t\t\t\t\tconsole.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );\n\t\t\t\t\t_gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t_gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t_gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );\n\t\t\t_gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );\n\n\t\t\t// Generate mipmaps only when copying level 0\n\t\t\tif ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );\n\n\t\t\tstate.unbindTexture();\n\n\t\t};\n\n\t\tthis.initTexture = function ( texture ) {\n\n\t\t\tif ( texture.isCubeTexture ) {\n\n\t\t\t\ttextures.setTextureCube( texture, 0 );\n\n\t\t\t} else if ( texture.isData3DTexture ) {\n\n\t\t\t\ttextures.setTexture3D( texture, 0 );\n\n\t\t\t} else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {\n\n\t\t\t\ttextures.setTexture2DArray( texture, 0 );\n\n\t\t\t} else {\n\n\t\t\t\ttextures.setTexture2D( texture, 0 );\n\n\t\t\t}\n\n\t\t\tstate.unbindTexture();\n\n\t\t};\n\n\t\tthis.resetState = function () {\n\n\t\t\t_currentActiveCubeFace = 0;\n\t\t\t_currentActiveMipmapLevel = 0;\n\t\t\t_currentRenderTarget = null;\n\n\t\t\tstate.reset();\n\t\t\tbindingStates.reset();\n\n\t\t};\n\n\t\tif ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {\n\n\t\t\t__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );\n\n\t\t}\n\n\t}\n\n\tget physicallyCorrectLights() { // @deprecated, r150\n\n\t\tconsole.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );\n\t\treturn ! this.useLegacyLights;\n\n\t}\n\n\tset physicallyCorrectLights( value ) { // @deprecated, r150\n\n\t\tconsole.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );\n\t\tthis.useLegacyLights = ! value;\n\n\t}\n\n\tget outputEncoding() { // @deprecated, r152\n\n\t\tconsole.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' );\n\t\treturn this.outputColorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding;\n\n\t}\n\n\tset outputEncoding( encoding ) { // @deprecated, r152\n\n\t\tconsole.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' );\n\t\tthis.outputColorSpace = encoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;\n\n\t}\n\n}\n\nclass WebGL1Renderer extends WebGLRenderer {}\n\nWebGL1Renderer.prototype.isWebGL1Renderer = true;\n\nclass FogExp2 {\n\n\tconstructor( color, density = 0.00025 ) {\n\n\t\tthis.isFogExp2 = true;\n\n\t\tthis.name = '';\n\n\t\tthis.color = new Color( color );\n\t\tthis.density = density;\n\n\t}\n\n\tclone() {\n\n\t\treturn new FogExp2( this.color, this.density );\n\n\t}\n\n\ttoJSON( /* meta */ ) {\n\n\t\treturn {\n\t\t\ttype: 'FogExp2',\n\t\t\tcolor: this.color.getHex(),\n\t\t\tdensity: this.density\n\t\t};\n\n\t}\n\n}\n\nclass Fog {\n\n\tconstructor( color, near = 1, far = 1000 ) {\n\n\t\tthis.isFog = true;\n\n\t\tthis.name = '';\n\n\t\tthis.color = new Color( color );\n\n\t\tthis.near = near;\n\t\tthis.far = far;\n\n\t}\n\n\tclone() {\n\n\t\treturn new Fog( this.color, this.near, this.far );\n\n\t}\n\n\ttoJSON( /* meta */ ) {\n\n\t\treturn {\n\t\t\ttype: 'Fog',\n\t\t\tcolor: this.color.getHex(),\n\t\t\tnear: this.near,\n\t\t\tfar: this.far\n\t\t};\n\n\t}\n\n}\n\nclass Scene extends Object3D {\n\n\tconstructor() {\n\n\t\tsuper();\n\n\t\tthis.isScene = true;\n\n\t\tthis.type = 'Scene';\n\n\t\tthis.background = null;\n\t\tthis.environment = null;\n\t\tthis.fog = null;\n\n\t\tthis.backgroundBlurriness = 0;\n\t\tthis.backgroundIntensity = 1;\n\n\t\tthis.overrideMaterial = null;\n\n\t\tif ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {\n\n\t\t\t__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );\n\n\t\t}\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tif ( source.background !== null ) this.background = source.background.clone();\n\t\tif ( source.environment !== null ) this.environment = source.environment.clone();\n\t\tif ( source.fog !== null ) this.fog = source.fog.clone();\n\n\t\tthis.backgroundBlurriness = source.backgroundBlurriness;\n\t\tthis.backgroundIntensity = source.backgroundIntensity;\n\n\t\tif ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();\n\n\t\tthis.matrixAutoUpdate = source.matrixAutoUpdate;\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON( meta ) {\n\n\t\tconst data = super.toJSON( meta );\n\n\t\tif ( this.fog !== null ) data.object.fog = this.fog.toJSON();\n\t\tif ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;\n\t\tif ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;\n\n\t\treturn data;\n\n\t}\n\n\tget autoUpdate() { // @deprecated, r144\n\n\t\tconsole.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );\n\t\treturn this.matrixWorldAutoUpdate;\n\n\t}\n\n\tset autoUpdate( value ) { // @deprecated, r144\n\n\t\tconsole.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );\n\t\tthis.matrixWorldAutoUpdate = value;\n\n\t}\n\n}\n\nclass InterleavedBuffer {\n\n\tconstructor( array, stride ) {\n\n\t\tthis.isInterleavedBuffer = true;\n\n\t\tthis.array = array;\n\t\tthis.stride = stride;\n\t\tthis.count = array !== undefined ? array.length / stride : 0;\n\n\t\tthis.usage = StaticDrawUsage;\n\t\tthis.updateRange = { offset: 0, count: - 1 };\n\n\t\tthis.version = 0;\n\n\t\tthis.uuid = generateUUID();\n\n\t}\n\n\tonUploadCallback() {}\n\n\tset needsUpdate( value ) {\n\n\t\tif ( value === true ) this.version ++;\n\n\t}\n\n\tsetUsage( value ) {\n\n\t\tthis.usage = value;\n\n\t\treturn this;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tthis.array = new source.array.constructor( source.array );\n\t\tthis.count = source.count;\n\t\tthis.stride = source.stride;\n\t\tthis.usage = source.usage;\n\n\t\treturn this;\n\n\t}\n\n\tcopyAt( index1, attribute, index2 ) {\n\n\t\tindex1 *= this.stride;\n\t\tindex2 *= attribute.stride;\n\n\t\tfor ( let i = 0, l = this.stride; i < l; i ++ ) {\n\n\t\t\tthis.array[ index1 + i ] = attribute.array[ index2 + i ];\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tset( value, offset = 0 ) {\n\n\t\tthis.array.set( value, offset );\n\n\t\treturn this;\n\n\t}\n\n\tclone( data ) {\n\n\t\tif ( data.arrayBuffers === undefined ) {\n\n\t\t\tdata.arrayBuffers = {};\n\n\t\t}\n\n\t\tif ( this.array.buffer._uuid === undefined ) {\n\n\t\t\tthis.array.buffer._uuid = generateUUID();\n\n\t\t}\n\n\t\tif ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {\n\n\t\t\tdata.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;\n\n\t\t}\n\n\t\tconst array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );\n\n\t\tconst ib = new this.constructor( array, this.stride );\n\t\tib.setUsage( this.usage );\n\n\t\treturn ib;\n\n\t}\n\n\tonUpload( callback ) {\n\n\t\tthis.onUploadCallback = callback;\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON( data ) {\n\n\t\tif ( data.arrayBuffers === undefined ) {\n\n\t\t\tdata.arrayBuffers = {};\n\n\t\t}\n\n\t\t// generate UUID for array buffer if necessary\n\n\t\tif ( this.array.buffer._uuid === undefined ) {\n\n\t\t\tthis.array.buffer._uuid = generateUUID();\n\n\t\t}\n\n\t\tif ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {\n\n\t\t\tdata.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );\n\n\t\t}\n\n\t\t//\n\n\t\treturn {\n\t\t\tuuid: this.uuid,\n\t\t\tbuffer: this.array.buffer._uuid,\n\t\t\ttype: this.array.constructor.name,\n\t\t\tstride: this.stride\n\t\t};\n\n\t}\n\n}\n\nconst _vector$5 = /*@__PURE__*/ new Vector3();\n\nclass InterleavedBufferAttribute {\n\n\tconstructor( interleavedBuffer, itemSize, offset, normalized = false ) {\n\n\t\tthis.isInterleavedBufferAttribute = true;\n\n\t\tthis.name = '';\n\n\t\tthis.data = interleavedBuffer;\n\t\tthis.itemSize = itemSize;\n\t\tthis.offset = offset;\n\n\t\tthis.normalized = normalized;\n\n\t}\n\n\tget count() {\n\n\t\treturn this.data.count;\n\n\t}\n\n\tget array() {\n\n\t\treturn this.data.array;\n\n\t}\n\n\tset needsUpdate( value ) {\n\n\t\tthis.data.needsUpdate = value;\n\n\t}\n\n\tapplyMatrix4( m ) {\n\n\t\tfor ( let i = 0, l = this.data.count; i < l; i ++ ) {\n\n\t\t\t_vector$5.fromBufferAttribute( this, i );\n\n\t\t\t_vector$5.applyMatrix4( m );\n\n\t\t\tthis.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tapplyNormalMatrix( m ) {\n\n\t\tfor ( let i = 0, l = this.count; i < l; i ++ ) {\n\n\t\t\t_vector$5.fromBufferAttribute( this, i );\n\n\t\t\t_vector$5.applyNormalMatrix( m );\n\n\t\t\tthis.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\ttransformDirection( m ) {\n\n\t\tfor ( let i = 0, l = this.count; i < l; i ++ ) {\n\n\t\t\t_vector$5.fromBufferAttribute( this, i );\n\n\t\t\t_vector$5.transformDirection( m );\n\n\t\t\tthis.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tsetX( index, x ) {\n\n\t\tif ( this.normalized ) x = normalize( x, this.array );\n\n\t\tthis.data.array[ index * this.data.stride + this.offset ] = x;\n\n\t\treturn this;\n\n\t}\n\n\tsetY( index, y ) {\n\n\t\tif ( this.normalized ) y = normalize( y, this.array );\n\n\t\tthis.data.array[ index * this.data.stride + this.offset + 1 ] = y;\n\n\t\treturn this;\n\n\t}\n\n\tsetZ( index, z ) {\n\n\t\tif ( this.normalized ) z = normalize( z, this.array );\n\n\t\tthis.data.array[ index * this.data.stride + this.offset + 2 ] = z;\n\n\t\treturn this;\n\n\t}\n\n\tsetW( index, w ) {\n\n\t\tif ( this.normalized ) w = normalize( w, this.array );\n\n\t\tthis.data.array[ index * this.data.stride + this.offset + 3 ] = w;\n\n\t\treturn this;\n\n\t}\n\n\tgetX( index ) {\n\n\t\tlet x = this.data.array[ index * this.data.stride + this.offset ];\n\n\t\tif ( this.normalized ) x = denormalize( x, this.array );\n\n\t\treturn x;\n\n\t}\n\n\tgetY( index ) {\n\n\t\tlet y = this.data.array[ index * this.data.stride + this.offset + 1 ];\n\n\t\tif ( this.normalized ) y = denormalize( y, this.array );\n\n\t\treturn y;\n\n\t}\n\n\tgetZ( index ) {\n\n\t\tlet z = this.data.array[ index * this.data.stride + this.offset + 2 ];\n\n\t\tif ( this.normalized ) z = denormalize( z, this.array );\n\n\t\treturn z;\n\n\t}\n\n\tgetW( index ) {\n\n\t\tlet w = this.data.array[ index * this.data.stride + this.offset + 3 ];\n\n\t\tif ( this.normalized ) w = denormalize( w, this.array );\n\n\t\treturn w;\n\n\t}\n\n\tsetXY( index, x, y ) {\n\n\t\tindex = index * this.data.stride + this.offset;\n\n\t\tif ( this.normalized ) {\n\n\t\t\tx = normalize( x, this.array );\n\t\t\ty = normalize( y, this.array );\n\n\t\t}\n\n\t\tthis.data.array[ index + 0 ] = x;\n\t\tthis.data.array[ index + 1 ] = y;\n\n\t\treturn this;\n\n\t}\n\n\tsetXYZ( index, x, y, z ) {\n\n\t\tindex = index * this.data.stride + this.offset;\n\n\t\tif ( this.normalized ) {\n\n\t\t\tx = normalize( x, this.array );\n\t\t\ty = normalize( y, this.array );\n\t\t\tz = normalize( z, this.array );\n\n\t\t}\n\n\t\tthis.data.array[ index + 0 ] = x;\n\t\tthis.data.array[ index + 1 ] = y;\n\t\tthis.data.array[ index + 2 ] = z;\n\n\t\treturn this;\n\n\t}\n\n\tsetXYZW( index, x, y, z, w ) {\n\n\t\tindex = index * this.data.stride + this.offset;\n\n\t\tif ( this.normalized ) {\n\n\t\t\tx = normalize( x, this.array );\n\t\t\ty = normalize( y, this.array );\n\t\t\tz = normalize( z, this.array );\n\t\t\tw = normalize( w, this.array );\n\n\t\t}\n\n\t\tthis.data.array[ index + 0 ] = x;\n\t\tthis.data.array[ index + 1 ] = y;\n\t\tthis.data.array[ index + 2 ] = z;\n\t\tthis.data.array[ index + 3 ] = w;\n\n\t\treturn this;\n\n\t}\n\n\tclone( data ) {\n\n\t\tif ( data === undefined ) {\n\n\t\t\tconsole.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );\n\n\t\t\tconst array = [];\n\n\t\t\tfor ( let i = 0; i < this.count; i ++ ) {\n\n\t\t\t\tconst index = i * this.data.stride + this.offset;\n\n\t\t\t\tfor ( let j = 0; j < this.itemSize; j ++ ) {\n\n\t\t\t\t\tarray.push( this.data.array[ index + j ] );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );\n\n\t\t} else {\n\n\t\t\tif ( data.interleavedBuffers === undefined ) {\n\n\t\t\t\tdata.interleavedBuffers = {};\n\n\t\t\t}\n\n\t\t\tif ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {\n\n\t\t\t\tdata.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );\n\n\t\t\t}\n\n\t\t\treturn new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );\n\n\t\t}\n\n\t}\n\n\ttoJSON( data ) {\n\n\t\tif ( data === undefined ) {\n\n\t\t\tconsole.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );\n\n\t\t\tconst array = [];\n\n\t\t\tfor ( let i = 0; i < this.count; i ++ ) {\n\n\t\t\t\tconst index = i * this.data.stride + this.offset;\n\n\t\t\t\tfor ( let j = 0; j < this.itemSize; j ++ ) {\n\n\t\t\t\t\tarray.push( this.data.array[ index + j ] );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// de-interleave data and save it as an ordinary buffer attribute for now\n\n\t\t\treturn {\n\t\t\t\titemSize: this.itemSize,\n\t\t\t\ttype: this.array.constructor.name,\n\t\t\t\tarray: array,\n\t\t\t\tnormalized: this.normalized\n\t\t\t};\n\n\t\t} else {\n\n\t\t\t// save as true interleaved attribute\n\n\t\t\tif ( data.interleavedBuffers === undefined ) {\n\n\t\t\t\tdata.interleavedBuffers = {};\n\n\t\t\t}\n\n\t\t\tif ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {\n\n\t\t\t\tdata.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );\n\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tisInterleavedBufferAttribute: true,\n\t\t\t\titemSize: this.itemSize,\n\t\t\t\tdata: this.data.uuid,\n\t\t\t\toffset: this.offset,\n\t\t\t\tnormalized: this.normalized\n\t\t\t};\n\n\t\t}\n\n\t}\n\n}\n\nclass SpriteMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isSpriteMaterial = true;\n\n\t\tthis.type = 'SpriteMaterial';\n\n\t\tthis.color = new Color( 0xffffff );\n\n\t\tthis.map = null;\n\n\t\tthis.alphaMap = null;\n\n\t\tthis.rotation = 0;\n\n\t\tthis.sizeAttenuation = true;\n\n\t\tthis.transparent = true;\n\n\t\tthis.fog = true;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.color.copy( source.color );\n\n\t\tthis.map = source.map;\n\n\t\tthis.alphaMap = source.alphaMap;\n\n\t\tthis.rotation = source.rotation;\n\n\t\tthis.sizeAttenuation = source.sizeAttenuation;\n\n\t\tthis.fog = source.fog;\n\n\t\treturn this;\n\n\t}\n\n}\n\nlet _geometry;\n\nconst _intersectPoint = /*@__PURE__*/ new Vector3();\nconst _worldScale = /*@__PURE__*/ new Vector3();\nconst _mvPosition = /*@__PURE__*/ new Vector3();\n\nconst _alignedPosition = /*@__PURE__*/ new Vector2();\nconst _rotatedPosition = /*@__PURE__*/ new Vector2();\nconst _viewWorldMatrix = /*@__PURE__*/ new Matrix4();\n\nconst _vA = /*@__PURE__*/ new Vector3();\nconst _vB = /*@__PURE__*/ new Vector3();\nconst _vC = /*@__PURE__*/ new Vector3();\n\nconst _uvA = /*@__PURE__*/ new Vector2();\nconst _uvB = /*@__PURE__*/ new Vector2();\nconst _uvC = /*@__PURE__*/ new Vector2();\n\nclass Sprite extends Object3D {\n\n\tconstructor( material ) {\n\n\t\tsuper();\n\n\t\tthis.isSprite = true;\n\n\t\tthis.type = 'Sprite';\n\n\t\tif ( _geometry === undefined ) {\n\n\t\t\t_geometry = new BufferGeometry();\n\n\t\t\tconst float32Array = new Float32Array( [\n\t\t\t\t- 0.5, - 0.5, 0, 0, 0,\n\t\t\t\t0.5, - 0.5, 0, 1, 0,\n\t\t\t\t0.5, 0.5, 0, 1, 1,\n\t\t\t\t- 0.5, 0.5, 0, 0, 1\n\t\t\t] );\n\n\t\t\tconst interleavedBuffer = new InterleavedBuffer( float32Array, 5 );\n\n\t\t\t_geometry.setIndex( [ 0, 1, 2,\t0, 2, 3 ] );\n\t\t\t_geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );\n\t\t\t_geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );\n\n\t\t}\n\n\t\tthis.geometry = _geometry;\n\t\tthis.material = ( material !== undefined ) ? material : new SpriteMaterial();\n\n\t\tthis.center = new Vector2( 0.5, 0.5 );\n\n\t}\n\n\traycast( raycaster, intersects ) {\n\n\t\tif ( raycaster.camera === null ) {\n\n\t\t\tconsole.error( 'THREE.Sprite: \"Raycaster.camera\" needs to be set in order to raycast against sprites.' );\n\n\t\t}\n\n\t\t_worldScale.setFromMatrixScale( this.matrixWorld );\n\n\t\t_viewWorldMatrix.copy( raycaster.camera.matrixWorld );\n\t\tthis.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );\n\n\t\t_mvPosition.setFromMatrixPosition( this.modelViewMatrix );\n\n\t\tif ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {\n\n\t\t\t_worldScale.multiplyScalar( - _mvPosition.z );\n\n\t\t}\n\n\t\tconst rotation = this.material.rotation;\n\t\tlet sin, cos;\n\n\t\tif ( rotation !== 0 ) {\n\n\t\t\tcos = Math.cos( rotation );\n\t\t\tsin = Math.sin( rotation );\n\n\t\t}\n\n\t\tconst center = this.center;\n\n\t\ttransformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );\n\t\ttransformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );\n\t\ttransformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );\n\n\t\t_uvA.set( 0, 0 );\n\t\t_uvB.set( 1, 0 );\n\t\t_uvC.set( 1, 1 );\n\n\t\t// check first triangle\n\t\tlet intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );\n\n\t\tif ( intersect === null ) {\n\n\t\t\t// check second triangle\n\t\t\ttransformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );\n\t\t\t_uvB.set( 0, 1 );\n\n\t\t\tintersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );\n\t\t\tif ( intersect === null ) {\n\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst distance = raycaster.ray.origin.distanceTo( _intersectPoint );\n\n\t\tif ( distance < raycaster.near || distance > raycaster.far ) return;\n\n\t\tintersects.push( {\n\n\t\t\tdistance: distance,\n\t\t\tpoint: _intersectPoint.clone(),\n\t\t\tuv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),\n\t\t\tface: null,\n\t\t\tobject: this\n\n\t\t} );\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tif ( source.center !== undefined ) this.center.copy( source.center );\n\n\t\tthis.material = source.material;\n\n\t\treturn this;\n\n\t}\n\n}\n\nfunction transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {\n\n\t// compute position in camera space\n\t_alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );\n\n\t// to check if rotation is not zero\n\tif ( sin !== undefined ) {\n\n\t\t_rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );\n\t\t_rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );\n\n\t} else {\n\n\t\t_rotatedPosition.copy( _alignedPosition );\n\n\t}\n\n\n\tvertexPosition.copy( mvPosition );\n\tvertexPosition.x += _rotatedPosition.x;\n\tvertexPosition.y += _rotatedPosition.y;\n\n\t// transform to world space\n\tvertexPosition.applyMatrix4( _viewWorldMatrix );\n\n}\n\nconst _v1$2 = /*@__PURE__*/ new Vector3();\nconst _v2$1 = /*@__PURE__*/ new Vector3();\n\nclass LOD extends Object3D {\n\n\tconstructor() {\n\n\t\tsuper();\n\n\t\tthis._currentLevel = 0;\n\n\t\tthis.type = 'LOD';\n\n\t\tObject.defineProperties( this, {\n\t\t\tlevels: {\n\t\t\t\tenumerable: true,\n\t\t\t\tvalue: []\n\t\t\t},\n\t\t\tisLOD: {\n\t\t\t\tvalue: true,\n\t\t\t}\n\t\t} );\n\n\t\tthis.autoUpdate = true;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source, false );\n\n\t\tconst levels = source.levels;\n\n\t\tfor ( let i = 0, l = levels.length; i < l; i ++ ) {\n\n\t\t\tconst level = levels[ i ];\n\n\t\t\tthis.addLevel( level.object.clone(), level.distance, level.hysteresis );\n\n\t\t}\n\n\t\tthis.autoUpdate = source.autoUpdate;\n\n\t\treturn this;\n\n\t}\n\n\taddLevel( object, distance = 0, hysteresis = 0 ) {\n\n\t\tdistance = Math.abs( distance );\n\n\t\tconst levels = this.levels;\n\n\t\tlet l;\n\n\t\tfor ( l = 0; l < levels.length; l ++ ) {\n\n\t\t\tif ( distance < levels[ l ].distance ) {\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t}\n\n\t\tlevels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );\n\n\t\tthis.add( object );\n\n\t\treturn this;\n\n\t}\n\n\tgetCurrentLevel() {\n\n\t\treturn this._currentLevel;\n\n\t}\n\n\n\n\tgetObjectForDistance( distance ) {\n\n\t\tconst levels = this.levels;\n\n\t\tif ( levels.length > 0 ) {\n\n\t\t\tlet i, l;\n\n\t\t\tfor ( i = 1, l = levels.length; i < l; i ++ ) {\n\n\t\t\t\tlet levelDistance = levels[ i ].distance;\n\n\t\t\t\tif ( levels[ i ].object.visible ) {\n\n\t\t\t\t\tlevelDistance -= levelDistance * levels[ i ].hysteresis;\n\n\t\t\t\t}\n\n\t\t\t\tif ( distance < levelDistance ) {\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn levels[ i - 1 ].object;\n\n\t\t}\n\n\t\treturn null;\n\n\t}\n\n\traycast( raycaster, intersects ) {\n\n\t\tconst levels = this.levels;\n\n\t\tif ( levels.length > 0 ) {\n\n\t\t\t_v1$2.setFromMatrixPosition( this.matrixWorld );\n\n\t\t\tconst distance = raycaster.ray.origin.distanceTo( _v1$2 );\n\n\t\t\tthis.getObjectForDistance( distance ).raycast( raycaster, intersects );\n\n\t\t}\n\n\t}\n\n\tupdate( camera ) {\n\n\t\tconst levels = this.levels;\n\n\t\tif ( levels.length > 1 ) {\n\n\t\t\t_v1$2.setFromMatrixPosition( camera.matrixWorld );\n\t\t\t_v2$1.setFromMatrixPosition( this.matrixWorld );\n\n\t\t\tconst distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;\n\n\t\t\tlevels[ 0 ].object.visible = true;\n\n\t\t\tlet i, l;\n\n\t\t\tfor ( i = 1, l = levels.length; i < l; i ++ ) {\n\n\t\t\t\tlet levelDistance = levels[ i ].distance;\n\n\t\t\t\tif ( levels[ i ].object.visible ) {\n\n\t\t\t\t\tlevelDistance -= levelDistance * levels[ i ].hysteresis;\n\n\t\t\t\t}\n\n\t\t\t\tif ( distance >= levelDistance ) {\n\n\t\t\t\t\tlevels[ i - 1 ].object.visible = false;\n\t\t\t\t\tlevels[ i ].object.visible = true;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tthis._currentLevel = i - 1;\n\n\t\t\tfor ( ; i < l; i ++ ) {\n\n\t\t\t\tlevels[ i ].object.visible = false;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\ttoJSON( meta ) {\n\n\t\tconst data = super.toJSON( meta );\n\n\t\tif ( this.autoUpdate === false ) data.object.autoUpdate = false;\n\n\t\tdata.object.levels = [];\n\n\t\tconst levels = this.levels;\n\n\t\tfor ( let i = 0, l = levels.length; i < l; i ++ ) {\n\n\t\t\tconst level = levels[ i ];\n\n\t\t\tdata.object.levels.push( {\n\t\t\t\tobject: level.object.uuid,\n\t\t\t\tdistance: level.distance,\n\t\t\t\thysteresis: level.hysteresis\n\t\t\t} );\n\n\t\t}\n\n\t\treturn data;\n\n\t}\n\n}\n\nconst _basePosition = /*@__PURE__*/ new Vector3();\n\nconst _skinIndex = /*@__PURE__*/ new Vector4();\nconst _skinWeight = /*@__PURE__*/ new Vector4();\n\nconst _vector3 = /*@__PURE__*/ new Vector3();\nconst _matrix4 = /*@__PURE__*/ new Matrix4();\nconst _vertex = /*@__PURE__*/ new Vector3();\n\n\n\nclass SkinnedMesh extends Mesh {\n\n\tconstructor( geometry, material ) {\n\n\t\tsuper( geometry, material );\n\n\t\tthis.isSkinnedMesh = true;\n\n\t\tthis.type = 'SkinnedMesh';\n\n\t\tthis.bindMode = 'attached';\n\t\tthis.bindMatrix = new Matrix4();\n\t\tthis.bindMatrixInverse = new Matrix4();\n\n\t\tthis.boundingBox = null;\n\t\tthis.boundingSphere = null;\n\n\t}\n\n\tcomputeBoundingBox() {\n\n\t\tconst geometry = this.geometry;\n\n\t\tif ( this.boundingBox === null ) {\n\n\t\t\tthis.boundingBox = new Box3();\n\n\t\t}\n\n\t\tthis.boundingBox.makeEmpty();\n\n\t\tconst positionAttribute = geometry.getAttribute( 'position' );\n\n\t\tfor ( let i = 0; i < positionAttribute.count; i ++ ) {\n\n\t\t\t_vertex.fromBufferAttribute( positionAttribute, i );\n\t\t\tthis.applyBoneTransform( i, _vertex );\n\t\t\tthis.boundingBox.expandByPoint( _vertex );\n\n\t\t}\n\n\t}\n\n\tcomputeBoundingSphere() {\n\n\t\tconst geometry = this.geometry;\n\n\t\tif ( this.boundingSphere === null ) {\n\n\t\t\tthis.boundingSphere = new Sphere();\n\n\t\t}\n\n\t\tthis.boundingSphere.makeEmpty();\n\n\t\tconst positionAttribute = geometry.getAttribute( 'position' );\n\n\t\tfor ( let i = 0; i < positionAttribute.count; i ++ ) {\n\n\t\t\t_vertex.fromBufferAttribute( positionAttribute, i );\n\t\t\tthis.applyBoneTransform( i, _vertex );\n\t\t\tthis.boundingSphere.expandByPoint( _vertex );\n\n\t\t}\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tthis.bindMode = source.bindMode;\n\t\tthis.bindMatrix.copy( source.bindMatrix );\n\t\tthis.bindMatrixInverse.copy( source.bindMatrixInverse );\n\n\t\tthis.skeleton = source.skeleton;\n\n\t\treturn this;\n\n\t}\n\n\t// raycast( raycaster, intersects ) {\n\n\t// \tif ( this.boundingSphere === null ) this.computeBoundingSphere();\n\n\t// \t_sphere.copy( this.boundingSphere );\n\t// \t_sphere.applyMatrix4( this.matrixWorld );\n\n\t// \tif ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;\n\n\t// \tthis._computeIntersections( raycaster, intersects );\n\n\t// }\n\n\tgetVertexPosition( index, target ) {\n\n\t\tsuper.getVertexPosition( index, target );\n\n\t\tthis.applyBoneTransform( index, target );\n\n\t\treturn target;\n\n\t}\n\n\tbind( skeleton, bindMatrix ) {\n\n\t\tthis.skeleton = skeleton;\n\n\t\tif ( bindMatrix === undefined ) {\n\n\t\t\tthis.updateMatrixWorld( true );\n\n\t\t\tthis.skeleton.calculateInverses();\n\n\t\t\tbindMatrix = this.matrixWorld;\n\n\t\t}\n\n\t\tthis.bindMatrix.copy( bindMatrix );\n\t\tthis.bindMatrixInverse.copy( bindMatrix ).invert();\n\n\t}\n\n\tpose() {\n\n\t\tthis.skeleton.pose();\n\n\t}\n\n\tnormalizeSkinWeights() {\n\n\t\tconst vector = new Vector4();\n\n\t\tconst skinWeight = this.geometry.attributes.skinWeight;\n\n\t\tfor ( let i = 0, l = skinWeight.count; i < l; i ++ ) {\n\n\t\t\tvector.fromBufferAttribute( skinWeight, i );\n\n\t\t\tconst scale = 1.0 / vector.manhattanLength();\n\n\t\t\tif ( scale !== Infinity ) {\n\n\t\t\t\tvector.multiplyScalar( scale );\n\n\t\t\t} else {\n\n\t\t\t\tvector.set( 1, 0, 0, 0 ); // do something reasonable\n\n\t\t\t}\n\n\t\t\tskinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );\n\n\t\t}\n\n\t}\n\n\tupdateMatrixWorld( force ) {\n\n\t\tsuper.updateMatrixWorld( force );\n\n\t\tif ( this.bindMode === 'attached' ) {\n\n\t\t\tthis.bindMatrixInverse.copy( this.matrixWorld ).invert();\n\n\t\t} else if ( this.bindMode === 'detached' ) {\n\n\t\t\tthis.bindMatrixInverse.copy( this.bindMatrix ).invert();\n\n\t\t} else {\n\n\t\t\tconsole.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );\n\n\t\t}\n\n\t}\n\n\tapplyBoneTransform( index, vector ) {\n\n\t\tconst skeleton = this.skeleton;\n\t\tconst geometry = this.geometry;\n\n\t\t_skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );\n\t\t_skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );\n\n\t\t_basePosition.copy( vector ).applyMatrix4( this.bindMatrix );\n\n\t\tvector.set( 0, 0, 0 );\n\n\t\tfor ( let i = 0; i < 4; i ++ ) {\n\n\t\t\tconst weight = _skinWeight.getComponent( i );\n\n\t\t\tif ( weight !== 0 ) {\n\n\t\t\t\tconst boneIndex = _skinIndex.getComponent( i );\n\n\t\t\t\t_matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );\n\n\t\t\t\tvector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn vector.applyMatrix4( this.bindMatrixInverse );\n\n\t}\n\n\tboneTransform( index, vector ) { // @deprecated, r151\n\n\t\tconsole.warn( 'THREE.SkinnedMesh: .boneTransform() was renamed to .applyBoneTransform() in r151.' );\n\t\treturn this.applyBoneTransform( index, vector );\n\n\t}\n\n\n}\n\nclass Bone extends Object3D {\n\n\tconstructor() {\n\n\t\tsuper();\n\n\t\tthis.isBone = true;\n\n\t\tthis.type = 'Bone';\n\n\t}\n\n}\n\nclass DataTexture extends Texture {\n\n\tconstructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {\n\n\t\tsuper( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );\n\n\t\tthis.isDataTexture = true;\n\n\t\tthis.image = { data: data, width: width, height: height };\n\n\t\tthis.generateMipmaps = false;\n\t\tthis.flipY = false;\n\t\tthis.unpackAlignment = 1;\n\n\t}\n\n}\n\nconst _offsetMatrix = /*@__PURE__*/ new Matrix4();\nconst _identityMatrix = /*@__PURE__*/ new Matrix4();\n\nclass Skeleton {\n\n\tconstructor( bones = [], boneInverses = [] ) {\n\n\t\tthis.uuid = generateUUID();\n\n\t\tthis.bones = bones.slice( 0 );\n\t\tthis.boneInverses = boneInverses;\n\t\tthis.boneMatrices = null;\n\n\t\tthis.boneTexture = null;\n\t\tthis.boneTextureSize = 0;\n\n\t\tthis.frame = - 1;\n\n\t\tthis.init();\n\n\t}\n\n\tinit() {\n\n\t\tconst bones = this.bones;\n\t\tconst boneInverses = this.boneInverses;\n\n\t\tthis.boneMatrices = new Float32Array( bones.length * 16 );\n\n\t\t// calculate inverse bone matrices if necessary\n\n\t\tif ( boneInverses.length === 0 ) {\n\n\t\t\tthis.calculateInverses();\n\n\t\t} else {\n\n\t\t\t// handle special case\n\n\t\t\tif ( bones.length !== boneInverses.length ) {\n\n\t\t\t\tconsole.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );\n\n\t\t\t\tthis.boneInverses = [];\n\n\t\t\t\tfor ( let i = 0, il = this.bones.length; i < il; i ++ ) {\n\n\t\t\t\t\tthis.boneInverses.push( new Matrix4() );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tcalculateInverses() {\n\n\t\tthis.boneInverses.length = 0;\n\n\t\tfor ( let i = 0, il = this.bones.length; i < il; i ++ ) {\n\n\t\t\tconst inverse = new Matrix4();\n\n\t\t\tif ( this.bones[ i ] ) {\n\n\t\t\t\tinverse.copy( this.bones[ i ].matrixWorld ).invert();\n\n\t\t\t}\n\n\t\t\tthis.boneInverses.push( inverse );\n\n\t\t}\n\n\t}\n\n\tpose() {\n\n\t\t// recover the bind-time world matrices\n\n\t\tfor ( let i = 0, il = this.bones.length; i < il; i ++ ) {\n\n\t\t\tconst bone = this.bones[ i ];\n\n\t\t\tif ( bone ) {\n\n\t\t\t\tbone.matrixWorld.copy( this.boneInverses[ i ] ).invert();\n\n\t\t\t}\n\n\t\t}\n\n\t\t// compute the local matrices, positions, rotations and scales\n\n\t\tfor ( let i = 0, il = this.bones.length; i < il; i ++ ) {\n\n\t\t\tconst bone = this.bones[ i ];\n\n\t\t\tif ( bone ) {\n\n\t\t\t\tif ( bone.parent && bone.parent.isBone ) {\n\n\t\t\t\t\tbone.matrix.copy( bone.parent.matrixWorld ).invert();\n\t\t\t\t\tbone.matrix.multiply( bone.matrixWorld );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tbone.matrix.copy( bone.matrixWorld );\n\n\t\t\t\t}\n\n\t\t\t\tbone.matrix.decompose( bone.position, bone.quaternion, bone.scale );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tupdate() {\n\n\t\tconst bones = this.bones;\n\t\tconst boneInverses = this.boneInverses;\n\t\tconst boneMatrices = this.boneMatrices;\n\t\tconst boneTexture = this.boneTexture;\n\n\t\t// flatten bone matrices to array\n\n\t\tfor ( let i = 0, il = bones.length; i < il; i ++ ) {\n\n\t\t\t// compute the offset between the current and the original transform\n\n\t\t\tconst matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;\n\n\t\t\t_offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );\n\t\t\t_offsetMatrix.toArray( boneMatrices, i * 16 );\n\n\t\t}\n\n\t\tif ( boneTexture !== null ) {\n\n\t\t\tboneTexture.needsUpdate = true;\n\n\t\t}\n\n\t}\n\n\tclone() {\n\n\t\treturn new Skeleton( this.bones, this.boneInverses );\n\n\t}\n\n\tcomputeBoneTexture() {\n\n\t\t// layout (1 matrix = 4 pixels)\n\t\t// RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)\n\t\t// with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)\n\t\t// 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)\n\t\t// 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)\n\t\t// 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)\n\n\t\tlet size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix\n\t\tsize = ceilPowerOfTwo( size );\n\t\tsize = Math.max( size, 4 );\n\n\t\tconst boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel\n\t\tboneMatrices.set( this.boneMatrices ); // copy current values\n\n\t\tconst boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );\n\t\tboneTexture.needsUpdate = true;\n\n\t\tthis.boneMatrices = boneMatrices;\n\t\tthis.boneTexture = boneTexture;\n\t\tthis.boneTextureSize = size;\n\n\t\treturn this;\n\n\t}\n\n\tgetBoneByName( name ) {\n\n\t\tfor ( let i = 0, il = this.bones.length; i < il; i ++ ) {\n\n\t\t\tconst bone = this.bones[ i ];\n\n\t\t\tif ( bone.name === name ) {\n\n\t\t\t\treturn bone;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn undefined;\n\n\t}\n\n\tdispose( ) {\n\n\t\tif ( this.boneTexture !== null ) {\n\n\t\t\tthis.boneTexture.dispose();\n\n\t\t\tthis.boneTexture = null;\n\n\t\t}\n\n\t}\n\n\tfromJSON( json, bones ) {\n\n\t\tthis.uuid = json.uuid;\n\n\t\tfor ( let i = 0, l = json.bones.length; i < l; i ++ ) {\n\n\t\t\tconst uuid = json.bones[ i ];\n\t\t\tlet bone = bones[ uuid ];\n\n\t\t\tif ( bone === undefined ) {\n\n\t\t\t\tconsole.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );\n\t\t\t\tbone = new Bone();\n\n\t\t\t}\n\n\t\t\tthis.bones.push( bone );\n\t\t\tthis.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );\n\n\t\t}\n\n\t\tthis.init();\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = {\n\t\t\tmetadata: {\n\t\t\t\tversion: 4.5,\n\t\t\t\ttype: 'Skeleton',\n\t\t\t\tgenerator: 'Skeleton.toJSON'\n\t\t\t},\n\t\t\tbones: [],\n\t\t\tboneInverses: []\n\t\t};\n\n\t\tdata.uuid = this.uuid;\n\n\t\tconst bones = this.bones;\n\t\tconst boneInverses = this.boneInverses;\n\n\t\tfor ( let i = 0, l = bones.length; i < l; i ++ ) {\n\n\t\t\tconst bone = bones[ i ];\n\t\t\tdata.bones.push( bone.uuid );\n\n\t\t\tconst boneInverse = boneInverses[ i ];\n\t\t\tdata.boneInverses.push( boneInverse.toArray() );\n\n\t\t}\n\n\t\treturn data;\n\n\t}\n\n}\n\nclass InstancedBufferAttribute extends BufferAttribute {\n\n\tconstructor( array, itemSize, normalized, meshPerAttribute = 1 ) {\n\n\t\tsuper( array, itemSize, normalized );\n\n\t\tthis.isInstancedBufferAttribute = true;\n\n\t\tthis.meshPerAttribute = meshPerAttribute;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.meshPerAttribute = source.meshPerAttribute;\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.meshPerAttribute = this.meshPerAttribute;\n\n\t\tdata.isInstancedBufferAttribute = true;\n\n\t\treturn data;\n\n\t}\n\n}\n\nconst _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();\nconst _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();\n\nconst _instanceIntersects = [];\n\nconst _box3 = /*@__PURE__*/ new Box3();\nconst _identity = /*@__PURE__*/ new Matrix4();\nconst _mesh = /*@__PURE__*/ new Mesh();\nconst _sphere$2 = /*@__PURE__*/ new Sphere();\n\nclass InstancedMesh extends Mesh {\n\n\tconstructor( geometry, material, count ) {\n\n\t\tsuper( geometry, material );\n\n\t\tthis.isInstancedMesh = true;\n\n\t\tthis.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );\n\t\tthis.instanceColor = null;\n\n\t\tthis.count = count;\n\n\t\tthis.boundingBox = null;\n\t\tthis.boundingSphere = null;\n\n\t\tfor ( let i = 0; i < count; i ++ ) {\n\n\t\t\tthis.setMatrixAt( i, _identity );\n\n\t\t}\n\n\t}\n\n\tcomputeBoundingBox() {\n\n\t\tconst geometry = this.geometry;\n\t\tconst count = this.count;\n\n\t\tif ( this.boundingBox === null ) {\n\n\t\t\tthis.boundingBox = new Box3();\n\n\t\t}\n\n\t\tif ( geometry.boundingBox === null ) {\n\n\t\t\tgeometry.computeBoundingBox();\n\n\t\t}\n\n\t\tthis.boundingBox.makeEmpty();\n\n\t\tfor ( let i = 0; i < count; i ++ ) {\n\n\t\t\tthis.getMatrixAt( i, _instanceLocalMatrix );\n\n\t\t\t_box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );\n\n\t\t\tthis.boundingBox.union( _box3 );\n\n\t\t}\n\n\t}\n\n\tcomputeBoundingSphere() {\n\n\t\tconst geometry = this.geometry;\n\t\tconst count = this.count;\n\n\t\tif ( this.boundingSphere === null ) {\n\n\t\t\tthis.boundingSphere = new Sphere();\n\n\t\t}\n\n\t\tif ( geometry.boundingSphere === null ) {\n\n\t\t\tgeometry.computeBoundingSphere();\n\n\t\t}\n\n\t\tthis.boundingSphere.makeEmpty();\n\n\t\tfor ( let i = 0; i < count; i ++ ) {\n\n\t\t\tthis.getMatrixAt( i, _instanceLocalMatrix );\n\n\t\t\t_sphere$2.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );\n\n\t\t\tthis.boundingSphere.union( _sphere$2 );\n\n\t\t}\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tthis.instanceMatrix.copy( source.instanceMatrix );\n\n\t\tif ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();\n\n\t\tthis.count = source.count;\n\n\t\treturn this;\n\n\t}\n\n\tgetColorAt( index, color ) {\n\n\t\tcolor.fromArray( this.instanceColor.array, index * 3 );\n\n\t}\n\n\tgetMatrixAt( index, matrix ) {\n\n\t\tmatrix.fromArray( this.instanceMatrix.array, index * 16 );\n\n\t}\n\n\traycast( raycaster, intersects ) {\n\n\t\tconst matrixWorld = this.matrixWorld;\n\t\tconst raycastTimes = this.count;\n\n\t\t_mesh.geometry = this.geometry;\n\t\t_mesh.material = this.material;\n\n\t\tif ( _mesh.material === undefined ) return;\n\n\t\t// test with bounding sphere first\n\n\t\tif ( this.boundingSphere === null ) this.computeBoundingSphere();\n\n\t\t_sphere$2.copy( this.boundingSphere );\n\t\t_sphere$2.applyMatrix4( matrixWorld );\n\n\t\tif ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;\n\n\t\t// now test each instance\n\n\t\tfor ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {\n\n\t\t\t// calculate the world matrix for each instance\n\n\t\t\tthis.getMatrixAt( instanceId, _instanceLocalMatrix );\n\n\t\t\t_instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );\n\n\t\t\t// the mesh represents this single instance\n\n\t\t\t_mesh.matrixWorld = _instanceWorldMatrix;\n\n\t\t\t_mesh.raycast( raycaster, _instanceIntersects );\n\n\t\t\t// process the result of raycast\n\n\t\t\tfor ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {\n\n\t\t\t\tconst intersect = _instanceIntersects[ i ];\n\t\t\t\tintersect.instanceId = instanceId;\n\t\t\t\tintersect.object = this;\n\t\t\t\tintersects.push( intersect );\n\n\t\t\t}\n\n\t\t\t_instanceIntersects.length = 0;\n\n\t\t}\n\n\t}\n\n\tsetColorAt( index, color ) {\n\n\t\tif ( this.instanceColor === null ) {\n\n\t\t\tthis.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );\n\n\t\t}\n\n\t\tcolor.toArray( this.instanceColor.array, index * 3 );\n\n\t}\n\n\tsetMatrixAt( index, matrix ) {\n\n\t\tmatrix.toArray( this.instanceMatrix.array, index * 16 );\n\n\t}\n\n\tupdateMorphTargets() {\n\n\t}\n\n\tdispose() {\n\n\t\tthis.dispatchEvent( { type: 'dispose' } );\n\n\t}\n\n}\n\nclass LineBasicMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isLineBasicMaterial = true;\n\n\t\tthis.type = 'LineBasicMaterial';\n\n\t\tthis.color = new Color( 0xffffff );\n\n\t\tthis.map = null;\n\n\t\tthis.linewidth = 1;\n\t\tthis.linecap = 'round';\n\t\tthis.linejoin = 'round';\n\n\t\tthis.fog = true;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.color.copy( source.color );\n\n\t\tthis.map = source.map;\n\n\t\tthis.linewidth = source.linewidth;\n\t\tthis.linecap = source.linecap;\n\t\tthis.linejoin = source.linejoin;\n\n\t\tthis.fog = source.fog;\n\n\t\treturn this;\n\n\t}\n\n}\n\nconst _start$1 = /*@__PURE__*/ new Vector3();\nconst _end$1 = /*@__PURE__*/ new Vector3();\nconst _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();\nconst _ray$1 = /*@__PURE__*/ new Ray();\nconst _sphere$1 = /*@__PURE__*/ new Sphere();\n\nclass Line extends Object3D {\n\n\tconstructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {\n\n\t\tsuper();\n\n\t\tthis.isLine = true;\n\n\t\tthis.type = 'Line';\n\n\t\tthis.geometry = geometry;\n\t\tthis.material = material;\n\n\t\tthis.updateMorphTargets();\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tthis.material = source.material;\n\t\tthis.geometry = source.geometry;\n\n\t\treturn this;\n\n\t}\n\n\tcomputeLineDistances() {\n\n\t\tconst geometry = this.geometry;\n\n\t\t// we assume non-indexed geometry\n\n\t\tif ( geometry.index === null ) {\n\n\t\t\tconst positionAttribute = geometry.attributes.position;\n\t\t\tconst lineDistances = [ 0 ];\n\n\t\t\tfor ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {\n\n\t\t\t\t_start$1.fromBufferAttribute( positionAttribute, i - 1 );\n\t\t\t\t_end$1.fromBufferAttribute( positionAttribute, i );\n\n\t\t\t\tlineDistances[ i ] = lineDistances[ i - 1 ];\n\t\t\t\tlineDistances[ i ] += _start$1.distanceTo( _end$1 );\n\n\t\t\t}\n\n\t\t\tgeometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );\n\n\t\t} else {\n\n\t\t\tconsole.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\traycast( raycaster, intersects ) {\n\n\t\tconst geometry = this.geometry;\n\t\tconst matrixWorld = this.matrixWorld;\n\t\tconst threshold = raycaster.params.Line.threshold;\n\t\tconst drawRange = geometry.drawRange;\n\n\t\t// Checking boundingSphere distance to ray\n\n\t\tif ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();\n\n\t\t_sphere$1.copy( geometry.boundingSphere );\n\t\t_sphere$1.applyMatrix4( matrixWorld );\n\t\t_sphere$1.radius += threshold;\n\n\t\tif ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;\n\n\t\t//\n\n\t\t_inverseMatrix$1.copy( matrixWorld ).invert();\n\t\t_ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );\n\n\t\tconst localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );\n\t\tconst localThresholdSq = localThreshold * localThreshold;\n\n\t\tconst vStart = new Vector3();\n\t\tconst vEnd = new Vector3();\n\t\tconst interSegment = new Vector3();\n\t\tconst interRay = new Vector3();\n\t\tconst step = this.isLineSegments ? 2 : 1;\n\n\t\tconst index = geometry.index;\n\t\tconst attributes = geometry.attributes;\n\t\tconst positionAttribute = attributes.position;\n\n\t\tif ( index !== null ) {\n\n\t\t\tconst start = Math.max( 0, drawRange.start );\n\t\t\tconst end = Math.min( index.count, ( drawRange.start + drawRange.count ) );\n\n\t\t\tfor ( let i = start, l = end - 1; i < l; i += step ) {\n\n\t\t\t\tconst a = index.getX( i );\n\t\t\t\tconst b = index.getX( i + 1 );\n\n\t\t\t\tvStart.fromBufferAttribute( positionAttribute, a );\n\t\t\t\tvEnd.fromBufferAttribute( positionAttribute, b );\n\n\t\t\t\tconst distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );\n\n\t\t\t\tif ( distSq > localThresholdSq ) continue;\n\n\t\t\t\tinterRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation\n\n\t\t\t\tconst distance = raycaster.ray.origin.distanceTo( interRay );\n\n\t\t\t\tif ( distance < raycaster.near || distance > raycaster.far ) continue;\n\n\t\t\t\tintersects.push( {\n\n\t\t\t\t\tdistance: distance,\n\t\t\t\t\t// What do we want? intersection point on the ray or on the segment??\n\t\t\t\t\t// point: raycaster.ray.at( distance ),\n\t\t\t\t\tpoint: interSegment.clone().applyMatrix4( this.matrixWorld ),\n\t\t\t\t\tindex: i,\n\t\t\t\t\tface: null,\n\t\t\t\t\tfaceIndex: null,\n\t\t\t\t\tobject: this\n\n\t\t\t\t} );\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tconst start = Math.max( 0, drawRange.start );\n\t\t\tconst end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );\n\n\t\t\tfor ( let i = start, l = end - 1; i < l; i += step ) {\n\n\t\t\t\tvStart.fromBufferAttribute( positionAttribute, i );\n\t\t\t\tvEnd.fromBufferAttribute( positionAttribute, i + 1 );\n\n\t\t\t\tconst distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );\n\n\t\t\t\tif ( distSq > localThresholdSq ) continue;\n\n\t\t\t\tinterRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation\n\n\t\t\t\tconst distance = raycaster.ray.origin.distanceTo( interRay );\n\n\t\t\t\tif ( distance < raycaster.near || distance > raycaster.far ) continue;\n\n\t\t\t\tintersects.push( {\n\n\t\t\t\t\tdistance: distance,\n\t\t\t\t\t// What do we want? intersection point on the ray or on the segment??\n\t\t\t\t\t// point: raycaster.ray.at( distance ),\n\t\t\t\t\tpoint: interSegment.clone().applyMatrix4( this.matrixWorld ),\n\t\t\t\t\tindex: i,\n\t\t\t\t\tface: null,\n\t\t\t\t\tfaceIndex: null,\n\t\t\t\t\tobject: this\n\n\t\t\t\t} );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tupdateMorphTargets() {\n\n\t\tconst geometry = this.geometry;\n\n\t\tconst morphAttributes = geometry.morphAttributes;\n\t\tconst keys = Object.keys( morphAttributes );\n\n\t\tif ( keys.length > 0 ) {\n\n\t\t\tconst morphAttribute = morphAttributes[ keys[ 0 ] ];\n\n\t\t\tif ( morphAttribute !== undefined ) {\n\n\t\t\t\tthis.morphTargetInfluences = [];\n\t\t\t\tthis.morphTargetDictionary = {};\n\n\t\t\t\tfor ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {\n\n\t\t\t\t\tconst name = morphAttribute[ m ].name || String( m );\n\n\t\t\t\t\tthis.morphTargetInfluences.push( 0 );\n\t\t\t\t\tthis.morphTargetDictionary[ name ] = m;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}\n\nconst _start = /*@__PURE__*/ new Vector3();\nconst _end = /*@__PURE__*/ new Vector3();\n\nclass LineSegments extends Line {\n\n\tconstructor( geometry, material ) {\n\n\t\tsuper( geometry, material );\n\n\t\tthis.isLineSegments = true;\n\n\t\tthis.type = 'LineSegments';\n\n\t}\n\n\tcomputeLineDistances() {\n\n\t\tconst geometry = this.geometry;\n\n\t\t// we assume non-indexed geometry\n\n\t\tif ( geometry.index === null ) {\n\n\t\t\tconst positionAttribute = geometry.attributes.position;\n\t\t\tconst lineDistances = [];\n\n\t\t\tfor ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {\n\n\t\t\t\t_start.fromBufferAttribute( positionAttribute, i );\n\t\t\t\t_end.fromBufferAttribute( positionAttribute, i + 1 );\n\n\t\t\t\tlineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];\n\t\t\t\tlineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );\n\n\t\t\t}\n\n\t\t\tgeometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );\n\n\t\t} else {\n\n\t\t\tconsole.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass LineLoop extends Line {\n\n\tconstructor( geometry, material ) {\n\n\t\tsuper( geometry, material );\n\n\t\tthis.isLineLoop = true;\n\n\t\tthis.type = 'LineLoop';\n\n\t}\n\n}\n\nclass PointsMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isPointsMaterial = true;\n\n\t\tthis.type = 'PointsMaterial';\n\n\t\tthis.color = new Color( 0xffffff );\n\n\t\tthis.map = null;\n\n\t\tthis.alphaMap = null;\n\n\t\tthis.size = 1;\n\t\tthis.sizeAttenuation = true;\n\n\t\tthis.fog = true;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.color.copy( source.color );\n\n\t\tthis.map = source.map;\n\n\t\tthis.alphaMap = source.alphaMap;\n\n\t\tthis.size = source.size;\n\t\tthis.sizeAttenuation = source.sizeAttenuation;\n\n\t\tthis.fog = source.fog;\n\n\t\treturn this;\n\n\t}\n\n}\n\nconst _inverseMatrix = /*@__PURE__*/ new Matrix4();\nconst _ray = /*@__PURE__*/ new Ray();\nconst _sphere = /*@__PURE__*/ new Sphere();\nconst _position$2 = /*@__PURE__*/ new Vector3();\n\nclass Points extends Object3D {\n\n\tconstructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {\n\n\t\tsuper();\n\n\t\tthis.isPoints = true;\n\n\t\tthis.type = 'Points';\n\n\t\tthis.geometry = geometry;\n\t\tthis.material = material;\n\n\t\tthis.updateMorphTargets();\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tthis.material = source.material;\n\t\tthis.geometry = source.geometry;\n\n\t\treturn this;\n\n\t}\n\n\traycast( raycaster, intersects ) {\n\n\t\tconst geometry = this.geometry;\n\t\tconst matrixWorld = this.matrixWorld;\n\t\tconst threshold = raycaster.params.Points.threshold;\n\t\tconst drawRange = geometry.drawRange;\n\n\t\t// Checking boundingSphere distance to ray\n\n\t\tif ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();\n\n\t\t_sphere.copy( geometry.boundingSphere );\n\t\t_sphere.applyMatrix4( matrixWorld );\n\t\t_sphere.radius += threshold;\n\n\t\tif ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;\n\n\t\t//\n\n\t\t_inverseMatrix.copy( matrixWorld ).invert();\n\t\t_ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );\n\n\t\tconst localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );\n\t\tconst localThresholdSq = localThreshold * localThreshold;\n\n\t\tconst index = geometry.index;\n\t\tconst attributes = geometry.attributes;\n\t\tconst positionAttribute = attributes.position;\n\n\t\tif ( index !== null ) {\n\n\t\t\tconst start = Math.max( 0, drawRange.start );\n\t\t\tconst end = Math.min( index.count, ( drawRange.start + drawRange.count ) );\n\n\t\t\tfor ( let i = start, il = end; i < il; i ++ ) {\n\n\t\t\t\tconst a = index.getX( i );\n\n\t\t\t\t_position$2.fromBufferAttribute( positionAttribute, a );\n\n\t\t\t\ttestPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tconst start = Math.max( 0, drawRange.start );\n\t\t\tconst end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );\n\n\t\t\tfor ( let i = start, l = end; i < l; i ++ ) {\n\n\t\t\t\t_position$2.fromBufferAttribute( positionAttribute, i );\n\n\t\t\t\ttestPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tupdateMorphTargets() {\n\n\t\tconst geometry = this.geometry;\n\n\t\tconst morphAttributes = geometry.morphAttributes;\n\t\tconst keys = Object.keys( morphAttributes );\n\n\t\tif ( keys.length > 0 ) {\n\n\t\t\tconst morphAttribute = morphAttributes[ keys[ 0 ] ];\n\n\t\t\tif ( morphAttribute !== undefined ) {\n\n\t\t\t\tthis.morphTargetInfluences = [];\n\t\t\t\tthis.morphTargetDictionary = {};\n\n\t\t\t\tfor ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {\n\n\t\t\t\t\tconst name = morphAttribute[ m ].name || String( m );\n\n\t\t\t\t\tthis.morphTargetInfluences.push( 0 );\n\t\t\t\t\tthis.morphTargetDictionary[ name ] = m;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}\n\nfunction testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {\n\n\tconst rayPointDistanceSq = _ray.distanceSqToPoint( point );\n\n\tif ( rayPointDistanceSq < localThresholdSq ) {\n\n\t\tconst intersectPoint = new Vector3();\n\n\t\t_ray.closestPointToPoint( point, intersectPoint );\n\t\tintersectPoint.applyMatrix4( matrixWorld );\n\n\t\tconst distance = raycaster.ray.origin.distanceTo( intersectPoint );\n\n\t\tif ( distance < raycaster.near || distance > raycaster.far ) return;\n\n\t\tintersects.push( {\n\n\t\t\tdistance: distance,\n\t\t\tdistanceToRay: Math.sqrt( rayPointDistanceSq ),\n\t\t\tpoint: intersectPoint,\n\t\t\tindex: index,\n\t\t\tface: null,\n\t\t\tobject: object\n\n\t\t} );\n\n\t}\n\n}\n\nclass VideoTexture extends Texture {\n\n\tconstructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {\n\n\t\tsuper( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );\n\n\t\tthis.isVideoTexture = true;\n\n\t\tthis.minFilter = minFilter !== undefined ? minFilter : LinearFilter;\n\t\tthis.magFilter = magFilter !== undefined ? magFilter : LinearFilter;\n\n\t\tthis.generateMipmaps = false;\n\n\t\tconst scope = this;\n\n\t\tfunction updateVideo() {\n\n\t\t\tscope.needsUpdate = true;\n\t\t\tvideo.requestVideoFrameCallback( updateVideo );\n\n\t\t}\n\n\t\tif ( 'requestVideoFrameCallback' in video ) {\n\n\t\t\tvideo.requestVideoFrameCallback( updateVideo );\n\n\t\t}\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor( this.image ).copy( this );\n\n\t}\n\n\tupdate() {\n\n\t\tconst video = this.image;\n\t\tconst hasVideoFrameCallback = 'requestVideoFrameCallback' in video;\n\n\t\tif ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {\n\n\t\t\tthis.needsUpdate = true;\n\n\t\t}\n\n\t}\n\n}\n\nclass FramebufferTexture extends Texture {\n\n\tconstructor( width, height, format ) {\n\n\t\tsuper( { width, height } );\n\n\t\tthis.isFramebufferTexture = true;\n\n\t\tthis.format = format;\n\n\t\tthis.magFilter = NearestFilter;\n\t\tthis.minFilter = NearestFilter;\n\n\t\tthis.generateMipmaps = false;\n\n\t\tthis.needsUpdate = true;\n\n\t}\n\n}\n\nclass CompressedTexture extends Texture {\n\n\tconstructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {\n\n\t\tsuper( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );\n\n\t\tthis.isCompressedTexture = true;\n\n\t\tthis.image = { width: width, height: height };\n\t\tthis.mipmaps = mipmaps;\n\n\t\t// no flipping for cube textures\n\t\t// (also flipping doesn't work for compressed textures )\n\n\t\tthis.flipY = false;\n\n\t\t// can't generate mipmaps for compressed textures\n\t\t// mips must be embedded in DDS files\n\n\t\tthis.generateMipmaps = false;\n\n\t}\n\n}\n\nclass CompressedArrayTexture extends CompressedTexture {\n\n\tconstructor( mipmaps, width, height, depth, format, type ) {\n\n\t\tsuper( mipmaps, width, height, format, type );\n\n\t\tthis.isCompressedArrayTexture = true;\n\t\tthis.image.depth = depth;\n\t\tthis.wrapR = ClampToEdgeWrapping;\n\n\t}\n\n}\n\nclass CanvasTexture extends Texture {\n\n\tconstructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {\n\n\t\tsuper( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );\n\n\t\tthis.isCanvasTexture = true;\n\n\t\tthis.needsUpdate = true;\n\n\t}\n\n}\n\n/**\n * Extensible curve object.\n *\n * Some common of curve methods:\n * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )\n * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )\n * .getPoints(), .getSpacedPoints()\n * .getLength()\n * .updateArcLengths()\n *\n * This following curves inherit from THREE.Curve:\n *\n * -- 2D curves --\n * THREE.ArcCurve\n * THREE.CubicBezierCurve\n * THREE.EllipseCurve\n * THREE.LineCurve\n * THREE.QuadraticBezierCurve\n * THREE.SplineCurve\n *\n * -- 3D curves --\n * THREE.CatmullRomCurve3\n * THREE.CubicBezierCurve3\n * THREE.LineCurve3\n * THREE.QuadraticBezierCurve3\n *\n * A series of curves can be represented as a THREE.CurvePath.\n *\n **/\n\nclass Curve {\n\n\tconstructor() {\n\n\t\tthis.type = 'Curve';\n\n\t\tthis.arcLengthDivisions = 200;\n\n\t}\n\n\t// Virtual base class method to overwrite and implement in subclasses\n\t//\t- t [0 .. 1]\n\n\tgetPoint( /* t, optionalTarget */ ) {\n\n\t\tconsole.warn( 'THREE.Curve: .getPoint() not implemented.' );\n\t\treturn null;\n\n\t}\n\n\t// Get point at relative position in curve according to arc length\n\t// - u [0 .. 1]\n\n\tgetPointAt( u, optionalTarget ) {\n\n\t\tconst t = this.getUtoTmapping( u );\n\t\treturn this.getPoint( t, optionalTarget );\n\n\t}\n\n\t// Get sequence of points using getPoint( t )\n\n\tgetPoints( divisions = 5 ) {\n\n\t\tconst points = [];\n\n\t\tfor ( let d = 0; d <= divisions; d ++ ) {\n\n\t\t\tpoints.push( this.getPoint( d / divisions ) );\n\n\t\t}\n\n\t\treturn points;\n\n\t}\n\n\t// Get sequence of points using getPointAt( u )\n\n\tgetSpacedPoints( divisions = 5 ) {\n\n\t\tconst points = [];\n\n\t\tfor ( let d = 0; d <= divisions; d ++ ) {\n\n\t\t\tpoints.push( this.getPointAt( d / divisions ) );\n\n\t\t}\n\n\t\treturn points;\n\n\t}\n\n\t// Get total curve arc length\n\n\tgetLength() {\n\n\t\tconst lengths = this.getLengths();\n\t\treturn lengths[ lengths.length - 1 ];\n\n\t}\n\n\t// Get list of cumulative segment lengths\n\n\tgetLengths( divisions = this.arcLengthDivisions ) {\n\n\t\tif ( this.cacheArcLengths &&\n\t\t\t( this.cacheArcLengths.length === divisions + 1 ) &&\n\t\t\t! this.needsUpdate ) {\n\n\t\t\treturn this.cacheArcLengths;\n\n\t\t}\n\n\t\tthis.needsUpdate = false;\n\n\t\tconst cache = [];\n\t\tlet current, last = this.getPoint( 0 );\n\t\tlet sum = 0;\n\n\t\tcache.push( 0 );\n\n\t\tfor ( let p = 1; p <= divisions; p ++ ) {\n\n\t\t\tcurrent = this.getPoint( p / divisions );\n\t\t\tsum += current.distanceTo( last );\n\t\t\tcache.push( sum );\n\t\t\tlast = current;\n\n\t\t}\n\n\t\tthis.cacheArcLengths = cache;\n\n\t\treturn cache; // { sums: cache, sum: sum }; Sum is in the last element.\n\n\t}\n\n\tupdateArcLengths() {\n\n\t\tthis.needsUpdate = true;\n\t\tthis.getLengths();\n\n\t}\n\n\t// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant\n\n\tgetUtoTmapping( u, distance ) {\n\n\t\tconst arcLengths = this.getLengths();\n\n\t\tlet i = 0;\n\t\tconst il = arcLengths.length;\n\n\t\tlet targetArcLength; // The targeted u distance value to get\n\n\t\tif ( distance ) {\n\n\t\t\ttargetArcLength = distance;\n\n\t\t} else {\n\n\t\t\ttargetArcLength = u * arcLengths[ il - 1 ];\n\n\t\t}\n\n\t\t// binary search for the index with largest value smaller than target u distance\n\n\t\tlet low = 0, high = il - 1, comparison;\n\n\t\twhile ( low <= high ) {\n\n\t\t\ti = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats\n\n\t\t\tcomparison = arcLengths[ i ] - targetArcLength;\n\n\t\t\tif ( comparison < 0 ) {\n\n\t\t\t\tlow = i + 1;\n\n\t\t\t} else if ( comparison > 0 ) {\n\n\t\t\t\thigh = i - 1;\n\n\t\t\t} else {\n\n\t\t\t\thigh = i;\n\t\t\t\tbreak;\n\n\t\t\t\t// DONE\n\n\t\t\t}\n\n\t\t}\n\n\t\ti = high;\n\n\t\tif ( arcLengths[ i ] === targetArcLength ) {\n\n\t\t\treturn i / ( il - 1 );\n\n\t\t}\n\n\t\t// we could get finer grain at lengths, or use simple interpolation between two points\n\n\t\tconst lengthBefore = arcLengths[ i ];\n\t\tconst lengthAfter = arcLengths[ i + 1 ];\n\n\t\tconst segmentLength = lengthAfter - lengthBefore;\n\n\t\t// determine where we are between the 'before' and 'after' points\n\n\t\tconst segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;\n\n\t\t// add that fractional amount to t\n\n\t\tconst t = ( i + segmentFraction ) / ( il - 1 );\n\n\t\treturn t;\n\n\t}\n\n\t// Returns a unit vector tangent at t\n\t// In case any sub curve does not implement its tangent derivation,\n\t// 2 points a small delta apart will be used to find its gradient\n\t// which seems to give a reasonable approximation\n\n\tgetTangent( t, optionalTarget ) {\n\n\t\tconst delta = 0.0001;\n\t\tlet t1 = t - delta;\n\t\tlet t2 = t + delta;\n\n\t\t// Capping in case of danger\n\n\t\tif ( t1 < 0 ) t1 = 0;\n\t\tif ( t2 > 1 ) t2 = 1;\n\n\t\tconst pt1 = this.getPoint( t1 );\n\t\tconst pt2 = this.getPoint( t2 );\n\n\t\tconst tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );\n\n\t\ttangent.copy( pt2 ).sub( pt1 ).normalize();\n\n\t\treturn tangent;\n\n\t}\n\n\tgetTangentAt( u, optionalTarget ) {\n\n\t\tconst t = this.getUtoTmapping( u );\n\t\treturn this.getTangent( t, optionalTarget );\n\n\t}\n\n\tcomputeFrenetFrames( segments, closed ) {\n\n\t\t// see http://www.cs.indiana.edu/pub/techreports/TR425.pdf\n\n\t\tconst normal = new Vector3();\n\n\t\tconst tangents = [];\n\t\tconst normals = [];\n\t\tconst binormals = [];\n\n\t\tconst vec = new Vector3();\n\t\tconst mat = new Matrix4();\n\n\t\t// compute the tangent vectors for each segment on the curve\n\n\t\tfor ( let i = 0; i <= segments; i ++ ) {\n\n\t\t\tconst u = i / segments;\n\n\t\t\ttangents[ i ] = this.getTangentAt( u, new Vector3() );\n\n\t\t}\n\n\t\t// select an initial normal vector perpendicular to the first tangent vector,\n\t\t// and in the direction of the minimum tangent xyz component\n\n\t\tnormals[ 0 ] = new Vector3();\n\t\tbinormals[ 0 ] = new Vector3();\n\t\tlet min = Number.MAX_VALUE;\n\t\tconst tx = Math.abs( tangents[ 0 ].x );\n\t\tconst ty = Math.abs( tangents[ 0 ].y );\n\t\tconst tz = Math.abs( tangents[ 0 ].z );\n\n\t\tif ( tx <= min ) {\n\n\t\t\tmin = tx;\n\t\t\tnormal.set( 1, 0, 0 );\n\n\t\t}\n\n\t\tif ( ty <= min ) {\n\n\t\t\tmin = ty;\n\t\t\tnormal.set( 0, 1, 0 );\n\n\t\t}\n\n\t\tif ( tz <= min ) {\n\n\t\t\tnormal.set( 0, 0, 1 );\n\n\t\t}\n\n\t\tvec.crossVectors( tangents[ 0 ], normal ).normalize();\n\n\t\tnormals[ 0 ].crossVectors( tangents[ 0 ], vec );\n\t\tbinormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );\n\n\n\t\t// compute the slowly-varying normal and binormal vectors for each segment on the curve\n\n\t\tfor ( let i = 1; i <= segments; i ++ ) {\n\n\t\t\tnormals[ i ] = normals[ i - 1 ].clone();\n\n\t\t\tbinormals[ i ] = binormals[ i - 1 ].clone();\n\n\t\t\tvec.crossVectors( tangents[ i - 1 ], tangents[ i ] );\n\n\t\t\tif ( vec.length() > Number.EPSILON ) {\n\n\t\t\t\tvec.normalize();\n\n\t\t\t\tconst theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors\n\n\t\t\t\tnormals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );\n\n\t\t\t}\n\n\t\t\tbinormals[ i ].crossVectors( tangents[ i ], normals[ i ] );\n\n\t\t}\n\n\t\t// if the curve is closed, postprocess the vectors so the first and last normal vectors are the same\n\n\t\tif ( closed === true ) {\n\n\t\t\tlet theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );\n\t\t\ttheta /= segments;\n\n\t\t\tif ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {\n\n\t\t\t\ttheta = - theta;\n\n\t\t\t}\n\n\t\t\tfor ( let i = 1; i <= segments; i ++ ) {\n\n\t\t\t\t// twist a little...\n\t\t\t\tnormals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );\n\t\t\t\tbinormals[ i ].crossVectors( tangents[ i ], normals[ i ] );\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn {\n\t\t\ttangents: tangents,\n\t\t\tnormals: normals,\n\t\t\tbinormals: binormals\n\t\t};\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tthis.arcLengthDivisions = source.arcLengthDivisions;\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = {\n\t\t\tmetadata: {\n\t\t\t\tversion: 4.5,\n\t\t\t\ttype: 'Curve',\n\t\t\t\tgenerator: 'Curve.toJSON'\n\t\t\t}\n\t\t};\n\n\t\tdata.arcLengthDivisions = this.arcLengthDivisions;\n\t\tdata.type = this.type;\n\n\t\treturn data;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tthis.arcLengthDivisions = json.arcLengthDivisions;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass EllipseCurve extends Curve {\n\n\tconstructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {\n\n\t\tsuper();\n\n\t\tthis.isEllipseCurve = true;\n\n\t\tthis.type = 'EllipseCurve';\n\n\t\tthis.aX = aX;\n\t\tthis.aY = aY;\n\n\t\tthis.xRadius = xRadius;\n\t\tthis.yRadius = yRadius;\n\n\t\tthis.aStartAngle = aStartAngle;\n\t\tthis.aEndAngle = aEndAngle;\n\n\t\tthis.aClockwise = aClockwise;\n\n\t\tthis.aRotation = aRotation;\n\n\t}\n\n\tgetPoint( t, optionalTarget ) {\n\n\t\tconst point = optionalTarget || new Vector2();\n\n\t\tconst twoPi = Math.PI * 2;\n\t\tlet deltaAngle = this.aEndAngle - this.aStartAngle;\n\t\tconst samePoints = Math.abs( deltaAngle ) < Number.EPSILON;\n\n\t\t// ensures that deltaAngle is 0 .. 2 PI\n\t\twhile ( deltaAngle < 0 ) deltaAngle += twoPi;\n\t\twhile ( deltaAngle > twoPi ) deltaAngle -= twoPi;\n\n\t\tif ( deltaAngle < Number.EPSILON ) {\n\n\t\t\tif ( samePoints ) {\n\n\t\t\t\tdeltaAngle = 0;\n\n\t\t\t} else {\n\n\t\t\t\tdeltaAngle = twoPi;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( this.aClockwise === true && ! samePoints ) {\n\n\t\t\tif ( deltaAngle === twoPi ) {\n\n\t\t\t\tdeltaAngle = - twoPi;\n\n\t\t\t} else {\n\n\t\t\t\tdeltaAngle = deltaAngle - twoPi;\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst angle = this.aStartAngle + t * deltaAngle;\n\t\tlet x = this.aX + this.xRadius * Math.cos( angle );\n\t\tlet y = this.aY + this.yRadius * Math.sin( angle );\n\n\t\tif ( this.aRotation !== 0 ) {\n\n\t\t\tconst cos = Math.cos( this.aRotation );\n\t\t\tconst sin = Math.sin( this.aRotation );\n\n\t\t\tconst tx = x - this.aX;\n\t\t\tconst ty = y - this.aY;\n\n\t\t\t// Rotate the point about the center of the ellipse.\n\t\t\tx = tx * cos - ty * sin + this.aX;\n\t\t\ty = tx * sin + ty * cos + this.aY;\n\n\t\t}\n\n\t\treturn point.set( x, y );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.aX = source.aX;\n\t\tthis.aY = source.aY;\n\n\t\tthis.xRadius = source.xRadius;\n\t\tthis.yRadius = source.yRadius;\n\n\t\tthis.aStartAngle = source.aStartAngle;\n\t\tthis.aEndAngle = source.aEndAngle;\n\n\t\tthis.aClockwise = source.aClockwise;\n\n\t\tthis.aRotation = source.aRotation;\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.aX = this.aX;\n\t\tdata.aY = this.aY;\n\n\t\tdata.xRadius = this.xRadius;\n\t\tdata.yRadius = this.yRadius;\n\n\t\tdata.aStartAngle = this.aStartAngle;\n\t\tdata.aEndAngle = this.aEndAngle;\n\n\t\tdata.aClockwise = this.aClockwise;\n\n\t\tdata.aRotation = this.aRotation;\n\n\t\treturn data;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tsuper.fromJSON( json );\n\n\t\tthis.aX = json.aX;\n\t\tthis.aY = json.aY;\n\n\t\tthis.xRadius = json.xRadius;\n\t\tthis.yRadius = json.yRadius;\n\n\t\tthis.aStartAngle = json.aStartAngle;\n\t\tthis.aEndAngle = json.aEndAngle;\n\n\t\tthis.aClockwise = json.aClockwise;\n\n\t\tthis.aRotation = json.aRotation;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass ArcCurve extends EllipseCurve {\n\n\tconstructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {\n\n\t\tsuper( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );\n\n\t\tthis.isArcCurve = true;\n\n\t\tthis.type = 'ArcCurve';\n\n\t}\n\n}\n\n/**\n * Centripetal CatmullRom Curve - which is useful for avoiding\n * cusps and self-intersections in non-uniform catmull rom curves.\n * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf\n *\n * curve.type accepts centripetal(default), chordal and catmullrom\n * curve.tension is used for catmullrom which defaults to 0.5\n */\n\n\n/*\nBased on an optimized c++ solution in\n - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/\n - http://ideone.com/NoEbVM\n\nThis CubicPoly class could be used for reusing some variables and calculations,\nbut for three.js curve use, it could be possible inlined and flatten into a single function call\nwhich can be placed in CurveUtils.\n*/\n\nfunction CubicPoly() {\n\n\tlet c0 = 0, c1 = 0, c2 = 0, c3 = 0;\n\n\t/*\n\t * Compute coefficients for a cubic polynomial\n\t * p(s) = c0 + c1*s + c2*s^2 + c3*s^3\n\t * such that\n\t * p(0) = x0, p(1) = x1\n\t * and\n\t * p'(0) = t0, p'(1) = t1.\n\t */\n\tfunction init( x0, x1, t0, t1 ) {\n\n\t\tc0 = x0;\n\t\tc1 = t0;\n\t\tc2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;\n\t\tc3 = 2 * x0 - 2 * x1 + t0 + t1;\n\n\t}\n\n\treturn {\n\n\t\tinitCatmullRom: function ( x0, x1, x2, x3, tension ) {\n\n\t\t\tinit( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );\n\n\t\t},\n\n\t\tinitNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {\n\n\t\t\t// compute tangents when parameterized in [t1,t2]\n\t\t\tlet t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;\n\t\t\tlet t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;\n\n\t\t\t// rescale tangents for parametrization in [0,1]\n\t\t\tt1 *= dt1;\n\t\t\tt2 *= dt1;\n\n\t\t\tinit( x1, x2, t1, t2 );\n\n\t\t},\n\n\t\tcalc: function ( t ) {\n\n\t\t\tconst t2 = t * t;\n\t\t\tconst t3 = t2 * t;\n\t\t\treturn c0 + c1 * t + c2 * t2 + c3 * t3;\n\n\t\t}\n\n\t};\n\n}\n\n//\n\nconst tmp = /*@__PURE__*/ new Vector3();\nconst px = /*@__PURE__*/ new CubicPoly();\nconst py = /*@__PURE__*/ new CubicPoly();\nconst pz = /*@__PURE__*/ new CubicPoly();\n\nclass CatmullRomCurve3 extends Curve {\n\n\tconstructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {\n\n\t\tsuper();\n\n\t\tthis.isCatmullRomCurve3 = true;\n\n\t\tthis.type = 'CatmullRomCurve3';\n\n\t\tthis.points = points;\n\t\tthis.closed = closed;\n\t\tthis.curveType = curveType;\n\t\tthis.tension = tension;\n\n\t}\n\n\tgetPoint( t, optionalTarget = new Vector3() ) {\n\n\t\tconst point = optionalTarget;\n\n\t\tconst points = this.points;\n\t\tconst l = points.length;\n\n\t\tconst p = ( l - ( this.closed ? 0 : 1 ) ) * t;\n\t\tlet intPoint = Math.floor( p );\n\t\tlet weight = p - intPoint;\n\n\t\tif ( this.closed ) {\n\n\t\t\tintPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;\n\n\t\t} else if ( weight === 0 && intPoint === l - 1 ) {\n\n\t\t\tintPoint = l - 2;\n\t\t\tweight = 1;\n\n\t\t}\n\n\t\tlet p0, p3; // 4 points (p1 & p2 defined below)\n\n\t\tif ( this.closed || intPoint > 0 ) {\n\n\t\t\tp0 = points[ ( intPoint - 1 ) % l ];\n\n\t\t} else {\n\n\t\t\t// extrapolate first point\n\t\t\ttmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );\n\t\t\tp0 = tmp;\n\n\t\t}\n\n\t\tconst p1 = points[ intPoint % l ];\n\t\tconst p2 = points[ ( intPoint + 1 ) % l ];\n\n\t\tif ( this.closed || intPoint + 2 < l ) {\n\n\t\t\tp3 = points[ ( intPoint + 2 ) % l ];\n\n\t\t} else {\n\n\t\t\t// extrapolate last point\n\t\t\ttmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );\n\t\t\tp3 = tmp;\n\n\t\t}\n\n\t\tif ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {\n\n\t\t\t// init Centripetal / Chordal Catmull-Rom\n\t\t\tconst pow = this.curveType === 'chordal' ? 0.5 : 0.25;\n\t\t\tlet dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );\n\t\t\tlet dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );\n\t\t\tlet dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );\n\n\t\t\t// safety check for repeated points\n\t\t\tif ( dt1 < 1e-4 ) dt1 = 1.0;\n\t\t\tif ( dt0 < 1e-4 ) dt0 = dt1;\n\t\t\tif ( dt2 < 1e-4 ) dt2 = dt1;\n\n\t\t\tpx.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );\n\t\t\tpy.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );\n\t\t\tpz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );\n\n\t\t} else if ( this.curveType === 'catmullrom' ) {\n\n\t\t\tpx.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );\n\t\t\tpy.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );\n\t\t\tpz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );\n\n\t\t}\n\n\t\tpoint.set(\n\t\t\tpx.calc( weight ),\n\t\t\tpy.calc( weight ),\n\t\t\tpz.calc( weight )\n\t\t);\n\n\t\treturn point;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.points = [];\n\n\t\tfor ( let i = 0, l = source.points.length; i < l; i ++ ) {\n\n\t\t\tconst point = source.points[ i ];\n\n\t\t\tthis.points.push( point.clone() );\n\n\t\t}\n\n\t\tthis.closed = source.closed;\n\t\tthis.curveType = source.curveType;\n\t\tthis.tension = source.tension;\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.points = [];\n\n\t\tfor ( let i = 0, l = this.points.length; i < l; i ++ ) {\n\n\t\t\tconst point = this.points[ i ];\n\t\t\tdata.points.push( point.toArray() );\n\n\t\t}\n\n\t\tdata.closed = this.closed;\n\t\tdata.curveType = this.curveType;\n\t\tdata.tension = this.tension;\n\n\t\treturn data;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tsuper.fromJSON( json );\n\n\t\tthis.points = [];\n\n\t\tfor ( let i = 0, l = json.points.length; i < l; i ++ ) {\n\n\t\t\tconst point = json.points[ i ];\n\t\t\tthis.points.push( new Vector3().fromArray( point ) );\n\n\t\t}\n\n\t\tthis.closed = json.closed;\n\t\tthis.curveType = json.curveType;\n\t\tthis.tension = json.tension;\n\n\t\treturn this;\n\n\t}\n\n}\n\n/**\n * Bezier Curves formulas obtained from\n * https://en.wikipedia.org/wiki/B%C3%A9zier_curve\n */\n\nfunction CatmullRom( t, p0, p1, p2, p3 ) {\n\n\tconst v0 = ( p2 - p0 ) * 0.5;\n\tconst v1 = ( p3 - p1 ) * 0.5;\n\tconst t2 = t * t;\n\tconst t3 = t * t2;\n\treturn ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;\n\n}\n\n//\n\nfunction QuadraticBezierP0( t, p ) {\n\n\tconst k = 1 - t;\n\treturn k * k * p;\n\n}\n\nfunction QuadraticBezierP1( t, p ) {\n\n\treturn 2 * ( 1 - t ) * t * p;\n\n}\n\nfunction QuadraticBezierP2( t, p ) {\n\n\treturn t * t * p;\n\n}\n\nfunction QuadraticBezier( t, p0, p1, p2 ) {\n\n\treturn QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +\n\t\tQuadraticBezierP2( t, p2 );\n\n}\n\n//\n\nfunction CubicBezierP0( t, p ) {\n\n\tconst k = 1 - t;\n\treturn k * k * k * p;\n\n}\n\nfunction CubicBezierP1( t, p ) {\n\n\tconst k = 1 - t;\n\treturn 3 * k * k * t * p;\n\n}\n\nfunction CubicBezierP2( t, p ) {\n\n\treturn 3 * ( 1 - t ) * t * t * p;\n\n}\n\nfunction CubicBezierP3( t, p ) {\n\n\treturn t * t * t * p;\n\n}\n\nfunction CubicBezier( t, p0, p1, p2, p3 ) {\n\n\treturn CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +\n\t\tCubicBezierP3( t, p3 );\n\n}\n\nclass CubicBezierCurve extends Curve {\n\n\tconstructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {\n\n\t\tsuper();\n\n\t\tthis.isCubicBezierCurve = true;\n\n\t\tthis.type = 'CubicBezierCurve';\n\n\t\tthis.v0 = v0;\n\t\tthis.v1 = v1;\n\t\tthis.v2 = v2;\n\t\tthis.v3 = v3;\n\n\t}\n\n\tgetPoint( t, optionalTarget = new Vector2() ) {\n\n\t\tconst point = optionalTarget;\n\n\t\tconst v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;\n\n\t\tpoint.set(\n\t\t\tCubicBezier( t, v0.x, v1.x, v2.x, v3.x ),\n\t\t\tCubicBezier( t, v0.y, v1.y, v2.y, v3.y )\n\t\t);\n\n\t\treturn point;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.v0.copy( source.v0 );\n\t\tthis.v1.copy( source.v1 );\n\t\tthis.v2.copy( source.v2 );\n\t\tthis.v3.copy( source.v3 );\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.v0 = this.v0.toArray();\n\t\tdata.v1 = this.v1.toArray();\n\t\tdata.v2 = this.v2.toArray();\n\t\tdata.v3 = this.v3.toArray();\n\n\t\treturn data;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tsuper.fromJSON( json );\n\n\t\tthis.v0.fromArray( json.v0 );\n\t\tthis.v1.fromArray( json.v1 );\n\t\tthis.v2.fromArray( json.v2 );\n\t\tthis.v3.fromArray( json.v3 );\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass CubicBezierCurve3 extends Curve {\n\n\tconstructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {\n\n\t\tsuper();\n\n\t\tthis.isCubicBezierCurve3 = true;\n\n\t\tthis.type = 'CubicBezierCurve3';\n\n\t\tthis.v0 = v0;\n\t\tthis.v1 = v1;\n\t\tthis.v2 = v2;\n\t\tthis.v3 = v3;\n\n\t}\n\n\tgetPoint( t, optionalTarget = new Vector3() ) {\n\n\t\tconst point = optionalTarget;\n\n\t\tconst v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;\n\n\t\tpoint.set(\n\t\t\tCubicBezier( t, v0.x, v1.x, v2.x, v3.x ),\n\t\t\tCubicBezier( t, v0.y, v1.y, v2.y, v3.y ),\n\t\t\tCubicBezier( t, v0.z, v1.z, v2.z, v3.z )\n\t\t);\n\n\t\treturn point;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.v0.copy( source.v0 );\n\t\tthis.v1.copy( source.v1 );\n\t\tthis.v2.copy( source.v2 );\n\t\tthis.v3.copy( source.v3 );\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.v0 = this.v0.toArray();\n\t\tdata.v1 = this.v1.toArray();\n\t\tdata.v2 = this.v2.toArray();\n\t\tdata.v3 = this.v3.toArray();\n\n\t\treturn data;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tsuper.fromJSON( json );\n\n\t\tthis.v0.fromArray( json.v0 );\n\t\tthis.v1.fromArray( json.v1 );\n\t\tthis.v2.fromArray( json.v2 );\n\t\tthis.v3.fromArray( json.v3 );\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass LineCurve extends Curve {\n\n\tconstructor( v1 = new Vector2(), v2 = new Vector2() ) {\n\n\t\tsuper();\n\n\t\tthis.isLineCurve = true;\n\n\t\tthis.type = 'LineCurve';\n\n\t\tthis.v1 = v1;\n\t\tthis.v2 = v2;\n\n\t}\n\n\tgetPoint( t, optionalTarget = new Vector2() ) {\n\n\t\tconst point = optionalTarget;\n\n\t\tif ( t === 1 ) {\n\n\t\t\tpoint.copy( this.v2 );\n\n\t\t} else {\n\n\t\t\tpoint.copy( this.v2 ).sub( this.v1 );\n\t\t\tpoint.multiplyScalar( t ).add( this.v1 );\n\n\t\t}\n\n\t\treturn point;\n\n\t}\n\n\t// Line curve is linear, so we can overwrite default getPointAt\n\tgetPointAt( u, optionalTarget ) {\n\n\t\treturn this.getPoint( u, optionalTarget );\n\n\t}\n\n\tgetTangent( t, optionalTarget = new Vector2() ) {\n\n\t\treturn optionalTarget.subVectors( this.v2, this.v1 ).normalize();\n\n\t}\n\n\tgetTangentAt( u, optionalTarget ) {\n\n\t\treturn this.getTangent( u, optionalTarget );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.v1.copy( source.v1 );\n\t\tthis.v2.copy( source.v2 );\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.v1 = this.v1.toArray();\n\t\tdata.v2 = this.v2.toArray();\n\n\t\treturn data;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tsuper.fromJSON( json );\n\n\t\tthis.v1.fromArray( json.v1 );\n\t\tthis.v2.fromArray( json.v2 );\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass LineCurve3 extends Curve {\n\n\tconstructor( v1 = new Vector3(), v2 = new Vector3() ) {\n\n\t\tsuper();\n\n\t\tthis.isLineCurve3 = true;\n\n\t\tthis.type = 'LineCurve3';\n\n\t\tthis.v1 = v1;\n\t\tthis.v2 = v2;\n\n\t}\n\tgetPoint( t, optionalTarget = new Vector3() ) {\n\n\t\tconst point = optionalTarget;\n\n\t\tif ( t === 1 ) {\n\n\t\t\tpoint.copy( this.v2 );\n\n\t\t} else {\n\n\t\t\tpoint.copy( this.v2 ).sub( this.v1 );\n\t\t\tpoint.multiplyScalar( t ).add( this.v1 );\n\n\t\t}\n\n\t\treturn point;\n\n\t}\n\t// Line curve is linear, so we can overwrite default getPointAt\n\tgetPointAt( u, optionalTarget ) {\n\n\t\treturn this.getPoint( u, optionalTarget );\n\n\t}\n\n\tgetTangent( t, optionalTarget = new Vector3() ) {\n\n\t\treturn optionalTarget.subVectors( this.v2, this.v1 ).normalize();\n\n\t}\n\n\tgetTangentAt( u, optionalTarget ) {\n\n\t\treturn this.getTangent( u, optionalTarget );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.v1.copy( source.v1 );\n\t\tthis.v2.copy( source.v2 );\n\n\t\treturn this;\n\n\t}\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.v1 = this.v1.toArray();\n\t\tdata.v2 = this.v2.toArray();\n\n\t\treturn data;\n\n\t}\n\tfromJSON( json ) {\n\n\t\tsuper.fromJSON( json );\n\n\t\tthis.v1.fromArray( json.v1 );\n\t\tthis.v2.fromArray( json.v2 );\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass QuadraticBezierCurve extends Curve {\n\n\tconstructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {\n\n\t\tsuper();\n\n\t\tthis.isQuadraticBezierCurve = true;\n\n\t\tthis.type = 'QuadraticBezierCurve';\n\n\t\tthis.v0 = v0;\n\t\tthis.v1 = v1;\n\t\tthis.v2 = v2;\n\n\t}\n\n\tgetPoint( t, optionalTarget = new Vector2() ) {\n\n\t\tconst point = optionalTarget;\n\n\t\tconst v0 = this.v0, v1 = this.v1, v2 = this.v2;\n\n\t\tpoint.set(\n\t\t\tQuadraticBezier( t, v0.x, v1.x, v2.x ),\n\t\t\tQuadraticBezier( t, v0.y, v1.y, v2.y )\n\t\t);\n\n\t\treturn point;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.v0.copy( source.v0 );\n\t\tthis.v1.copy( source.v1 );\n\t\tthis.v2.copy( source.v2 );\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.v0 = this.v0.toArray();\n\t\tdata.v1 = this.v1.toArray();\n\t\tdata.v2 = this.v2.toArray();\n\n\t\treturn data;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tsuper.fromJSON( json );\n\n\t\tthis.v0.fromArray( json.v0 );\n\t\tthis.v1.fromArray( json.v1 );\n\t\tthis.v2.fromArray( json.v2 );\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass QuadraticBezierCurve3 extends Curve {\n\n\tconstructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {\n\n\t\tsuper();\n\n\t\tthis.isQuadraticBezierCurve3 = true;\n\n\t\tthis.type = 'QuadraticBezierCurve3';\n\n\t\tthis.v0 = v0;\n\t\tthis.v1 = v1;\n\t\tthis.v2 = v2;\n\n\t}\n\n\tgetPoint( t, optionalTarget = new Vector3() ) {\n\n\t\tconst point = optionalTarget;\n\n\t\tconst v0 = this.v0, v1 = this.v1, v2 = this.v2;\n\n\t\tpoint.set(\n\t\t\tQuadraticBezier( t, v0.x, v1.x, v2.x ),\n\t\t\tQuadraticBezier( t, v0.y, v1.y, v2.y ),\n\t\t\tQuadraticBezier( t, v0.z, v1.z, v2.z )\n\t\t);\n\n\t\treturn point;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.v0.copy( source.v0 );\n\t\tthis.v1.copy( source.v1 );\n\t\tthis.v2.copy( source.v2 );\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.v0 = this.v0.toArray();\n\t\tdata.v1 = this.v1.toArray();\n\t\tdata.v2 = this.v2.toArray();\n\n\t\treturn data;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tsuper.fromJSON( json );\n\n\t\tthis.v0.fromArray( json.v0 );\n\t\tthis.v1.fromArray( json.v1 );\n\t\tthis.v2.fromArray( json.v2 );\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass SplineCurve extends Curve {\n\n\tconstructor( points = [] ) {\n\n\t\tsuper();\n\n\t\tthis.isSplineCurve = true;\n\n\t\tthis.type = 'SplineCurve';\n\n\t\tthis.points = points;\n\n\t}\n\n\tgetPoint( t, optionalTarget = new Vector2() ) {\n\n\t\tconst point = optionalTarget;\n\n\t\tconst points = this.points;\n\t\tconst p = ( points.length - 1 ) * t;\n\n\t\tconst intPoint = Math.floor( p );\n\t\tconst weight = p - intPoint;\n\n\t\tconst p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];\n\t\tconst p1 = points[ intPoint ];\n\t\tconst p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];\n\t\tconst p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];\n\n\t\tpoint.set(\n\t\t\tCatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),\n\t\t\tCatmullRom( weight, p0.y, p1.y, p2.y, p3.y )\n\t\t);\n\n\t\treturn point;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.points = [];\n\n\t\tfor ( let i = 0, l = source.points.length; i < l; i ++ ) {\n\n\t\t\tconst point = source.points[ i ];\n\n\t\t\tthis.points.push( point.clone() );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.points = [];\n\n\t\tfor ( let i = 0, l = this.points.length; i < l; i ++ ) {\n\n\t\t\tconst point = this.points[ i ];\n\t\t\tdata.points.push( point.toArray() );\n\n\t\t}\n\n\t\treturn data;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tsuper.fromJSON( json );\n\n\t\tthis.points = [];\n\n\t\tfor ( let i = 0, l = json.points.length; i < l; i ++ ) {\n\n\t\t\tconst point = json.points[ i ];\n\t\t\tthis.points.push( new Vector2().fromArray( point ) );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n}\n\nvar Curves = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tArcCurve: ArcCurve,\n\tCatmullRomCurve3: CatmullRomCurve3,\n\tCubicBezierCurve: CubicBezierCurve,\n\tCubicBezierCurve3: CubicBezierCurve3,\n\tEllipseCurve: EllipseCurve,\n\tLineCurve: LineCurve,\n\tLineCurve3: LineCurve3,\n\tQuadraticBezierCurve: QuadraticBezierCurve,\n\tQuadraticBezierCurve3: QuadraticBezierCurve3,\n\tSplineCurve: SplineCurve\n});\n\n/**************************************************************\n *\tCurved Path - a curve path is simply a array of connected\n * curves, but retains the api of a curve\n **************************************************************/\n\nclass CurvePath extends Curve {\n\n\tconstructor() {\n\n\t\tsuper();\n\n\t\tthis.type = 'CurvePath';\n\n\t\tthis.curves = [];\n\t\tthis.autoClose = false; // Automatically closes the path\n\n\t}\n\n\tadd( curve ) {\n\n\t\tthis.curves.push( curve );\n\n\t}\n\n\tclosePath() {\n\n\t\t// Add a line curve if start and end of lines are not connected\n\t\tconst startPoint = this.curves[ 0 ].getPoint( 0 );\n\t\tconst endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );\n\n\t\tif ( ! startPoint.equals( endPoint ) ) {\n\n\t\t\tthis.curves.push( new LineCurve( endPoint, startPoint ) );\n\n\t\t}\n\n\t}\n\n\t// To get accurate point with reference to\n\t// entire path distance at time t,\n\t// following has to be done:\n\n\t// 1. Length of each sub path have to be known\n\t// 2. Locate and identify type of curve\n\t// 3. Get t for the curve\n\t// 4. Return curve.getPointAt(t')\n\n\tgetPoint( t, optionalTarget ) {\n\n\t\tconst d = t * this.getLength();\n\t\tconst curveLengths = this.getCurveLengths();\n\t\tlet i = 0;\n\n\t\t// To think about boundaries points.\n\n\t\twhile ( i < curveLengths.length ) {\n\n\t\t\tif ( curveLengths[ i ] >= d ) {\n\n\t\t\t\tconst diff = curveLengths[ i ] - d;\n\t\t\t\tconst curve = this.curves[ i ];\n\n\t\t\t\tconst segmentLength = curve.getLength();\n\t\t\t\tconst u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;\n\n\t\t\t\treturn curve.getPointAt( u, optionalTarget );\n\n\t\t\t}\n\n\t\t\ti ++;\n\n\t\t}\n\n\t\treturn null;\n\n\t\t// loop where sum != 0, sum > d , sum+1 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {\n\n\t\t\tpoints.push( points[ 0 ] );\n\n\t\t}\n\n\t\treturn points;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.curves = [];\n\n\t\tfor ( let i = 0, l = source.curves.length; i < l; i ++ ) {\n\n\t\t\tconst curve = source.curves[ i ];\n\n\t\t\tthis.curves.push( curve.clone() );\n\n\t\t}\n\n\t\tthis.autoClose = source.autoClose;\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.autoClose = this.autoClose;\n\t\tdata.curves = [];\n\n\t\tfor ( let i = 0, l = this.curves.length; i < l; i ++ ) {\n\n\t\t\tconst curve = this.curves[ i ];\n\t\t\tdata.curves.push( curve.toJSON() );\n\n\t\t}\n\n\t\treturn data;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tsuper.fromJSON( json );\n\n\t\tthis.autoClose = json.autoClose;\n\t\tthis.curves = [];\n\n\t\tfor ( let i = 0, l = json.curves.length; i < l; i ++ ) {\n\n\t\t\tconst curve = json.curves[ i ];\n\t\t\tthis.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass Path extends CurvePath {\n\n\tconstructor( points ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'Path';\n\n\t\tthis.currentPoint = new Vector2();\n\n\t\tif ( points ) {\n\n\t\t\tthis.setFromPoints( points );\n\n\t\t}\n\n\t}\n\n\tsetFromPoints( points ) {\n\n\t\tthis.moveTo( points[ 0 ].x, points[ 0 ].y );\n\n\t\tfor ( let i = 1, l = points.length; i < l; i ++ ) {\n\n\t\t\tthis.lineTo( points[ i ].x, points[ i ].y );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tmoveTo( x, y ) {\n\n\t\tthis.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?\n\n\t\treturn this;\n\n\t}\n\n\tlineTo( x, y ) {\n\n\t\tconst curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );\n\t\tthis.curves.push( curve );\n\n\t\tthis.currentPoint.set( x, y );\n\n\t\treturn this;\n\n\t}\n\n\tquadraticCurveTo( aCPx, aCPy, aX, aY ) {\n\n\t\tconst curve = new QuadraticBezierCurve(\n\t\t\tthis.currentPoint.clone(),\n\t\t\tnew Vector2( aCPx, aCPy ),\n\t\t\tnew Vector2( aX, aY )\n\t\t);\n\n\t\tthis.curves.push( curve );\n\n\t\tthis.currentPoint.set( aX, aY );\n\n\t\treturn this;\n\n\t}\n\n\tbezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {\n\n\t\tconst curve = new CubicBezierCurve(\n\t\t\tthis.currentPoint.clone(),\n\t\t\tnew Vector2( aCP1x, aCP1y ),\n\t\t\tnew Vector2( aCP2x, aCP2y ),\n\t\t\tnew Vector2( aX, aY )\n\t\t);\n\n\t\tthis.curves.push( curve );\n\n\t\tthis.currentPoint.set( aX, aY );\n\n\t\treturn this;\n\n\t}\n\n\tsplineThru( pts /*Array of Vector*/ ) {\n\n\t\tconst npts = [ this.currentPoint.clone() ].concat( pts );\n\n\t\tconst curve = new SplineCurve( npts );\n\t\tthis.curves.push( curve );\n\n\t\tthis.currentPoint.copy( pts[ pts.length - 1 ] );\n\n\t\treturn this;\n\n\t}\n\n\tarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {\n\n\t\tconst x0 = this.currentPoint.x;\n\t\tconst y0 = this.currentPoint.y;\n\n\t\tthis.absarc( aX + x0, aY + y0, aRadius,\n\t\t\taStartAngle, aEndAngle, aClockwise );\n\n\t\treturn this;\n\n\t}\n\n\tabsarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {\n\n\t\tthis.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );\n\n\t\treturn this;\n\n\t}\n\n\tellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {\n\n\t\tconst x0 = this.currentPoint.x;\n\t\tconst y0 = this.currentPoint.y;\n\n\t\tthis.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );\n\n\t\treturn this;\n\n\t}\n\n\tabsellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {\n\n\t\tconst curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );\n\n\t\tif ( this.curves.length > 0 ) {\n\n\t\t\t// if a previous curve is present, attempt to join\n\t\t\tconst firstPoint = curve.getPoint( 0 );\n\n\t\t\tif ( ! firstPoint.equals( this.currentPoint ) ) {\n\n\t\t\t\tthis.lineTo( firstPoint.x, firstPoint.y );\n\n\t\t\t}\n\n\t\t}\n\n\t\tthis.curves.push( curve );\n\n\t\tconst lastPoint = curve.getPoint( 1 );\n\t\tthis.currentPoint.copy( lastPoint );\n\n\t\treturn this;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.currentPoint.copy( source.currentPoint );\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.currentPoint = this.currentPoint.toArray();\n\n\t\treturn data;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tsuper.fromJSON( json );\n\n\t\tthis.currentPoint.fromArray( json.currentPoint );\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass LatheGeometry extends BufferGeometry {\n\n\tconstructor( points = [ new Vector2( 0, - 0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'LatheGeometry';\n\n\t\tthis.parameters = {\n\t\t\tpoints: points,\n\t\t\tsegments: segments,\n\t\t\tphiStart: phiStart,\n\t\t\tphiLength: phiLength\n\t\t};\n\n\t\tsegments = Math.floor( segments );\n\n\t\t// clamp phiLength so it's in range of [ 0, 2PI ]\n\n\t\tphiLength = clamp( phiLength, 0, Math.PI * 2 );\n\n\t\t// buffers\n\n\t\tconst indices = [];\n\t\tconst vertices = [];\n\t\tconst uvs = [];\n\t\tconst initNormals = [];\n\t\tconst normals = [];\n\n\t\t// helper variables\n\n\t\tconst inverseSegments = 1.0 / segments;\n\t\tconst vertex = new Vector3();\n\t\tconst uv = new Vector2();\n\t\tconst normal = new Vector3();\n\t\tconst curNormal = new Vector3();\n\t\tconst prevNormal = new Vector3();\n\t\tlet dx = 0;\n\t\tlet dy = 0;\n\n\t\t// pre-compute normals for initial \"meridian\"\n\n\t\tfor ( let j = 0; j <= ( points.length - 1 ); j ++ ) {\n\n\t\t\tswitch ( j ) {\n\n\t\t\t\tcase 0:\t\t\t\t// special handling for 1st vertex on path\n\n\t\t\t\t\tdx = points[ j + 1 ].x - points[ j ].x;\n\t\t\t\t\tdy = points[ j + 1 ].y - points[ j ].y;\n\n\t\t\t\t\tnormal.x = dy * 1.0;\n\t\t\t\t\tnormal.y = - dx;\n\t\t\t\t\tnormal.z = dy * 0.0;\n\n\t\t\t\t\tprevNormal.copy( normal );\n\n\t\t\t\t\tnormal.normalize();\n\n\t\t\t\t\tinitNormals.push( normal.x, normal.y, normal.z );\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase ( points.length - 1 ):\t// special handling for last Vertex on path\n\n\t\t\t\t\tinitNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\t\t\t// default handling for all vertices in between\n\n\t\t\t\t\tdx = points[ j + 1 ].x - points[ j ].x;\n\t\t\t\t\tdy = points[ j + 1 ].y - points[ j ].y;\n\n\t\t\t\t\tnormal.x = dy * 1.0;\n\t\t\t\t\tnormal.y = - dx;\n\t\t\t\t\tnormal.z = dy * 0.0;\n\n\t\t\t\t\tcurNormal.copy( normal );\n\n\t\t\t\t\tnormal.x += prevNormal.x;\n\t\t\t\t\tnormal.y += prevNormal.y;\n\t\t\t\t\tnormal.z += prevNormal.z;\n\n\t\t\t\t\tnormal.normalize();\n\n\t\t\t\t\tinitNormals.push( normal.x, normal.y, normal.z );\n\n\t\t\t\t\tprevNormal.copy( curNormal );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// generate vertices, uvs and normals\n\n\t\tfor ( let i = 0; i <= segments; i ++ ) {\n\n\t\t\tconst phi = phiStart + i * inverseSegments * phiLength;\n\n\t\t\tconst sin = Math.sin( phi );\n\t\t\tconst cos = Math.cos( phi );\n\n\t\t\tfor ( let j = 0; j <= ( points.length - 1 ); j ++ ) {\n\n\t\t\t\t// vertex\n\n\t\t\t\tvertex.x = points[ j ].x * sin;\n\t\t\t\tvertex.y = points[ j ].y;\n\t\t\t\tvertex.z = points[ j ].x * cos;\n\n\t\t\t\tvertices.push( vertex.x, vertex.y, vertex.z );\n\n\t\t\t\t// uv\n\n\t\t\t\tuv.x = i / segments;\n\t\t\t\tuv.y = j / ( points.length - 1 );\n\n\t\t\t\tuvs.push( uv.x, uv.y );\n\n\t\t\t\t// normal\n\n\t\t\t\tconst x = initNormals[ 3 * j + 0 ] * sin;\n\t\t\t\tconst y = initNormals[ 3 * j + 1 ];\n\t\t\t\tconst z = initNormals[ 3 * j + 0 ] * cos;\n\n\t\t\t\tnormals.push( x, y, z );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// indices\n\n\t\tfor ( let i = 0; i < segments; i ++ ) {\n\n\t\t\tfor ( let j = 0; j < ( points.length - 1 ); j ++ ) {\n\n\t\t\t\tconst base = j + i * points.length;\n\n\t\t\t\tconst a = base;\n\t\t\t\tconst b = base + points.length;\n\t\t\t\tconst c = base + points.length + 1;\n\t\t\t\tconst d = base + 1;\n\n\t\t\t\t// faces\n\n\t\t\t\tindices.push( a, b, d );\n\t\t\t\tindices.push( c, d, b );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// build geometry\n\n\t\tthis.setIndex( indices );\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );\n\t\tthis.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );\n\n\t}\n\n}\n\nclass CapsuleGeometry extends LatheGeometry {\n\n\tconstructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {\n\n\t\tconst path = new Path();\n\t\tpath.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );\n\t\tpath.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );\n\n\t\tsuper( path.getPoints( capSegments ), radialSegments );\n\n\t\tthis.type = 'CapsuleGeometry';\n\n\t\tthis.parameters = {\n\t\t\tradius: radius,\n\t\t\theight: length,\n\t\t\tcapSegments: capSegments,\n\t\t\tradialSegments: radialSegments,\n\t\t};\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );\n\n\t}\n\n}\n\nclass CircleGeometry extends BufferGeometry {\n\n\tconstructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'CircleGeometry';\n\n\t\tthis.parameters = {\n\t\t\tradius: radius,\n\t\t\tsegments: segments,\n\t\t\tthetaStart: thetaStart,\n\t\t\tthetaLength: thetaLength\n\t\t};\n\n\t\tsegments = Math.max( 3, segments );\n\n\t\t// buffers\n\n\t\tconst indices = [];\n\t\tconst vertices = [];\n\t\tconst normals = [];\n\t\tconst uvs = [];\n\n\t\t// helper variables\n\n\t\tconst vertex = new Vector3();\n\t\tconst uv = new Vector2();\n\n\t\t// center point\n\n\t\tvertices.push( 0, 0, 0 );\n\t\tnormals.push( 0, 0, 1 );\n\t\tuvs.push( 0.5, 0.5 );\n\n\t\tfor ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {\n\n\t\t\tconst segment = thetaStart + s / segments * thetaLength;\n\n\t\t\t// vertex\n\n\t\t\tvertex.x = radius * Math.cos( segment );\n\t\t\tvertex.y = radius * Math.sin( segment );\n\n\t\t\tvertices.push( vertex.x, vertex.y, vertex.z );\n\n\t\t\t// normal\n\n\t\t\tnormals.push( 0, 0, 1 );\n\n\t\t\t// uvs\n\n\t\t\tuv.x = ( vertices[ i ] / radius + 1 ) / 2;\n\t\t\tuv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;\n\n\t\t\tuvs.push( uv.x, uv.y );\n\n\t\t}\n\n\t\t// indices\n\n\t\tfor ( let i = 1; i <= segments; i ++ ) {\n\n\t\t\tindices.push( i, i + 1, 0 );\n\n\t\t}\n\n\t\t// build geometry\n\n\t\tthis.setIndex( indices );\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tthis.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );\n\n\t}\n\n}\n\nclass CylinderGeometry extends BufferGeometry {\n\n\tconstructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'CylinderGeometry';\n\n\t\tthis.parameters = {\n\t\t\tradiusTop: radiusTop,\n\t\t\tradiusBottom: radiusBottom,\n\t\t\theight: height,\n\t\t\tradialSegments: radialSegments,\n\t\t\theightSegments: heightSegments,\n\t\t\topenEnded: openEnded,\n\t\t\tthetaStart: thetaStart,\n\t\t\tthetaLength: thetaLength\n\t\t};\n\n\t\tconst scope = this;\n\n\t\tradialSegments = Math.floor( radialSegments );\n\t\theightSegments = Math.floor( heightSegments );\n\n\t\t// buffers\n\n\t\tconst indices = [];\n\t\tconst vertices = [];\n\t\tconst normals = [];\n\t\tconst uvs = [];\n\n\t\t// helper variables\n\n\t\tlet index = 0;\n\t\tconst indexArray = [];\n\t\tconst halfHeight = height / 2;\n\t\tlet groupStart = 0;\n\n\t\t// generate geometry\n\n\t\tgenerateTorso();\n\n\t\tif ( openEnded === false ) {\n\n\t\t\tif ( radiusTop > 0 ) generateCap( true );\n\t\t\tif ( radiusBottom > 0 ) generateCap( false );\n\n\t\t}\n\n\t\t// build geometry\n\n\t\tthis.setIndex( indices );\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tthis.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );\n\n\t\tfunction generateTorso() {\n\n\t\t\tconst normal = new Vector3();\n\t\t\tconst vertex = new Vector3();\n\n\t\t\tlet groupCount = 0;\n\n\t\t\t// this will be used to calculate the normal\n\t\t\tconst slope = ( radiusBottom - radiusTop ) / height;\n\n\t\t\t// generate vertices, normals and uvs\n\n\t\t\tfor ( let y = 0; y <= heightSegments; y ++ ) {\n\n\t\t\t\tconst indexRow = [];\n\n\t\t\t\tconst v = y / heightSegments;\n\n\t\t\t\t// calculate the radius of the current row\n\n\t\t\t\tconst radius = v * ( radiusBottom - radiusTop ) + radiusTop;\n\n\t\t\t\tfor ( let x = 0; x <= radialSegments; x ++ ) {\n\n\t\t\t\t\tconst u = x / radialSegments;\n\n\t\t\t\t\tconst theta = u * thetaLength + thetaStart;\n\n\t\t\t\t\tconst sinTheta = Math.sin( theta );\n\t\t\t\t\tconst cosTheta = Math.cos( theta );\n\n\t\t\t\t\t// vertex\n\n\t\t\t\t\tvertex.x = radius * sinTheta;\n\t\t\t\t\tvertex.y = - v * height + halfHeight;\n\t\t\t\t\tvertex.z = radius * cosTheta;\n\t\t\t\t\tvertices.push( vertex.x, vertex.y, vertex.z );\n\n\t\t\t\t\t// normal\n\n\t\t\t\t\tnormal.set( sinTheta, slope, cosTheta ).normalize();\n\t\t\t\t\tnormals.push( normal.x, normal.y, normal.z );\n\n\t\t\t\t\t// uv\n\n\t\t\t\t\tuvs.push( u, 1 - v );\n\n\t\t\t\t\t// save index of vertex in respective row\n\n\t\t\t\t\tindexRow.push( index ++ );\n\n\t\t\t\t}\n\n\t\t\t\t// now save vertices of the row in our index array\n\n\t\t\t\tindexArray.push( indexRow );\n\n\t\t\t}\n\n\t\t\t// generate indices\n\n\t\t\tfor ( let x = 0; x < radialSegments; x ++ ) {\n\n\t\t\t\tfor ( let y = 0; y < heightSegments; y ++ ) {\n\n\t\t\t\t\t// we use the index array to access the correct indices\n\n\t\t\t\t\tconst a = indexArray[ y ][ x ];\n\t\t\t\t\tconst b = indexArray[ y + 1 ][ x ];\n\t\t\t\t\tconst c = indexArray[ y + 1 ][ x + 1 ];\n\t\t\t\t\tconst d = indexArray[ y ][ x + 1 ];\n\n\t\t\t\t\t// faces\n\n\t\t\t\t\tindices.push( a, b, d );\n\t\t\t\t\tindices.push( b, c, d );\n\n\t\t\t\t\t// update group counter\n\n\t\t\t\t\tgroupCount += 6;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// add a group to the geometry. this will ensure multi material support\n\n\t\t\tscope.addGroup( groupStart, groupCount, 0 );\n\n\t\t\t// calculate new start value for groups\n\n\t\t\tgroupStart += groupCount;\n\n\t\t}\n\n\t\tfunction generateCap( top ) {\n\n\t\t\t// save the index of the first center vertex\n\t\t\tconst centerIndexStart = index;\n\n\t\t\tconst uv = new Vector2();\n\t\t\tconst vertex = new Vector3();\n\n\t\t\tlet groupCount = 0;\n\n\t\t\tconst radius = ( top === true ) ? radiusTop : radiusBottom;\n\t\t\tconst sign = ( top === true ) ? 1 : - 1;\n\n\t\t\t// first we generate the center vertex data of the cap.\n\t\t\t// because the geometry needs one set of uvs per face,\n\t\t\t// we must generate a center vertex per face/segment\n\n\t\t\tfor ( let x = 1; x <= radialSegments; x ++ ) {\n\n\t\t\t\t// vertex\n\n\t\t\t\tvertices.push( 0, halfHeight * sign, 0 );\n\n\t\t\t\t// normal\n\n\t\t\t\tnormals.push( 0, sign, 0 );\n\n\t\t\t\t// uv\n\n\t\t\t\tuvs.push( 0.5, 0.5 );\n\n\t\t\t\t// increase index\n\n\t\t\t\tindex ++;\n\n\t\t\t}\n\n\t\t\t// save the index of the last center vertex\n\t\t\tconst centerIndexEnd = index;\n\n\t\t\t// now we generate the surrounding vertices, normals and uvs\n\n\t\t\tfor ( let x = 0; x <= radialSegments; x ++ ) {\n\n\t\t\t\tconst u = x / radialSegments;\n\t\t\t\tconst theta = u * thetaLength + thetaStart;\n\n\t\t\t\tconst cosTheta = Math.cos( theta );\n\t\t\t\tconst sinTheta = Math.sin( theta );\n\n\t\t\t\t// vertex\n\n\t\t\t\tvertex.x = radius * sinTheta;\n\t\t\t\tvertex.y = halfHeight * sign;\n\t\t\t\tvertex.z = radius * cosTheta;\n\t\t\t\tvertices.push( vertex.x, vertex.y, vertex.z );\n\n\t\t\t\t// normal\n\n\t\t\t\tnormals.push( 0, sign, 0 );\n\n\t\t\t\t// uv\n\n\t\t\t\tuv.x = ( cosTheta * 0.5 ) + 0.5;\n\t\t\t\tuv.y = ( sinTheta * 0.5 * sign ) + 0.5;\n\t\t\t\tuvs.push( uv.x, uv.y );\n\n\t\t\t\t// increase index\n\n\t\t\t\tindex ++;\n\n\t\t\t}\n\n\t\t\t// generate indices\n\n\t\t\tfor ( let x = 0; x < radialSegments; x ++ ) {\n\n\t\t\t\tconst c = centerIndexStart + x;\n\t\t\t\tconst i = centerIndexEnd + x;\n\n\t\t\t\tif ( top === true ) {\n\n\t\t\t\t\t// face top\n\n\t\t\t\t\tindices.push( i, i + 1, c );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// face bottom\n\n\t\t\t\t\tindices.push( i + 1, i, c );\n\n\t\t\t\t}\n\n\t\t\t\tgroupCount += 3;\n\n\t\t\t}\n\n\t\t\t// add a group to the geometry. this will ensure multi material support\n\n\t\t\tscope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );\n\n\t\t\t// calculate new start value for groups\n\n\t\t\tgroupStart += groupCount;\n\n\t\t}\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );\n\n\t}\n\n}\n\nclass ConeGeometry extends CylinderGeometry {\n\n\tconstructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {\n\n\t\tsuper( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );\n\n\t\tthis.type = 'ConeGeometry';\n\n\t\tthis.parameters = {\n\t\t\tradius: radius,\n\t\t\theight: height,\n\t\t\tradialSegments: radialSegments,\n\t\t\theightSegments: heightSegments,\n\t\t\topenEnded: openEnded,\n\t\t\tthetaStart: thetaStart,\n\t\t\tthetaLength: thetaLength\n\t\t};\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );\n\n\t}\n\n}\n\nclass PolyhedronGeometry extends BufferGeometry {\n\n\tconstructor( vertices = [], indices = [], radius = 1, detail = 0 ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'PolyhedronGeometry';\n\n\t\tthis.parameters = {\n\t\t\tvertices: vertices,\n\t\t\tindices: indices,\n\t\t\tradius: radius,\n\t\t\tdetail: detail\n\t\t};\n\n\t\t// default buffer data\n\n\t\tconst vertexBuffer = [];\n\t\tconst uvBuffer = [];\n\n\t\t// the subdivision creates the vertex buffer data\n\n\t\tsubdivide( detail );\n\n\t\t// all vertices should lie on a conceptual sphere with a given radius\n\n\t\tapplyRadius( radius );\n\n\t\t// finally, create the uv data\n\n\t\tgenerateUVs();\n\n\t\t// build non-indexed geometry\n\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );\n\t\tthis.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );\n\n\t\tif ( detail === 0 ) {\n\n\t\t\tthis.computeVertexNormals(); // flat normals\n\n\t\t} else {\n\n\t\t\tthis.normalizeNormals(); // smooth normals\n\n\t\t}\n\n\t\t// helper functions\n\n\t\tfunction subdivide( detail ) {\n\n\t\t\tconst a = new Vector3();\n\t\t\tconst b = new Vector3();\n\t\t\tconst c = new Vector3();\n\n\t\t\t// iterate over all faces and apply a subdivision with the given detail value\n\n\t\t\tfor ( let i = 0; i < indices.length; i += 3 ) {\n\n\t\t\t\t// get the vertices of the face\n\n\t\t\t\tgetVertexByIndex( indices[ i + 0 ], a );\n\t\t\t\tgetVertexByIndex( indices[ i + 1 ], b );\n\t\t\t\tgetVertexByIndex( indices[ i + 2 ], c );\n\n\t\t\t\t// perform subdivision\n\n\t\t\t\tsubdivideFace( a, b, c, detail );\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction subdivideFace( a, b, c, detail ) {\n\n\t\t\tconst cols = detail + 1;\n\n\t\t\t// we use this multidimensional array as a data structure for creating the subdivision\n\n\t\t\tconst v = [];\n\n\t\t\t// construct all of the vertices for this subdivision\n\n\t\t\tfor ( let i = 0; i <= cols; i ++ ) {\n\n\t\t\t\tv[ i ] = [];\n\n\t\t\t\tconst aj = a.clone().lerp( c, i / cols );\n\t\t\t\tconst bj = b.clone().lerp( c, i / cols );\n\n\t\t\t\tconst rows = cols - i;\n\n\t\t\t\tfor ( let j = 0; j <= rows; j ++ ) {\n\n\t\t\t\t\tif ( j === 0 && i === cols ) {\n\n\t\t\t\t\t\tv[ i ][ j ] = aj;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tv[ i ][ j ] = aj.clone().lerp( bj, j / rows );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// construct all of the faces\n\n\t\t\tfor ( let i = 0; i < cols; i ++ ) {\n\n\t\t\t\tfor ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {\n\n\t\t\t\t\tconst k = Math.floor( j / 2 );\n\n\t\t\t\t\tif ( j % 2 === 0 ) {\n\n\t\t\t\t\t\tpushVertex( v[ i ][ k + 1 ] );\n\t\t\t\t\t\tpushVertex( v[ i + 1 ][ k ] );\n\t\t\t\t\t\tpushVertex( v[ i ][ k ] );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tpushVertex( v[ i ][ k + 1 ] );\n\t\t\t\t\t\tpushVertex( v[ i + 1 ][ k + 1 ] );\n\t\t\t\t\t\tpushVertex( v[ i + 1 ][ k ] );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction applyRadius( radius ) {\n\n\t\t\tconst vertex = new Vector3();\n\n\t\t\t// iterate over the entire buffer and apply the radius to each vertex\n\n\t\t\tfor ( let i = 0; i < vertexBuffer.length; i += 3 ) {\n\n\t\t\t\tvertex.x = vertexBuffer[ i + 0 ];\n\t\t\t\tvertex.y = vertexBuffer[ i + 1 ];\n\t\t\t\tvertex.z = vertexBuffer[ i + 2 ];\n\n\t\t\t\tvertex.normalize().multiplyScalar( radius );\n\n\t\t\t\tvertexBuffer[ i + 0 ] = vertex.x;\n\t\t\t\tvertexBuffer[ i + 1 ] = vertex.y;\n\t\t\t\tvertexBuffer[ i + 2 ] = vertex.z;\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction generateUVs() {\n\n\t\t\tconst vertex = new Vector3();\n\n\t\t\tfor ( let i = 0; i < vertexBuffer.length; i += 3 ) {\n\n\t\t\t\tvertex.x = vertexBuffer[ i + 0 ];\n\t\t\t\tvertex.y = vertexBuffer[ i + 1 ];\n\t\t\t\tvertex.z = vertexBuffer[ i + 2 ];\n\n\t\t\t\tconst u = azimuth( vertex ) / 2 / Math.PI + 0.5;\n\t\t\t\tconst v = inclination( vertex ) / Math.PI + 0.5;\n\t\t\t\tuvBuffer.push( u, 1 - v );\n\n\t\t\t}\n\n\t\t\tcorrectUVs();\n\n\t\t\tcorrectSeam();\n\n\t\t}\n\n\t\tfunction correctSeam() {\n\n\t\t\t// handle case when face straddles the seam, see #3269\n\n\t\t\tfor ( let i = 0; i < uvBuffer.length; i += 6 ) {\n\n\t\t\t\t// uv data of a single face\n\n\t\t\t\tconst x0 = uvBuffer[ i + 0 ];\n\t\t\t\tconst x1 = uvBuffer[ i + 2 ];\n\t\t\t\tconst x2 = uvBuffer[ i + 4 ];\n\n\t\t\t\tconst max = Math.max( x0, x1, x2 );\n\t\t\t\tconst min = Math.min( x0, x1, x2 );\n\n\t\t\t\t// 0.9 is somewhat arbitrary\n\n\t\t\t\tif ( max > 0.9 && min < 0.1 ) {\n\n\t\t\t\t\tif ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;\n\t\t\t\t\tif ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;\n\t\t\t\t\tif ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction pushVertex( vertex ) {\n\n\t\t\tvertexBuffer.push( vertex.x, vertex.y, vertex.z );\n\n\t\t}\n\n\t\tfunction getVertexByIndex( index, vertex ) {\n\n\t\t\tconst stride = index * 3;\n\n\t\t\tvertex.x = vertices[ stride + 0 ];\n\t\t\tvertex.y = vertices[ stride + 1 ];\n\t\t\tvertex.z = vertices[ stride + 2 ];\n\n\t\t}\n\n\t\tfunction correctUVs() {\n\n\t\t\tconst a = new Vector3();\n\t\t\tconst b = new Vector3();\n\t\t\tconst c = new Vector3();\n\n\t\t\tconst centroid = new Vector3();\n\n\t\t\tconst uvA = new Vector2();\n\t\t\tconst uvB = new Vector2();\n\t\t\tconst uvC = new Vector2();\n\n\t\t\tfor ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {\n\n\t\t\t\ta.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );\n\t\t\t\tb.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );\n\t\t\t\tc.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );\n\n\t\t\t\tuvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );\n\t\t\t\tuvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );\n\t\t\t\tuvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );\n\n\t\t\t\tcentroid.copy( a ).add( b ).add( c ).divideScalar( 3 );\n\n\t\t\t\tconst azi = azimuth( centroid );\n\n\t\t\t\tcorrectUV( uvA, j + 0, a, azi );\n\t\t\t\tcorrectUV( uvB, j + 2, b, azi );\n\t\t\t\tcorrectUV( uvC, j + 4, c, azi );\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction correctUV( uv, stride, vector, azimuth ) {\n\n\t\t\tif ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {\n\n\t\t\t\tuvBuffer[ stride ] = uv.x - 1;\n\n\t\t\t}\n\n\t\t\tif ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {\n\n\t\t\t\tuvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// Angle around the Y axis, counter-clockwise when looking from above.\n\n\t\tfunction azimuth( vector ) {\n\n\t\t\treturn Math.atan2( vector.z, - vector.x );\n\n\t\t}\n\n\n\t\t// Angle above the XZ plane.\n\n\t\tfunction inclination( vector ) {\n\n\t\t\treturn Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );\n\n\t\t}\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );\n\n\t}\n\n}\n\nclass DodecahedronGeometry extends PolyhedronGeometry {\n\n\tconstructor( radius = 1, detail = 0 ) {\n\n\t\tconst t = ( 1 + Math.sqrt( 5 ) ) / 2;\n\t\tconst r = 1 / t;\n\n\t\tconst vertices = [\n\n\t\t\t// (±1, ±1, ±1)\n\t\t\t- 1, - 1, - 1,\t- 1, - 1, 1,\n\t\t\t- 1, 1, - 1, - 1, 1, 1,\n\t\t\t1, - 1, - 1, 1, - 1, 1,\n\t\t\t1, 1, - 1, 1, 1, 1,\n\n\t\t\t// (0, ±1/φ, ±φ)\n\t\t\t0, - r, - t, 0, - r, t,\n\t\t\t0, r, - t, 0, r, t,\n\n\t\t\t// (±1/φ, ±φ, 0)\n\t\t\t- r, - t, 0, - r, t, 0,\n\t\t\tr, - t, 0, r, t, 0,\n\n\t\t\t// (±φ, 0, ±1/φ)\n\t\t\t- t, 0, - r, t, 0, - r,\n\t\t\t- t, 0, r, t, 0, r\n\t\t];\n\n\t\tconst indices = [\n\t\t\t3, 11, 7, \t3, 7, 15, \t3, 15, 13,\n\t\t\t7, 19, 17, \t7, 17, 6, \t7, 6, 15,\n\t\t\t17, 4, 8, \t17, 8, 10, \t17, 10, 6,\n\t\t\t8, 0, 16, \t8, 16, 2, \t8, 2, 10,\n\t\t\t0, 12, 1, \t0, 1, 18, \t0, 18, 16,\n\t\t\t6, 10, 2, \t6, 2, 13, \t6, 13, 15,\n\t\t\t2, 16, 18, \t2, 18, 3, \t2, 3, 13,\n\t\t\t18, 1, 9, \t18, 9, 11, \t18, 11, 3,\n\t\t\t4, 14, 12, \t4, 12, 0, \t4, 0, 8,\n\t\t\t11, 9, 5, \t11, 5, 19, \t11, 19, 7,\n\t\t\t19, 5, 14, \t19, 14, 4, \t19, 4, 17,\n\t\t\t1, 12, 14, \t1, 14, 5, \t1, 5, 9\n\t\t];\n\n\t\tsuper( vertices, indices, radius, detail );\n\n\t\tthis.type = 'DodecahedronGeometry';\n\n\t\tthis.parameters = {\n\t\t\tradius: radius,\n\t\t\tdetail: detail\n\t\t};\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new DodecahedronGeometry( data.radius, data.detail );\n\n\t}\n\n}\n\nconst _v0 = /*@__PURE__*/ new Vector3();\nconst _v1$1 = /*@__PURE__*/ new Vector3();\nconst _normal = /*@__PURE__*/ new Vector3();\nconst _triangle = /*@__PURE__*/ new Triangle();\n\nclass EdgesGeometry extends BufferGeometry {\n\n\tconstructor( geometry = null, thresholdAngle = 1 ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'EdgesGeometry';\n\n\t\tthis.parameters = {\n\t\t\tgeometry: geometry,\n\t\t\tthresholdAngle: thresholdAngle\n\t\t};\n\n\t\tif ( geometry !== null ) {\n\n\t\t\tconst precisionPoints = 4;\n\t\t\tconst precision = Math.pow( 10, precisionPoints );\n\t\t\tconst thresholdDot = Math.cos( DEG2RAD * thresholdAngle );\n\n\t\t\tconst indexAttr = geometry.getIndex();\n\t\t\tconst positionAttr = geometry.getAttribute( 'position' );\n\t\t\tconst indexCount = indexAttr ? indexAttr.count : positionAttr.count;\n\n\t\t\tconst indexArr = [ 0, 0, 0 ];\n\t\t\tconst vertKeys = [ 'a', 'b', 'c' ];\n\t\t\tconst hashes = new Array( 3 );\n\n\t\t\tconst edgeData = {};\n\t\t\tconst vertices = [];\n\t\t\tfor ( let i = 0; i < indexCount; i += 3 ) {\n\n\t\t\t\tif ( indexAttr ) {\n\n\t\t\t\t\tindexArr[ 0 ] = indexAttr.getX( i );\n\t\t\t\t\tindexArr[ 1 ] = indexAttr.getX( i + 1 );\n\t\t\t\t\tindexArr[ 2 ] = indexAttr.getX( i + 2 );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tindexArr[ 0 ] = i;\n\t\t\t\t\tindexArr[ 1 ] = i + 1;\n\t\t\t\t\tindexArr[ 2 ] = i + 2;\n\n\t\t\t\t}\n\n\t\t\t\tconst { a, b, c } = _triangle;\n\t\t\t\ta.fromBufferAttribute( positionAttr, indexArr[ 0 ] );\n\t\t\t\tb.fromBufferAttribute( positionAttr, indexArr[ 1 ] );\n\t\t\t\tc.fromBufferAttribute( positionAttr, indexArr[ 2 ] );\n\t\t\t\t_triangle.getNormal( _normal );\n\n\t\t\t\t// create hashes for the edge from the vertices\n\t\t\t\thashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;\n\t\t\t\thashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;\n\t\t\t\thashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;\n\n\t\t\t\t// skip degenerate triangles\n\t\t\t\tif ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\t}\n\n\t\t\t\t// iterate over every edge\n\t\t\t\tfor ( let j = 0; j < 3; j ++ ) {\n\n\t\t\t\t\t// get the first and next vertex making up the edge\n\t\t\t\t\tconst jNext = ( j + 1 ) % 3;\n\t\t\t\t\tconst vecHash0 = hashes[ j ];\n\t\t\t\t\tconst vecHash1 = hashes[ jNext ];\n\t\t\t\t\tconst v0 = _triangle[ vertKeys[ j ] ];\n\t\t\t\t\tconst v1 = _triangle[ vertKeys[ jNext ] ];\n\n\t\t\t\t\tconst hash = `${ vecHash0 }_${ vecHash1 }`;\n\t\t\t\t\tconst reverseHash = `${ vecHash1 }_${ vecHash0 }`;\n\n\t\t\t\t\tif ( reverseHash in edgeData && edgeData[ reverseHash ] ) {\n\n\t\t\t\t\t\t// if we found a sibling edge add it into the vertex array if\n\t\t\t\t\t\t// it meets the angle threshold and delete the edge from the map.\n\t\t\t\t\t\tif ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {\n\n\t\t\t\t\t\t\tvertices.push( v0.x, v0.y, v0.z );\n\t\t\t\t\t\t\tvertices.push( v1.x, v1.y, v1.z );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tedgeData[ reverseHash ] = null;\n\n\t\t\t\t\t} else if ( ! ( hash in edgeData ) ) {\n\n\t\t\t\t\t\t// if we've already got an edge here then skip adding a new one\n\t\t\t\t\t\tedgeData[ hash ] = {\n\n\t\t\t\t\t\t\tindex0: indexArr[ j ],\n\t\t\t\t\t\t\tindex1: indexArr[ jNext ],\n\t\t\t\t\t\t\tnormal: _normal.clone(),\n\n\t\t\t\t\t\t};\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// iterate over all remaining, unmatched edges and add them to the vertex array\n\t\t\tfor ( const key in edgeData ) {\n\n\t\t\t\tif ( edgeData[ key ] ) {\n\n\t\t\t\t\tconst { index0, index1 } = edgeData[ key ];\n\t\t\t\t\t_v0.fromBufferAttribute( positionAttr, index0 );\n\t\t\t\t\t_v1$1.fromBufferAttribute( positionAttr, index1 );\n\n\t\t\t\t\tvertices.push( _v0.x, _v0.y, _v0.z );\n\t\t\t\t\tvertices.push( _v1$1.x, _v1$1.y, _v1$1.z );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\n\t\t}\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass Shape extends Path {\n\n\tconstructor( points ) {\n\n\t\tsuper( points );\n\n\t\tthis.uuid = generateUUID();\n\n\t\tthis.type = 'Shape';\n\n\t\tthis.holes = [];\n\n\t}\n\n\tgetPointsHoles( divisions ) {\n\n\t\tconst holesPts = [];\n\n\t\tfor ( let i = 0, l = this.holes.length; i < l; i ++ ) {\n\n\t\t\tholesPts[ i ] = this.holes[ i ].getPoints( divisions );\n\n\t\t}\n\n\t\treturn holesPts;\n\n\t}\n\n\t// get points of shape and holes (keypoints based on segments parameter)\n\n\textractPoints( divisions ) {\n\n\t\treturn {\n\n\t\t\tshape: this.getPoints( divisions ),\n\t\t\tholes: this.getPointsHoles( divisions )\n\n\t\t};\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.holes = [];\n\n\t\tfor ( let i = 0, l = source.holes.length; i < l; i ++ ) {\n\n\t\t\tconst hole = source.holes[ i ];\n\n\t\t\tthis.holes.push( hole.clone() );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.uuid = this.uuid;\n\t\tdata.holes = [];\n\n\t\tfor ( let i = 0, l = this.holes.length; i < l; i ++ ) {\n\n\t\t\tconst hole = this.holes[ i ];\n\t\t\tdata.holes.push( hole.toJSON() );\n\n\t\t}\n\n\t\treturn data;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tsuper.fromJSON( json );\n\n\t\tthis.uuid = json.uuid;\n\t\tthis.holes = [];\n\n\t\tfor ( let i = 0, l = json.holes.length; i < l; i ++ ) {\n\n\t\t\tconst hole = json.holes[ i ];\n\t\t\tthis.holes.push( new Path().fromJSON( hole ) );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n}\n\n/**\n * Port from https://github.com/mapbox/earcut (v2.2.4)\n */\n\nconst Earcut = {\n\n\ttriangulate: function ( data, holeIndices, dim = 2 ) {\n\n\t\tconst hasHoles = holeIndices && holeIndices.length;\n\t\tconst outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;\n\t\tlet outerNode = linkedList( data, 0, outerLen, dim, true );\n\t\tconst triangles = [];\n\n\t\tif ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;\n\n\t\tlet minX, minY, maxX, maxY, x, y, invSize;\n\n\t\tif ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );\n\n\t\t// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n\t\tif ( data.length > 80 * dim ) {\n\n\t\t\tminX = maxX = data[ 0 ];\n\t\t\tminY = maxY = data[ 1 ];\n\n\t\t\tfor ( let i = dim; i < outerLen; i += dim ) {\n\n\t\t\t\tx = data[ i ];\n\t\t\t\ty = data[ i + 1 ];\n\t\t\t\tif ( x < minX ) minX = x;\n\t\t\t\tif ( y < minY ) minY = y;\n\t\t\t\tif ( x > maxX ) maxX = x;\n\t\t\t\tif ( y > maxY ) maxY = y;\n\n\t\t\t}\n\n\t\t\t// minX, minY and invSize are later used to transform coords into integers for z-order calculation\n\t\t\tinvSize = Math.max( maxX - minX, maxY - minY );\n\t\t\tinvSize = invSize !== 0 ? 32767 / invSize : 0;\n\n\t\t}\n\n\t\tearcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );\n\n\t\treturn triangles;\n\n\t}\n\n};\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList( data, start, end, dim, clockwise ) {\n\n\tlet i, last;\n\n\tif ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {\n\n\t\tfor ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );\n\n\t} else {\n\n\t\tfor ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );\n\n\t}\n\n\tif ( last && equals( last, last.next ) ) {\n\n\t\tremoveNode( last );\n\t\tlast = last.next;\n\n\t}\n\n\treturn last;\n\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints( start, end ) {\n\n\tif ( ! start ) return start;\n\tif ( ! end ) end = start;\n\n\tlet p = start,\n\t\tagain;\n\tdo {\n\n\t\tagain = false;\n\n\t\tif ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {\n\n\t\t\tremoveNode( p );\n\t\t\tp = end = p.prev;\n\t\t\tif ( p === p.next ) break;\n\t\t\tagain = true;\n\n\t\t} else {\n\n\t\t\tp = p.next;\n\n\t\t}\n\n\t} while ( again || p !== end );\n\n\treturn end;\n\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {\n\n\tif ( ! ear ) return;\n\n\t// interlink polygon nodes in z-order\n\tif ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );\n\n\tlet stop = ear,\n\t\tprev, next;\n\n\t// iterate through ears, slicing them one by one\n\twhile ( ear.prev !== ear.next ) {\n\n\t\tprev = ear.prev;\n\t\tnext = ear.next;\n\n\t\tif ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {\n\n\t\t\t// cut off the triangle\n\t\t\ttriangles.push( prev.i / dim | 0 );\n\t\t\ttriangles.push( ear.i / dim | 0 );\n\t\t\ttriangles.push( next.i / dim | 0 );\n\n\t\t\tremoveNode( ear );\n\n\t\t\t// skipping the next vertex leads to less sliver triangles\n\t\t\tear = next.next;\n\t\t\tstop = next.next;\n\n\t\t\tcontinue;\n\n\t\t}\n\n\t\tear = next;\n\n\t\t// if we looped through the whole remaining polygon and can't find any more ears\n\t\tif ( ear === stop ) {\n\n\t\t\t// try filtering points and slicing again\n\t\t\tif ( ! pass ) {\n\n\t\t\t\tearcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );\n\n\t\t\t\t// if this didn't work, try curing all small self-intersections locally\n\n\t\t\t} else if ( pass === 1 ) {\n\n\t\t\t\tear = cureLocalIntersections( filterPoints( ear ), triangles, dim );\n\t\t\t\tearcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );\n\n\t\t\t\t// as a last resort, try splitting the remaining polygon into two\n\n\t\t\t} else if ( pass === 2 ) {\n\n\t\t\t\tsplitEarcut( ear, triangles, dim, minX, minY, invSize );\n\n\t\t\t}\n\n\t\t\tbreak;\n\n\t\t}\n\n\t}\n\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar( ear ) {\n\n\tconst a = ear.prev,\n\t\tb = ear,\n\t\tc = ear.next;\n\n\tif ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear\n\n\t// now make sure we don't have other points inside the potential ear\n\tconst ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n\t// triangle bbox; min & max are calculated like this for speed\n\tconst x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),\n\t\ty0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),\n\t\tx1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),\n\t\ty1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );\n\n\tlet p = c.next;\n\twhile ( p !== a ) {\n\n\t\tif ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&\n\t\t\tarea( p.prev, p, p.next ) >= 0 ) return false;\n\t\tp = p.next;\n\n\t}\n\n\treturn true;\n\n}\n\nfunction isEarHashed( ear, minX, minY, invSize ) {\n\n\tconst a = ear.prev,\n\t\tb = ear,\n\t\tc = ear.next;\n\n\tif ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear\n\n\tconst ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n\t// triangle bbox; min & max are calculated like this for speed\n\tconst x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),\n\t\ty0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),\n\t\tx1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),\n\t\ty1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );\n\n\t// z-order range for the current triangle bbox;\n\tconst minZ = zOrder( x0, y0, minX, minY, invSize ),\n\t\tmaxZ = zOrder( x1, y1, minX, minY, invSize );\n\n\tlet p = ear.prevZ,\n\t\tn = ear.nextZ;\n\n\t// look for points inside the triangle in both directions\n\twhile ( p && p.z >= minZ && n && n.z <= maxZ ) {\n\n\t\tif ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;\n\t\tp = p.prevZ;\n\n\t\tif ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;\n\t\tn = n.nextZ;\n\n\t}\n\n\t// look for remaining points in decreasing z-order\n\twhile ( p && p.z >= minZ ) {\n\n\t\tif ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;\n\t\tp = p.prevZ;\n\n\t}\n\n\t// look for remaining points in increasing z-order\n\twhile ( n && n.z <= maxZ ) {\n\n\t\tif ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;\n\t\tn = n.nextZ;\n\n\t}\n\n\treturn true;\n\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections( start, triangles, dim ) {\n\n\tlet p = start;\n\tdo {\n\n\t\tconst a = p.prev,\n\t\t\tb = p.next.next;\n\n\t\tif ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {\n\n\t\t\ttriangles.push( a.i / dim | 0 );\n\t\t\ttriangles.push( p.i / dim | 0 );\n\t\t\ttriangles.push( b.i / dim | 0 );\n\n\t\t\t// remove two nodes involved\n\t\t\tremoveNode( p );\n\t\t\tremoveNode( p.next );\n\n\t\t\tp = start = b;\n\n\t\t}\n\n\t\tp = p.next;\n\n\t} while ( p !== start );\n\n\treturn filterPoints( p );\n\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut( start, triangles, dim, minX, minY, invSize ) {\n\n\t// look for a valid diagonal that divides the polygon into two\n\tlet a = start;\n\tdo {\n\n\t\tlet b = a.next.next;\n\t\twhile ( b !== a.prev ) {\n\n\t\t\tif ( a.i !== b.i && isValidDiagonal( a, b ) ) {\n\n\t\t\t\t// split the polygon in two by the diagonal\n\t\t\t\tlet c = splitPolygon( a, b );\n\n\t\t\t\t// filter colinear points around the cuts\n\t\t\t\ta = filterPoints( a, a.next );\n\t\t\t\tc = filterPoints( c, c.next );\n\n\t\t\t\t// run earcut on each half\n\t\t\t\tearcutLinked( a, triangles, dim, minX, minY, invSize, 0 );\n\t\t\t\tearcutLinked( c, triangles, dim, minX, minY, invSize, 0 );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tb = b.next;\n\n\t\t}\n\n\t\ta = a.next;\n\n\t} while ( a !== start );\n\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles( data, holeIndices, outerNode, dim ) {\n\n\tconst queue = [];\n\tlet i, len, start, end, list;\n\n\tfor ( i = 0, len = holeIndices.length; i < len; i ++ ) {\n\n\t\tstart = holeIndices[ i ] * dim;\n\t\tend = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;\n\t\tlist = linkedList( data, start, end, dim, false );\n\t\tif ( list === list.next ) list.steiner = true;\n\t\tqueue.push( getLeftmost( list ) );\n\n\t}\n\n\tqueue.sort( compareX );\n\n\t// process holes from left to right\n\tfor ( i = 0; i < queue.length; i ++ ) {\n\n\t\touterNode = eliminateHole( queue[ i ], outerNode );\n\n\t}\n\n\treturn outerNode;\n\n}\n\nfunction compareX( a, b ) {\n\n\treturn a.x - b.x;\n\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole( hole, outerNode ) {\n\n\tconst bridge = findHoleBridge( hole, outerNode );\n\tif ( ! bridge ) {\n\n\t\treturn outerNode;\n\n\t}\n\n\tconst bridgeReverse = splitPolygon( bridge, hole );\n\n\t// filter collinear points around the cuts\n\tfilterPoints( bridgeReverse, bridgeReverse.next );\n\treturn filterPoints( bridge, bridge.next );\n\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge( hole, outerNode ) {\n\n\tlet p = outerNode,\n\t\tqx = - Infinity,\n\t\tm;\n\n\tconst hx = hole.x, hy = hole.y;\n\n\t// find a segment intersected by a ray from the hole's leftmost point to the left;\n\t// segment's endpoint with lesser x will be potential connection point\n\tdo {\n\n\t\tif ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {\n\n\t\t\tconst x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );\n\t\t\tif ( x <= hx && x > qx ) {\n\n\t\t\t\tqx = x;\n\t\t\t\tm = p.x < p.next.x ? p : p.next;\n\t\t\t\tif ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint\n\n\t\t\t}\n\n\t\t}\n\n\t\tp = p.next;\n\n\t} while ( p !== outerNode );\n\n\tif ( ! m ) return null;\n\n\t// look for points inside the triangle of hole point, segment intersection and endpoint;\n\t// if there are no points found, we have a valid connection;\n\t// otherwise choose the point of the minimum angle with the ray as connection point\n\n\tconst stop = m,\n\t\tmx = m.x,\n\t\tmy = m.y;\n\tlet tanMin = Infinity, tan;\n\n\tp = m;\n\n\tdo {\n\n\t\tif ( hx >= p.x && p.x >= mx && hx !== p.x &&\n\t\t\t\tpointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {\n\n\t\t\ttan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential\n\n\t\t\tif ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {\n\n\t\t\t\tm = p;\n\t\t\t\ttanMin = tan;\n\n\t\t\t}\n\n\t\t}\n\n\t\tp = p.next;\n\n\t} while ( p !== stop );\n\n\treturn m;\n\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector( m, p ) {\n\n\treturn area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;\n\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve( start, minX, minY, invSize ) {\n\n\tlet p = start;\n\tdo {\n\n\t\tif ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );\n\t\tp.prevZ = p.prev;\n\t\tp.nextZ = p.next;\n\t\tp = p.next;\n\n\t} while ( p !== start );\n\n\tp.prevZ.nextZ = null;\n\tp.prevZ = null;\n\n\tsortLinked( p );\n\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked( list ) {\n\n\tlet i, p, q, e, tail, numMerges, pSize, qSize,\n\t\tinSize = 1;\n\n\tdo {\n\n\t\tp = list;\n\t\tlist = null;\n\t\ttail = null;\n\t\tnumMerges = 0;\n\n\t\twhile ( p ) {\n\n\t\t\tnumMerges ++;\n\t\t\tq = p;\n\t\t\tpSize = 0;\n\t\t\tfor ( i = 0; i < inSize; i ++ ) {\n\n\t\t\t\tpSize ++;\n\t\t\t\tq = q.nextZ;\n\t\t\t\tif ( ! q ) break;\n\n\t\t\t}\n\n\t\t\tqSize = inSize;\n\n\t\t\twhile ( pSize > 0 || ( qSize > 0 && q ) ) {\n\n\t\t\t\tif ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {\n\n\t\t\t\t\te = p;\n\t\t\t\t\tp = p.nextZ;\n\t\t\t\t\tpSize --;\n\n\t\t\t\t} else {\n\n\t\t\t\t\te = q;\n\t\t\t\t\tq = q.nextZ;\n\t\t\t\t\tqSize --;\n\n\t\t\t\t}\n\n\t\t\t\tif ( tail ) tail.nextZ = e;\n\t\t\t\telse list = e;\n\n\t\t\t\te.prevZ = tail;\n\t\t\t\ttail = e;\n\n\t\t\t}\n\n\t\t\tp = q;\n\n\t\t}\n\n\t\ttail.nextZ = null;\n\t\tinSize *= 2;\n\n\t} while ( numMerges > 1 );\n\n\treturn list;\n\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder( x, y, minX, minY, invSize ) {\n\n\t// coords are transformed into non-negative 15-bit integer range\n\tx = ( x - minX ) * invSize | 0;\n\ty = ( y - minY ) * invSize | 0;\n\n\tx = ( x | ( x << 8 ) ) & 0x00FF00FF;\n\tx = ( x | ( x << 4 ) ) & 0x0F0F0F0F;\n\tx = ( x | ( x << 2 ) ) & 0x33333333;\n\tx = ( x | ( x << 1 ) ) & 0x55555555;\n\n\ty = ( y | ( y << 8 ) ) & 0x00FF00FF;\n\ty = ( y | ( y << 4 ) ) & 0x0F0F0F0F;\n\ty = ( y | ( y << 2 ) ) & 0x33333333;\n\ty = ( y | ( y << 1 ) ) & 0x55555555;\n\n\treturn x | ( y << 1 );\n\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost( start ) {\n\n\tlet p = start,\n\t\tleftmost = start;\n\tdo {\n\n\t\tif ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;\n\t\tp = p.next;\n\n\t} while ( p !== start );\n\n\treturn leftmost;\n\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {\n\n\treturn ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&\n ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&\n ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );\n\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal( a, b ) {\n\n\treturn a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges\n ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible\n ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors\n equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case\n\n}\n\n// signed area of a triangle\nfunction area( p, q, r ) {\n\n\treturn ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );\n\n}\n\n// check if two points are equal\nfunction equals( p1, p2 ) {\n\n\treturn p1.x === p2.x && p1.y === p2.y;\n\n}\n\n// check if two segments intersect\nfunction intersects( p1, q1, p2, q2 ) {\n\n\tconst o1 = sign( area( p1, q1, p2 ) );\n\tconst o2 = sign( area( p1, q1, q2 ) );\n\tconst o3 = sign( area( p2, q2, p1 ) );\n\tconst o4 = sign( area( p2, q2, q1 ) );\n\n\tif ( o1 !== o2 && o3 !== o4 ) return true; // general case\n\n\tif ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n\tif ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n\tif ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n\tif ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n\treturn false;\n\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment( p, q, r ) {\n\n\treturn q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y );\n\n}\n\nfunction sign( num ) {\n\n\treturn num > 0 ? 1 : num < 0 ? - 1 : 0;\n\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon( a, b ) {\n\n\tlet p = a;\n\tdo {\n\n\t\tif ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n\t\t\tintersects( p, p.next, a, b ) ) return true;\n\t\tp = p.next;\n\n\t} while ( p !== a );\n\n\treturn false;\n\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside( a, b ) {\n\n\treturn area( a.prev, a, a.next ) < 0 ?\n\t\tarea( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :\n\t\tarea( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;\n\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside( a, b ) {\n\n\tlet p = a,\n\t\tinside = false;\n\tconst px = ( a.x + b.x ) / 2,\n\t\tpy = ( a.y + b.y ) / 2;\n\tdo {\n\n\t\tif ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&\n\t\t\t( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )\n\t\t\tinside = ! inside;\n\t\tp = p.next;\n\n\t} while ( p !== a );\n\n\treturn inside;\n\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon( a, b ) {\n\n\tconst a2 = new Node( a.i, a.x, a.y ),\n\t\tb2 = new Node( b.i, b.x, b.y ),\n\t\tan = a.next,\n\t\tbp = b.prev;\n\n\ta.next = b;\n\tb.prev = a;\n\n\ta2.next = an;\n\tan.prev = a2;\n\n\tb2.next = a2;\n\ta2.prev = b2;\n\n\tbp.next = b2;\n\tb2.prev = bp;\n\n\treturn b2;\n\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode( i, x, y, last ) {\n\n\tconst p = new Node( i, x, y );\n\n\tif ( ! last ) {\n\n\t\tp.prev = p;\n\t\tp.next = p;\n\n\t} else {\n\n\t\tp.next = last.next;\n\t\tp.prev = last;\n\t\tlast.next.prev = p;\n\t\tlast.next = p;\n\n\t}\n\n\treturn p;\n\n}\n\nfunction removeNode( p ) {\n\n\tp.next.prev = p.prev;\n\tp.prev.next = p.next;\n\n\tif ( p.prevZ ) p.prevZ.nextZ = p.nextZ;\n\tif ( p.nextZ ) p.nextZ.prevZ = p.prevZ;\n\n}\n\nfunction Node( i, x, y ) {\n\n\t// vertex index in coordinates array\n\tthis.i = i;\n\n\t// vertex coordinates\n\tthis.x = x;\n\tthis.y = y;\n\n\t// previous and next vertex nodes in a polygon ring\n\tthis.prev = null;\n\tthis.next = null;\n\n\t// z-order curve value\n\tthis.z = 0;\n\n\t// previous and next nodes in z-order\n\tthis.prevZ = null;\n\tthis.nextZ = null;\n\n\t// indicates whether this is a steiner point\n\tthis.steiner = false;\n\n}\n\nfunction signedArea( data, start, end, dim ) {\n\n\tlet sum = 0;\n\tfor ( let i = start, j = end - dim; i < end; i += dim ) {\n\n\t\tsum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );\n\t\tj = i;\n\n\t}\n\n\treturn sum;\n\n}\n\nclass ShapeUtils {\n\n\t// calculate area of the contour polygon\n\n\tstatic area( contour ) {\n\n\t\tconst n = contour.length;\n\t\tlet a = 0.0;\n\n\t\tfor ( let p = n - 1, q = 0; q < n; p = q ++ ) {\n\n\t\t\ta += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;\n\n\t\t}\n\n\t\treturn a * 0.5;\n\n\t}\n\n\tstatic isClockWise( pts ) {\n\n\t\treturn ShapeUtils.area( pts ) < 0;\n\n\t}\n\n\tstatic triangulateShape( contour, holes ) {\n\n\t\tconst vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]\n\t\tconst holeIndices = []; // array of hole indices\n\t\tconst faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]\n\n\t\tremoveDupEndPts( contour );\n\t\taddContour( vertices, contour );\n\n\t\t//\n\n\t\tlet holeIndex = contour.length;\n\n\t\tholes.forEach( removeDupEndPts );\n\n\t\tfor ( let i = 0; i < holes.length; i ++ ) {\n\n\t\t\tholeIndices.push( holeIndex );\n\t\t\tholeIndex += holes[ i ].length;\n\t\t\taddContour( vertices, holes[ i ] );\n\n\t\t}\n\n\t\t//\n\n\t\tconst triangles = Earcut.triangulate( vertices, holeIndices );\n\n\t\t//\n\n\t\tfor ( let i = 0; i < triangles.length; i += 3 ) {\n\n\t\t\tfaces.push( triangles.slice( i, i + 3 ) );\n\n\t\t}\n\n\t\treturn faces;\n\n\t}\n\n}\n\nfunction removeDupEndPts( points ) {\n\n\tconst l = points.length;\n\n\tif ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {\n\n\t\tpoints.pop();\n\n\t}\n\n}\n\nfunction addContour( vertices, contour ) {\n\n\tfor ( let i = 0; i < contour.length; i ++ ) {\n\n\t\tvertices.push( contour[ i ].x );\n\t\tvertices.push( contour[ i ].y );\n\n\t}\n\n}\n\n/**\n * Creates extruded geometry from a path shape.\n *\n * parameters = {\n *\n * curveSegments: , // number of points on the curves\n * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too\n * depth: , // Depth to extrude the shape\n *\n * bevelEnabled: , // turn on bevel\n * bevelThickness: , // how deep into the original shape bevel goes\n * bevelSize: , // how far from shape outline (including bevelOffset) is bevel\n * bevelOffset: , // how far from shape outline does bevel start\n * bevelSegments: , // number of bevel layers\n *\n * extrudePath: // curve to extrude shape along\n *\n * UVGenerator: // object that provides UV generator functions\n *\n * }\n */\n\nclass ExtrudeGeometry extends BufferGeometry {\n\n\tconstructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'ExtrudeGeometry';\n\n\t\tthis.parameters = {\n\t\t\tshapes: shapes,\n\t\t\toptions: options\n\t\t};\n\n\t\tshapes = Array.isArray( shapes ) ? shapes : [ shapes ];\n\n\t\tconst scope = this;\n\n\t\tconst verticesArray = [];\n\t\tconst uvArray = [];\n\n\t\tfor ( let i = 0, l = shapes.length; i < l; i ++ ) {\n\n\t\t\tconst shape = shapes[ i ];\n\t\t\taddShape( shape );\n\n\t\t}\n\n\t\t// build geometry\n\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );\n\n\t\tthis.computeVertexNormals();\n\n\t\t// functions\n\n\t\tfunction addShape( shape ) {\n\n\t\t\tconst placeholder = [];\n\n\t\t\t// options\n\n\t\t\tconst curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;\n\t\t\tconst steps = options.steps !== undefined ? options.steps : 1;\n\t\t\tconst depth = options.depth !== undefined ? options.depth : 1;\n\n\t\t\tlet bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;\n\t\t\tlet bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;\n\t\t\tlet bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;\n\t\t\tlet bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;\n\t\t\tlet bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;\n\n\t\t\tconst extrudePath = options.extrudePath;\n\n\t\t\tconst uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;\n\n\t\t\t//\n\n\t\t\tlet extrudePts, extrudeByPath = false;\n\t\t\tlet splineTube, binormal, normal, position2;\n\n\t\t\tif ( extrudePath ) {\n\n\t\t\t\textrudePts = extrudePath.getSpacedPoints( steps );\n\n\t\t\t\textrudeByPath = true;\n\t\t\t\tbevelEnabled = false; // bevels not supported for path extrusion\n\n\t\t\t\t// SETUP TNB variables\n\n\t\t\t\t// TODO1 - have a .isClosed in spline?\n\n\t\t\t\tsplineTube = extrudePath.computeFrenetFrames( steps, false );\n\n\t\t\t\t// console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);\n\n\t\t\t\tbinormal = new Vector3();\n\t\t\t\tnormal = new Vector3();\n\t\t\t\tposition2 = new Vector3();\n\n\t\t\t}\n\n\t\t\t// Safeguards if bevels are not enabled\n\n\t\t\tif ( ! bevelEnabled ) {\n\n\t\t\t\tbevelSegments = 0;\n\t\t\t\tbevelThickness = 0;\n\t\t\t\tbevelSize = 0;\n\t\t\t\tbevelOffset = 0;\n\n\t\t\t}\n\n\t\t\t// Variables initialization\n\n\t\t\tconst shapePoints = shape.extractPoints( curveSegments );\n\n\t\t\tlet vertices = shapePoints.shape;\n\t\t\tconst holes = shapePoints.holes;\n\n\t\t\tconst reverse = ! ShapeUtils.isClockWise( vertices );\n\n\t\t\tif ( reverse ) {\n\n\t\t\t\tvertices = vertices.reverse();\n\n\t\t\t\t// Maybe we should also check if holes are in the opposite direction, just to be safe ...\n\n\t\t\t\tfor ( let h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\t\t\tconst ahole = holes[ h ];\n\n\t\t\t\t\tif ( ShapeUtils.isClockWise( ahole ) ) {\n\n\t\t\t\t\t\tholes[ h ] = ahole.reverse();\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\t\t\tconst faces = ShapeUtils.triangulateShape( vertices, holes );\n\n\t\t\t/* Vertices */\n\n\t\t\tconst contour = vertices; // vertices has all points but contour has only points of circumference\n\n\t\t\tfor ( let h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\t\tconst ahole = holes[ h ];\n\n\t\t\t\tvertices = vertices.concat( ahole );\n\n\t\t\t}\n\n\n\t\t\tfunction scalePt2( pt, vec, size ) {\n\n\t\t\t\tif ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );\n\n\t\t\t\treturn pt.clone().addScaledVector( vec, size );\n\n\t\t\t}\n\n\t\t\tconst vlen = vertices.length, flen = faces.length;\n\n\n\t\t\t// Find directions for point movement\n\n\n\t\t\tfunction getBevelVec( inPt, inPrev, inNext ) {\n\n\t\t\t\t// computes for inPt the corresponding point inPt' on a new contour\n\t\t\t\t// shifted by 1 unit (length of normalized vector) to the left\n\t\t\t\t// if we walk along contour clockwise, this new contour is outside the old one\n\t\t\t\t//\n\t\t\t\t// inPt' is the intersection of the two lines parallel to the two\n\t\t\t\t// adjacent edges of inPt at a distance of 1 unit on the left side.\n\n\t\t\t\tlet v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt\n\n\t\t\t\t// good reading for geometry algorithms (here: line-line intersection)\n\t\t\t\t// http://geomalgorithms.com/a05-_intersect-1.html\n\n\t\t\t\tconst v_prev_x = inPt.x - inPrev.x,\n\t\t\t\t\tv_prev_y = inPt.y - inPrev.y;\n\t\t\t\tconst v_next_x = inNext.x - inPt.x,\n\t\t\t\t\tv_next_y = inNext.y - inPt.y;\n\n\t\t\t\tconst v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );\n\n\t\t\t\t// check for collinear edges\n\t\t\t\tconst collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );\n\n\t\t\t\tif ( Math.abs( collinear0 ) > Number.EPSILON ) {\n\n\t\t\t\t\t// not collinear\n\n\t\t\t\t\t// length of vectors for normalizing\n\n\t\t\t\t\tconst v_prev_len = Math.sqrt( v_prev_lensq );\n\t\t\t\t\tconst v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );\n\n\t\t\t\t\t// shift adjacent points by unit vectors to the left\n\n\t\t\t\t\tconst ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );\n\t\t\t\t\tconst ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );\n\n\t\t\t\t\tconst ptNextShift_x = ( inNext.x - v_next_y / v_next_len );\n\t\t\t\t\tconst ptNextShift_y = ( inNext.y + v_next_x / v_next_len );\n\n\t\t\t\t\t// scaling factor for v_prev to intersection point\n\n\t\t\t\t\tconst sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -\n\t\t\t\t\t\t\t( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /\n\t\t\t\t\t\t( v_prev_x * v_next_y - v_prev_y * v_next_x );\n\n\t\t\t\t\t// vector from inPt to intersection point\n\n\t\t\t\t\tv_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );\n\t\t\t\t\tv_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );\n\n\t\t\t\t\t// Don't normalize!, otherwise sharp corners become ugly\n\t\t\t\t\t// but prevent crazy spikes\n\t\t\t\t\tconst v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );\n\t\t\t\t\tif ( v_trans_lensq <= 2 ) {\n\n\t\t\t\t\t\treturn new Vector2( v_trans_x, v_trans_y );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tshrink_by = Math.sqrt( v_trans_lensq / 2 );\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// handle special case of collinear edges\n\n\t\t\t\t\tlet direction_eq = false; // assumes: opposite\n\n\t\t\t\t\tif ( v_prev_x > Number.EPSILON ) {\n\n\t\t\t\t\t\tif ( v_next_x > Number.EPSILON ) {\n\n\t\t\t\t\t\t\tdirection_eq = true;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tif ( v_prev_x < - Number.EPSILON ) {\n\n\t\t\t\t\t\t\tif ( v_next_x < - Number.EPSILON ) {\n\n\t\t\t\t\t\t\t\tdirection_eq = true;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tif ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {\n\n\t\t\t\t\t\t\t\tdirection_eq = true;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( direction_eq ) {\n\n\t\t\t\t\t\t// console.log(\"Warning: lines are a straight sequence\");\n\t\t\t\t\t\tv_trans_x = - v_prev_y;\n\t\t\t\t\t\tv_trans_y = v_prev_x;\n\t\t\t\t\t\tshrink_by = Math.sqrt( v_prev_lensq );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t// console.log(\"Warning: lines are a straight spike\");\n\t\t\t\t\t\tv_trans_x = v_prev_x;\n\t\t\t\t\t\tv_trans_y = v_prev_y;\n\t\t\t\t\t\tshrink_by = Math.sqrt( v_prev_lensq / 2 );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\treturn new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );\n\n\t\t\t}\n\n\n\t\t\tconst contourMovements = [];\n\n\t\t\tfor ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {\n\n\t\t\t\tif ( j === il ) j = 0;\n\t\t\t\tif ( k === il ) k = 0;\n\n\t\t\t\t// (j)---(i)---(k)\n\t\t\t\t// console.log('i,j,k', i, j , k)\n\n\t\t\t\tcontourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );\n\n\t\t\t}\n\n\t\t\tconst holesMovements = [];\n\t\t\tlet oneHoleMovements, verticesMovements = contourMovements.concat();\n\n\t\t\tfor ( let h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\t\tconst ahole = holes[ h ];\n\n\t\t\t\toneHoleMovements = [];\n\n\t\t\t\tfor ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {\n\n\t\t\t\t\tif ( j === il ) j = 0;\n\t\t\t\t\tif ( k === il ) k = 0;\n\n\t\t\t\t\t// (j)---(i)---(k)\n\t\t\t\t\toneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );\n\n\t\t\t\t}\n\n\t\t\t\tholesMovements.push( oneHoleMovements );\n\t\t\t\tverticesMovements = verticesMovements.concat( oneHoleMovements );\n\n\t\t\t}\n\n\n\t\t\t// Loop bevelSegments, 1 for the front, 1 for the back\n\n\t\t\tfor ( let b = 0; b < bevelSegments; b ++ ) {\n\n\t\t\t\t//for ( b = bevelSegments; b > 0; b -- ) {\n\n\t\t\t\tconst t = b / bevelSegments;\n\t\t\t\tconst z = bevelThickness * Math.cos( t * Math.PI / 2 );\n\t\t\t\tconst bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;\n\n\t\t\t\t// contract shape\n\n\t\t\t\tfor ( let i = 0, il = contour.length; i < il; i ++ ) {\n\n\t\t\t\t\tconst vert = scalePt2( contour[ i ], contourMovements[ i ], bs );\n\n\t\t\t\t\tv( vert.x, vert.y, - z );\n\n\t\t\t\t}\n\n\t\t\t\t// expand holes\n\n\t\t\t\tfor ( let h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\t\t\tconst ahole = holes[ h ];\n\t\t\t\t\toneHoleMovements = holesMovements[ h ];\n\n\t\t\t\t\tfor ( let i = 0, il = ahole.length; i < il; i ++ ) {\n\n\t\t\t\t\t\tconst vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );\n\n\t\t\t\t\t\tv( vert.x, vert.y, - z );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tconst bs = bevelSize + bevelOffset;\n\n\t\t\t// Back facing vertices\n\n\t\t\tfor ( let i = 0; i < vlen; i ++ ) {\n\n\t\t\t\tconst vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];\n\n\t\t\t\tif ( ! extrudeByPath ) {\n\n\t\t\t\t\tv( vert.x, vert.y, 0 );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );\n\n\t\t\t\t\tnormal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );\n\t\t\t\t\tbinormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );\n\n\t\t\t\t\tposition2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );\n\n\t\t\t\t\tv( position2.x, position2.y, position2.z );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// Add stepped vertices...\n\t\t\t// Including front facing vertices\n\n\t\t\tfor ( let s = 1; s <= steps; s ++ ) {\n\n\t\t\t\tfor ( let i = 0; i < vlen; i ++ ) {\n\n\t\t\t\t\tconst vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];\n\n\t\t\t\t\tif ( ! extrudeByPath ) {\n\n\t\t\t\t\t\tv( vert.x, vert.y, depth / steps * s );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t// v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );\n\n\t\t\t\t\t\tnormal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );\n\t\t\t\t\t\tbinormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );\n\n\t\t\t\t\t\tposition2.copy( extrudePts[ s ] ).add( normal ).add( binormal );\n\n\t\t\t\t\t\tv( position2.x, position2.y, position2.z );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\t\t\t// Add bevel segments planes\n\n\t\t\t//for ( b = 1; b <= bevelSegments; b ++ ) {\n\t\t\tfor ( let b = bevelSegments - 1; b >= 0; b -- ) {\n\n\t\t\t\tconst t = b / bevelSegments;\n\t\t\t\tconst z = bevelThickness * Math.cos( t * Math.PI / 2 );\n\t\t\t\tconst bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;\n\n\t\t\t\t// contract shape\n\n\t\t\t\tfor ( let i = 0, il = contour.length; i < il; i ++ ) {\n\n\t\t\t\t\tconst vert = scalePt2( contour[ i ], contourMovements[ i ], bs );\n\t\t\t\t\tv( vert.x, vert.y, depth + z );\n\n\t\t\t\t}\n\n\t\t\t\t// expand holes\n\n\t\t\t\tfor ( let h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\t\t\tconst ahole = holes[ h ];\n\t\t\t\t\toneHoleMovements = holesMovements[ h ];\n\n\t\t\t\t\tfor ( let i = 0, il = ahole.length; i < il; i ++ ) {\n\n\t\t\t\t\t\tconst vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );\n\n\t\t\t\t\t\tif ( ! extrudeByPath ) {\n\n\t\t\t\t\t\t\tv( vert.x, vert.y, depth + z );\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tv( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t/* Faces */\n\n\t\t\t// Top and bottom faces\n\n\t\t\tbuildLidFaces();\n\n\t\t\t// Sides faces\n\n\t\t\tbuildSideFaces();\n\n\n\t\t\t///// Internal functions\n\n\t\t\tfunction buildLidFaces() {\n\n\t\t\t\tconst start = verticesArray.length / 3;\n\n\t\t\t\tif ( bevelEnabled ) {\n\n\t\t\t\t\tlet layer = 0; // steps + 1\n\t\t\t\t\tlet offset = vlen * layer;\n\n\t\t\t\t\t// Bottom faces\n\n\t\t\t\t\tfor ( let i = 0; i < flen; i ++ ) {\n\n\t\t\t\t\t\tconst face = faces[ i ];\n\t\t\t\t\t\tf3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tlayer = steps + bevelSegments * 2;\n\t\t\t\t\toffset = vlen * layer;\n\n\t\t\t\t\t// Top faces\n\n\t\t\t\t\tfor ( let i = 0; i < flen; i ++ ) {\n\n\t\t\t\t\t\tconst face = faces[ i ];\n\t\t\t\t\t\tf3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// Bottom faces\n\n\t\t\t\t\tfor ( let i = 0; i < flen; i ++ ) {\n\n\t\t\t\t\t\tconst face = faces[ i ];\n\t\t\t\t\t\tf3( face[ 2 ], face[ 1 ], face[ 0 ] );\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// Top faces\n\n\t\t\t\t\tfor ( let i = 0; i < flen; i ++ ) {\n\n\t\t\t\t\t\tconst face = faces[ i ];\n\t\t\t\t\t\tf3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tscope.addGroup( start, verticesArray.length / 3 - start, 0 );\n\n\t\t\t}\n\n\t\t\t// Create faces for the z-sides of the shape\n\n\t\t\tfunction buildSideFaces() {\n\n\t\t\t\tconst start = verticesArray.length / 3;\n\t\t\t\tlet layeroffset = 0;\n\t\t\t\tsidewalls( contour, layeroffset );\n\t\t\t\tlayeroffset += contour.length;\n\n\t\t\t\tfor ( let h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\t\t\tconst ahole = holes[ h ];\n\t\t\t\t\tsidewalls( ahole, layeroffset );\n\n\t\t\t\t\t//, true\n\t\t\t\t\tlayeroffset += ahole.length;\n\n\t\t\t\t}\n\n\n\t\t\t\tscope.addGroup( start, verticesArray.length / 3 - start, 1 );\n\n\n\t\t\t}\n\n\t\t\tfunction sidewalls( contour, layeroffset ) {\n\n\t\t\t\tlet i = contour.length;\n\n\t\t\t\twhile ( -- i >= 0 ) {\n\n\t\t\t\t\tconst j = i;\n\t\t\t\t\tlet k = i - 1;\n\t\t\t\t\tif ( k < 0 ) k = contour.length - 1;\n\n\t\t\t\t\t//console.log('b', i,j, i-1, k,vertices.length);\n\n\t\t\t\t\tfor ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {\n\n\t\t\t\t\t\tconst slen1 = vlen * s;\n\t\t\t\t\t\tconst slen2 = vlen * ( s + 1 );\n\n\t\t\t\t\t\tconst a = layeroffset + j + slen1,\n\t\t\t\t\t\t\tb = layeroffset + k + slen1,\n\t\t\t\t\t\t\tc = layeroffset + k + slen2,\n\t\t\t\t\t\t\td = layeroffset + j + slen2;\n\n\t\t\t\t\t\tf4( a, b, c, d );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tfunction v( x, y, z ) {\n\n\t\t\t\tplaceholder.push( x );\n\t\t\t\tplaceholder.push( y );\n\t\t\t\tplaceholder.push( z );\n\n\t\t\t}\n\n\n\t\t\tfunction f3( a, b, c ) {\n\n\t\t\t\taddVertex( a );\n\t\t\t\taddVertex( b );\n\t\t\t\taddVertex( c );\n\n\t\t\t\tconst nextIndex = verticesArray.length / 3;\n\t\t\t\tconst uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );\n\n\t\t\t\taddUV( uvs[ 0 ] );\n\t\t\t\taddUV( uvs[ 1 ] );\n\t\t\t\taddUV( uvs[ 2 ] );\n\n\t\t\t}\n\n\t\t\tfunction f4( a, b, c, d ) {\n\n\t\t\t\taddVertex( a );\n\t\t\t\taddVertex( b );\n\t\t\t\taddVertex( d );\n\n\t\t\t\taddVertex( b );\n\t\t\t\taddVertex( c );\n\t\t\t\taddVertex( d );\n\n\n\t\t\t\tconst nextIndex = verticesArray.length / 3;\n\t\t\t\tconst uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );\n\n\t\t\t\taddUV( uvs[ 0 ] );\n\t\t\t\taddUV( uvs[ 1 ] );\n\t\t\t\taddUV( uvs[ 3 ] );\n\n\t\t\t\taddUV( uvs[ 1 ] );\n\t\t\t\taddUV( uvs[ 2 ] );\n\t\t\t\taddUV( uvs[ 3 ] );\n\n\t\t\t}\n\n\t\t\tfunction addVertex( index ) {\n\n\t\t\t\tverticesArray.push( placeholder[ index * 3 + 0 ] );\n\t\t\t\tverticesArray.push( placeholder[ index * 3 + 1 ] );\n\t\t\t\tverticesArray.push( placeholder[ index * 3 + 2 ] );\n\n\t\t\t}\n\n\n\t\t\tfunction addUV( vector2 ) {\n\n\t\t\t\tuvArray.push( vector2.x );\n\t\t\t\tuvArray.push( vector2.y );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tconst shapes = this.parameters.shapes;\n\t\tconst options = this.parameters.options;\n\n\t\treturn toJSON$1( shapes, options, data );\n\n\t}\n\n\tstatic fromJSON( data, shapes ) {\n\n\t\tconst geometryShapes = [];\n\n\t\tfor ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {\n\n\t\t\tconst shape = shapes[ data.shapes[ j ] ];\n\n\t\t\tgeometryShapes.push( shape );\n\n\t\t}\n\n\t\tconst extrudePath = data.options.extrudePath;\n\n\t\tif ( extrudePath !== undefined ) {\n\n\t\t\tdata.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );\n\n\t\t}\n\n\t\treturn new ExtrudeGeometry( geometryShapes, data.options );\n\n\t}\n\n}\n\nconst WorldUVGenerator = {\n\n\tgenerateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {\n\n\t\tconst a_x = vertices[ indexA * 3 ];\n\t\tconst a_y = vertices[ indexA * 3 + 1 ];\n\t\tconst b_x = vertices[ indexB * 3 ];\n\t\tconst b_y = vertices[ indexB * 3 + 1 ];\n\t\tconst c_x = vertices[ indexC * 3 ];\n\t\tconst c_y = vertices[ indexC * 3 + 1 ];\n\n\t\treturn [\n\t\t\tnew Vector2( a_x, a_y ),\n\t\t\tnew Vector2( b_x, b_y ),\n\t\t\tnew Vector2( c_x, c_y )\n\t\t];\n\n\t},\n\n\tgenerateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {\n\n\t\tconst a_x = vertices[ indexA * 3 ];\n\t\tconst a_y = vertices[ indexA * 3 + 1 ];\n\t\tconst a_z = vertices[ indexA * 3 + 2 ];\n\t\tconst b_x = vertices[ indexB * 3 ];\n\t\tconst b_y = vertices[ indexB * 3 + 1 ];\n\t\tconst b_z = vertices[ indexB * 3 + 2 ];\n\t\tconst c_x = vertices[ indexC * 3 ];\n\t\tconst c_y = vertices[ indexC * 3 + 1 ];\n\t\tconst c_z = vertices[ indexC * 3 + 2 ];\n\t\tconst d_x = vertices[ indexD * 3 ];\n\t\tconst d_y = vertices[ indexD * 3 + 1 ];\n\t\tconst d_z = vertices[ indexD * 3 + 2 ];\n\n\t\tif ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {\n\n\t\t\treturn [\n\t\t\t\tnew Vector2( a_x, 1 - a_z ),\n\t\t\t\tnew Vector2( b_x, 1 - b_z ),\n\t\t\t\tnew Vector2( c_x, 1 - c_z ),\n\t\t\t\tnew Vector2( d_x, 1 - d_z )\n\t\t\t];\n\n\t\t} else {\n\n\t\t\treturn [\n\t\t\t\tnew Vector2( a_y, 1 - a_z ),\n\t\t\t\tnew Vector2( b_y, 1 - b_z ),\n\t\t\t\tnew Vector2( c_y, 1 - c_z ),\n\t\t\t\tnew Vector2( d_y, 1 - d_z )\n\t\t\t];\n\n\t\t}\n\n\t}\n\n};\n\nfunction toJSON$1( shapes, options, data ) {\n\n\tdata.shapes = [];\n\n\tif ( Array.isArray( shapes ) ) {\n\n\t\tfor ( let i = 0, l = shapes.length; i < l; i ++ ) {\n\n\t\t\tconst shape = shapes[ i ];\n\n\t\t\tdata.shapes.push( shape.uuid );\n\n\t\t}\n\n\t} else {\n\n\t\tdata.shapes.push( shapes.uuid );\n\n\t}\n\n\tdata.options = Object.assign( {}, options );\n\n\tif ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();\n\n\treturn data;\n\n}\n\nclass IcosahedronGeometry extends PolyhedronGeometry {\n\n\tconstructor( radius = 1, detail = 0 ) {\n\n\t\tconst t = ( 1 + Math.sqrt( 5 ) ) / 2;\n\n\t\tconst vertices = [\n\t\t\t- 1, t, 0, \t1, t, 0, \t- 1, - t, 0, \t1, - t, 0,\n\t\t\t0, - 1, t, \t0, 1, t,\t0, - 1, - t, \t0, 1, - t,\n\t\t\tt, 0, - 1, \tt, 0, 1, \t- t, 0, - 1, \t- t, 0, 1\n\t\t];\n\n\t\tconst indices = [\n\t\t\t0, 11, 5, \t0, 5, 1, \t0, 1, 7, \t0, 7, 10, \t0, 10, 11,\n\t\t\t1, 5, 9, \t5, 11, 4,\t11, 10, 2,\t10, 7, 6,\t7, 1, 8,\n\t\t\t3, 9, 4, \t3, 4, 2,\t3, 2, 6,\t3, 6, 8,\t3, 8, 9,\n\t\t\t4, 9, 5, \t2, 4, 11,\t6, 2, 10,\t8, 6, 7,\t9, 8, 1\n\t\t];\n\n\t\tsuper( vertices, indices, radius, detail );\n\n\t\tthis.type = 'IcosahedronGeometry';\n\n\t\tthis.parameters = {\n\t\t\tradius: radius,\n\t\t\tdetail: detail\n\t\t};\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new IcosahedronGeometry( data.radius, data.detail );\n\n\t}\n\n}\n\nclass OctahedronGeometry extends PolyhedronGeometry {\n\n\tconstructor( radius = 1, detail = 0 ) {\n\n\t\tconst vertices = [\n\t\t\t1, 0, 0, \t- 1, 0, 0,\t0, 1, 0,\n\t\t\t0, - 1, 0, \t0, 0, 1,\t0, 0, - 1\n\t\t];\n\n\t\tconst indices = [\n\t\t\t0, 2, 4,\t0, 4, 3,\t0, 3, 5,\n\t\t\t0, 5, 2,\t1, 2, 5,\t1, 5, 3,\n\t\t\t1, 3, 4,\t1, 4, 2\n\t\t];\n\n\t\tsuper( vertices, indices, radius, detail );\n\n\t\tthis.type = 'OctahedronGeometry';\n\n\t\tthis.parameters = {\n\t\t\tradius: radius,\n\t\t\tdetail: detail\n\t\t};\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new OctahedronGeometry( data.radius, data.detail );\n\n\t}\n\n}\n\nclass RingGeometry extends BufferGeometry {\n\n\tconstructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'RingGeometry';\n\n\t\tthis.parameters = {\n\t\t\tinnerRadius: innerRadius,\n\t\t\touterRadius: outerRadius,\n\t\t\tthetaSegments: thetaSegments,\n\t\t\tphiSegments: phiSegments,\n\t\t\tthetaStart: thetaStart,\n\t\t\tthetaLength: thetaLength\n\t\t};\n\n\t\tthetaSegments = Math.max( 3, thetaSegments );\n\t\tphiSegments = Math.max( 1, phiSegments );\n\n\t\t// buffers\n\n\t\tconst indices = [];\n\t\tconst vertices = [];\n\t\tconst normals = [];\n\t\tconst uvs = [];\n\n\t\t// some helper variables\n\n\t\tlet radius = innerRadius;\n\t\tconst radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );\n\t\tconst vertex = new Vector3();\n\t\tconst uv = new Vector2();\n\n\t\t// generate vertices, normals and uvs\n\n\t\tfor ( let j = 0; j <= phiSegments; j ++ ) {\n\n\t\t\tfor ( let i = 0; i <= thetaSegments; i ++ ) {\n\n\t\t\t\t// values are generate from the inside of the ring to the outside\n\n\t\t\t\tconst segment = thetaStart + i / thetaSegments * thetaLength;\n\n\t\t\t\t// vertex\n\n\t\t\t\tvertex.x = radius * Math.cos( segment );\n\t\t\t\tvertex.y = radius * Math.sin( segment );\n\n\t\t\t\tvertices.push( vertex.x, vertex.y, vertex.z );\n\n\t\t\t\t// normal\n\n\t\t\t\tnormals.push( 0, 0, 1 );\n\n\t\t\t\t// uv\n\n\t\t\t\tuv.x = ( vertex.x / outerRadius + 1 ) / 2;\n\t\t\t\tuv.y = ( vertex.y / outerRadius + 1 ) / 2;\n\n\t\t\t\tuvs.push( uv.x, uv.y );\n\n\t\t\t}\n\n\t\t\t// increase the radius for next row of vertices\n\n\t\t\tradius += radiusStep;\n\n\t\t}\n\n\t\t// indices\n\n\t\tfor ( let j = 0; j < phiSegments; j ++ ) {\n\n\t\t\tconst thetaSegmentLevel = j * ( thetaSegments + 1 );\n\n\t\t\tfor ( let i = 0; i < thetaSegments; i ++ ) {\n\n\t\t\t\tconst segment = i + thetaSegmentLevel;\n\n\t\t\t\tconst a = segment;\n\t\t\t\tconst b = segment + thetaSegments + 1;\n\t\t\t\tconst c = segment + thetaSegments + 2;\n\t\t\t\tconst d = segment + 1;\n\n\t\t\t\t// faces\n\n\t\t\t\tindices.push( a, b, d );\n\t\t\t\tindices.push( b, c, d );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// build geometry\n\n\t\tthis.setIndex( indices );\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tthis.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );\n\n\t}\n\n}\n\nclass ShapeGeometry extends BufferGeometry {\n\n\tconstructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'ShapeGeometry';\n\n\t\tthis.parameters = {\n\t\t\tshapes: shapes,\n\t\t\tcurveSegments: curveSegments\n\t\t};\n\n\t\t// buffers\n\n\t\tconst indices = [];\n\t\tconst vertices = [];\n\t\tconst normals = [];\n\t\tconst uvs = [];\n\n\t\t// helper variables\n\n\t\tlet groupStart = 0;\n\t\tlet groupCount = 0;\n\n\t\t// allow single and array values for \"shapes\" parameter\n\n\t\tif ( Array.isArray( shapes ) === false ) {\n\n\t\t\taddShape( shapes );\n\n\t\t} else {\n\n\t\t\tfor ( let i = 0; i < shapes.length; i ++ ) {\n\n\t\t\t\taddShape( shapes[ i ] );\n\n\t\t\t\tthis.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support\n\n\t\t\t\tgroupStart += groupCount;\n\t\t\t\tgroupCount = 0;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// build geometry\n\n\t\tthis.setIndex( indices );\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tthis.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );\n\n\n\t\t// helper functions\n\n\t\tfunction addShape( shape ) {\n\n\t\t\tconst indexOffset = vertices.length / 3;\n\t\t\tconst points = shape.extractPoints( curveSegments );\n\n\t\t\tlet shapeVertices = points.shape;\n\t\t\tconst shapeHoles = points.holes;\n\n\t\t\t// check direction of vertices\n\n\t\t\tif ( ShapeUtils.isClockWise( shapeVertices ) === false ) {\n\n\t\t\t\tshapeVertices = shapeVertices.reverse();\n\n\t\t\t}\n\n\t\t\tfor ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {\n\n\t\t\t\tconst shapeHole = shapeHoles[ i ];\n\n\t\t\t\tif ( ShapeUtils.isClockWise( shapeHole ) === true ) {\n\n\t\t\t\t\tshapeHoles[ i ] = shapeHole.reverse();\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tconst faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );\n\n\t\t\t// join vertices of inner and outer paths to a single array\n\n\t\t\tfor ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {\n\n\t\t\t\tconst shapeHole = shapeHoles[ i ];\n\t\t\t\tshapeVertices = shapeVertices.concat( shapeHole );\n\n\t\t\t}\n\n\t\t\t// vertices, normals, uvs\n\n\t\t\tfor ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {\n\n\t\t\t\tconst vertex = shapeVertices[ i ];\n\n\t\t\t\tvertices.push( vertex.x, vertex.y, 0 );\n\t\t\t\tnormals.push( 0, 0, 1 );\n\t\t\t\tuvs.push( vertex.x, vertex.y ); // world uvs\n\n\t\t\t}\n\n\t\t\t// indices\n\n\t\t\tfor ( let i = 0, l = faces.length; i < l; i ++ ) {\n\n\t\t\t\tconst face = faces[ i ];\n\n\t\t\t\tconst a = face[ 0 ] + indexOffset;\n\t\t\t\tconst b = face[ 1 ] + indexOffset;\n\t\t\t\tconst c = face[ 2 ] + indexOffset;\n\n\t\t\t\tindices.push( a, b, c );\n\t\t\t\tgroupCount += 3;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tconst shapes = this.parameters.shapes;\n\n\t\treturn toJSON( shapes, data );\n\n\t}\n\n\tstatic fromJSON( data, shapes ) {\n\n\t\tconst geometryShapes = [];\n\n\t\tfor ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {\n\n\t\t\tconst shape = shapes[ data.shapes[ j ] ];\n\n\t\t\tgeometryShapes.push( shape );\n\n\t\t}\n\n\t\treturn new ShapeGeometry( geometryShapes, data.curveSegments );\n\n\t}\n\n}\n\nfunction toJSON( shapes, data ) {\n\n\tdata.shapes = [];\n\n\tif ( Array.isArray( shapes ) ) {\n\n\t\tfor ( let i = 0, l = shapes.length; i < l; i ++ ) {\n\n\t\t\tconst shape = shapes[ i ];\n\n\t\t\tdata.shapes.push( shape.uuid );\n\n\t\t}\n\n\t} else {\n\n\t\tdata.shapes.push( shapes.uuid );\n\n\t}\n\n\treturn data;\n\n}\n\nclass SphereGeometry extends BufferGeometry {\n\n\tconstructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'SphereGeometry';\n\n\t\tthis.parameters = {\n\t\t\tradius: radius,\n\t\t\twidthSegments: widthSegments,\n\t\t\theightSegments: heightSegments,\n\t\t\tphiStart: phiStart,\n\t\t\tphiLength: phiLength,\n\t\t\tthetaStart: thetaStart,\n\t\t\tthetaLength: thetaLength\n\t\t};\n\n\t\twidthSegments = Math.max( 3, Math.floor( widthSegments ) );\n\t\theightSegments = Math.max( 2, Math.floor( heightSegments ) );\n\n\t\tconst thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );\n\n\t\tlet index = 0;\n\t\tconst grid = [];\n\n\t\tconst vertex = new Vector3();\n\t\tconst normal = new Vector3();\n\n\t\t// buffers\n\n\t\tconst indices = [];\n\t\tconst vertices = [];\n\t\tconst normals = [];\n\t\tconst uvs = [];\n\n\t\t// generate vertices, normals and uvs\n\n\t\tfor ( let iy = 0; iy <= heightSegments; iy ++ ) {\n\n\t\t\tconst verticesRow = [];\n\n\t\t\tconst v = iy / heightSegments;\n\n\t\t\t// special case for the poles\n\n\t\t\tlet uOffset = 0;\n\n\t\t\tif ( iy === 0 && thetaStart === 0 ) {\n\n\t\t\t\tuOffset = 0.5 / widthSegments;\n\n\t\t\t} else if ( iy === heightSegments && thetaEnd === Math.PI ) {\n\n\t\t\t\tuOffset = - 0.5 / widthSegments;\n\n\t\t\t}\n\n\t\t\tfor ( let ix = 0; ix <= widthSegments; ix ++ ) {\n\n\t\t\t\tconst u = ix / widthSegments;\n\n\t\t\t\t// vertex\n\n\t\t\t\tvertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );\n\t\t\t\tvertex.y = radius * Math.cos( thetaStart + v * thetaLength );\n\t\t\t\tvertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );\n\n\t\t\t\tvertices.push( vertex.x, vertex.y, vertex.z );\n\n\t\t\t\t// normal\n\n\t\t\t\tnormal.copy( vertex ).normalize();\n\t\t\t\tnormals.push( normal.x, normal.y, normal.z );\n\n\t\t\t\t// uv\n\n\t\t\t\tuvs.push( u + uOffset, 1 - v );\n\n\t\t\t\tverticesRow.push( index ++ );\n\n\t\t\t}\n\n\t\t\tgrid.push( verticesRow );\n\n\t\t}\n\n\t\t// indices\n\n\t\tfor ( let iy = 0; iy < heightSegments; iy ++ ) {\n\n\t\t\tfor ( let ix = 0; ix < widthSegments; ix ++ ) {\n\n\t\t\t\tconst a = grid[ iy ][ ix + 1 ];\n\t\t\t\tconst b = grid[ iy ][ ix ];\n\t\t\t\tconst c = grid[ iy + 1 ][ ix ];\n\t\t\t\tconst d = grid[ iy + 1 ][ ix + 1 ];\n\n\t\t\t\tif ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );\n\t\t\t\tif ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// build geometry\n\n\t\tthis.setIndex( indices );\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tthis.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );\n\n\t}\n\n}\n\nclass TetrahedronGeometry extends PolyhedronGeometry {\n\n\tconstructor( radius = 1, detail = 0 ) {\n\n\t\tconst vertices = [\n\t\t\t1, 1, 1, \t- 1, - 1, 1, \t- 1, 1, - 1, \t1, - 1, - 1\n\t\t];\n\n\t\tconst indices = [\n\t\t\t2, 1, 0, \t0, 3, 2,\t1, 3, 0,\t2, 3, 1\n\t\t];\n\n\t\tsuper( vertices, indices, radius, detail );\n\n\t\tthis.type = 'TetrahedronGeometry';\n\n\t\tthis.parameters = {\n\t\t\tradius: radius,\n\t\t\tdetail: detail\n\t\t};\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new TetrahedronGeometry( data.radius, data.detail );\n\n\t}\n\n}\n\nclass TorusGeometry extends BufferGeometry {\n\n\tconstructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'TorusGeometry';\n\n\t\tthis.parameters = {\n\t\t\tradius: radius,\n\t\t\ttube: tube,\n\t\t\tradialSegments: radialSegments,\n\t\t\ttubularSegments: tubularSegments,\n\t\t\tarc: arc\n\t\t};\n\n\t\tradialSegments = Math.floor( radialSegments );\n\t\ttubularSegments = Math.floor( tubularSegments );\n\n\t\t// buffers\n\n\t\tconst indices = [];\n\t\tconst vertices = [];\n\t\tconst normals = [];\n\t\tconst uvs = [];\n\n\t\t// helper variables\n\n\t\tconst center = new Vector3();\n\t\tconst vertex = new Vector3();\n\t\tconst normal = new Vector3();\n\n\t\t// generate vertices, normals and uvs\n\n\t\tfor ( let j = 0; j <= radialSegments; j ++ ) {\n\n\t\t\tfor ( let i = 0; i <= tubularSegments; i ++ ) {\n\n\t\t\t\tconst u = i / tubularSegments * arc;\n\t\t\t\tconst v = j / radialSegments * Math.PI * 2;\n\n\t\t\t\t// vertex\n\n\t\t\t\tvertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );\n\t\t\t\tvertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );\n\t\t\t\tvertex.z = tube * Math.sin( v );\n\n\t\t\t\tvertices.push( vertex.x, vertex.y, vertex.z );\n\n\t\t\t\t// normal\n\n\t\t\t\tcenter.x = radius * Math.cos( u );\n\t\t\t\tcenter.y = radius * Math.sin( u );\n\t\t\t\tnormal.subVectors( vertex, center ).normalize();\n\n\t\t\t\tnormals.push( normal.x, normal.y, normal.z );\n\n\t\t\t\t// uv\n\n\t\t\t\tuvs.push( i / tubularSegments );\n\t\t\t\tuvs.push( j / radialSegments );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// generate indices\n\n\t\tfor ( let j = 1; j <= radialSegments; j ++ ) {\n\n\t\t\tfor ( let i = 1; i <= tubularSegments; i ++ ) {\n\n\t\t\t\t// indices\n\n\t\t\t\tconst a = ( tubularSegments + 1 ) * j + i - 1;\n\t\t\t\tconst b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;\n\t\t\t\tconst c = ( tubularSegments + 1 ) * ( j - 1 ) + i;\n\t\t\t\tconst d = ( tubularSegments + 1 ) * j + i;\n\n\t\t\t\t// faces\n\n\t\t\t\tindices.push( a, b, d );\n\t\t\t\tindices.push( b, c, d );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// build geometry\n\n\t\tthis.setIndex( indices );\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tthis.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );\n\n\t}\n\n}\n\nclass TorusKnotGeometry extends BufferGeometry {\n\n\tconstructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'TorusKnotGeometry';\n\n\t\tthis.parameters = {\n\t\t\tradius: radius,\n\t\t\ttube: tube,\n\t\t\ttubularSegments: tubularSegments,\n\t\t\tradialSegments: radialSegments,\n\t\t\tp: p,\n\t\t\tq: q\n\t\t};\n\n\t\ttubularSegments = Math.floor( tubularSegments );\n\t\tradialSegments = Math.floor( radialSegments );\n\n\t\t// buffers\n\n\t\tconst indices = [];\n\t\tconst vertices = [];\n\t\tconst normals = [];\n\t\tconst uvs = [];\n\n\t\t// helper variables\n\n\t\tconst vertex = new Vector3();\n\t\tconst normal = new Vector3();\n\n\t\tconst P1 = new Vector3();\n\t\tconst P2 = new Vector3();\n\n\t\tconst B = new Vector3();\n\t\tconst T = new Vector3();\n\t\tconst N = new Vector3();\n\n\t\t// generate vertices, normals and uvs\n\n\t\tfor ( let i = 0; i <= tubularSegments; ++ i ) {\n\n\t\t\t// the radian \"u\" is used to calculate the position on the torus curve of the current tubular segment\n\n\t\t\tconst u = i / tubularSegments * p * Math.PI * 2;\n\n\t\t\t// now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.\n\t\t\t// these points are used to create a special \"coordinate space\", which is necessary to calculate the correct vertex positions\n\n\t\t\tcalculatePositionOnCurve( u, p, q, radius, P1 );\n\t\t\tcalculatePositionOnCurve( u + 0.01, p, q, radius, P2 );\n\n\t\t\t// calculate orthonormal basis\n\n\t\t\tT.subVectors( P2, P1 );\n\t\t\tN.addVectors( P2, P1 );\n\t\t\tB.crossVectors( T, N );\n\t\t\tN.crossVectors( B, T );\n\n\t\t\t// normalize B, N. T can be ignored, we don't use it\n\n\t\t\tB.normalize();\n\t\t\tN.normalize();\n\n\t\t\tfor ( let j = 0; j <= radialSegments; ++ j ) {\n\n\t\t\t\t// now calculate the vertices. they are nothing more than an extrusion of the torus curve.\n\t\t\t\t// because we extrude a shape in the xy-plane, there is no need to calculate a z-value.\n\n\t\t\t\tconst v = j / radialSegments * Math.PI * 2;\n\t\t\t\tconst cx = - tube * Math.cos( v );\n\t\t\t\tconst cy = tube * Math.sin( v );\n\n\t\t\t\t// now calculate the final vertex position.\n\t\t\t\t// first we orient the extrusion with our basis vectors, then we add it to the current position on the curve\n\n\t\t\t\tvertex.x = P1.x + ( cx * N.x + cy * B.x );\n\t\t\t\tvertex.y = P1.y + ( cx * N.y + cy * B.y );\n\t\t\t\tvertex.z = P1.z + ( cx * N.z + cy * B.z );\n\n\t\t\t\tvertices.push( vertex.x, vertex.y, vertex.z );\n\n\t\t\t\t// normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)\n\n\t\t\t\tnormal.subVectors( vertex, P1 ).normalize();\n\n\t\t\t\tnormals.push( normal.x, normal.y, normal.z );\n\n\t\t\t\t// uv\n\n\t\t\t\tuvs.push( i / tubularSegments );\n\t\t\t\tuvs.push( j / radialSegments );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// generate indices\n\n\t\tfor ( let j = 1; j <= tubularSegments; j ++ ) {\n\n\t\t\tfor ( let i = 1; i <= radialSegments; i ++ ) {\n\n\t\t\t\t// indices\n\n\t\t\t\tconst a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );\n\t\t\t\tconst b = ( radialSegments + 1 ) * j + ( i - 1 );\n\t\t\t\tconst c = ( radialSegments + 1 ) * j + i;\n\t\t\t\tconst d = ( radialSegments + 1 ) * ( j - 1 ) + i;\n\n\t\t\t\t// faces\n\n\t\t\t\tindices.push( a, b, d );\n\t\t\t\tindices.push( b, c, d );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// build geometry\n\n\t\tthis.setIndex( indices );\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tthis.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );\n\n\t\t// this function calculates the current position on the torus curve\n\n\t\tfunction calculatePositionOnCurve( u, p, q, radius, position ) {\n\n\t\t\tconst cu = Math.cos( u );\n\t\t\tconst su = Math.sin( u );\n\t\t\tconst quOverP = q / p * u;\n\t\t\tconst cs = Math.cos( quOverP );\n\n\t\t\tposition.x = radius * ( 2 + cs ) * 0.5 * cu;\n\t\t\tposition.y = radius * ( 2 + cs ) * su * 0.5;\n\t\t\tposition.z = radius * Math.sin( quOverP ) * 0.5;\n\n\t\t}\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\treturn new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );\n\n\t}\n\n}\n\nclass TubeGeometry extends BufferGeometry {\n\n\tconstructor( path = new QuadraticBezierCurve3( new Vector3( - 1, - 1, 0 ), new Vector3( - 1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'TubeGeometry';\n\n\t\tthis.parameters = {\n\t\t\tpath: path,\n\t\t\ttubularSegments: tubularSegments,\n\t\t\tradius: radius,\n\t\t\tradialSegments: radialSegments,\n\t\t\tclosed: closed\n\t\t};\n\n\t\tconst frames = path.computeFrenetFrames( tubularSegments, closed );\n\n\t\t// expose internals\n\n\t\tthis.tangents = frames.tangents;\n\t\tthis.normals = frames.normals;\n\t\tthis.binormals = frames.binormals;\n\n\t\t// helper variables\n\n\t\tconst vertex = new Vector3();\n\t\tconst normal = new Vector3();\n\t\tconst uv = new Vector2();\n\t\tlet P = new Vector3();\n\n\t\t// buffer\n\n\t\tconst vertices = [];\n\t\tconst normals = [];\n\t\tconst uvs = [];\n\t\tconst indices = [];\n\n\t\t// create buffer data\n\n\t\tgenerateBufferData();\n\n\t\t// build geometry\n\n\t\tthis.setIndex( indices );\n\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tthis.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );\n\t\tthis.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );\n\n\t\t// functions\n\n\t\tfunction generateBufferData() {\n\n\t\t\tfor ( let i = 0; i < tubularSegments; i ++ ) {\n\n\t\t\t\tgenerateSegment( i );\n\n\t\t\t}\n\n\t\t\t// if the geometry is not closed, generate the last row of vertices and normals\n\t\t\t// at the regular position on the given path\n\t\t\t//\n\t\t\t// if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)\n\n\t\t\tgenerateSegment( ( closed === false ) ? tubularSegments : 0 );\n\n\t\t\t// uvs are generated in a separate function.\n\t\t\t// this makes it easy compute correct values for closed geometries\n\n\t\t\tgenerateUVs();\n\n\t\t\t// finally create faces\n\n\t\t\tgenerateIndices();\n\n\t\t}\n\n\t\tfunction generateSegment( i ) {\n\n\t\t\t// we use getPointAt to sample evenly distributed points from the given path\n\n\t\t\tP = path.getPointAt( i / tubularSegments, P );\n\n\t\t\t// retrieve corresponding normal and binormal\n\n\t\t\tconst N = frames.normals[ i ];\n\t\t\tconst B = frames.binormals[ i ];\n\n\t\t\t// generate normals and vertices for the current segment\n\n\t\t\tfor ( let j = 0; j <= radialSegments; j ++ ) {\n\n\t\t\t\tconst v = j / radialSegments * Math.PI * 2;\n\n\t\t\t\tconst sin = Math.sin( v );\n\t\t\t\tconst cos = - Math.cos( v );\n\n\t\t\t\t// normal\n\n\t\t\t\tnormal.x = ( cos * N.x + sin * B.x );\n\t\t\t\tnormal.y = ( cos * N.y + sin * B.y );\n\t\t\t\tnormal.z = ( cos * N.z + sin * B.z );\n\t\t\t\tnormal.normalize();\n\n\t\t\t\tnormals.push( normal.x, normal.y, normal.z );\n\n\t\t\t\t// vertex\n\n\t\t\t\tvertex.x = P.x + radius * normal.x;\n\t\t\t\tvertex.y = P.y + radius * normal.y;\n\t\t\t\tvertex.z = P.z + radius * normal.z;\n\n\t\t\t\tvertices.push( vertex.x, vertex.y, vertex.z );\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction generateIndices() {\n\n\t\t\tfor ( let j = 1; j <= tubularSegments; j ++ ) {\n\n\t\t\t\tfor ( let i = 1; i <= radialSegments; i ++ ) {\n\n\t\t\t\t\tconst a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );\n\t\t\t\t\tconst b = ( radialSegments + 1 ) * j + ( i - 1 );\n\t\t\t\t\tconst c = ( radialSegments + 1 ) * j + i;\n\t\t\t\t\tconst d = ( radialSegments + 1 ) * ( j - 1 ) + i;\n\n\t\t\t\t\t// faces\n\n\t\t\t\t\tindices.push( a, b, d );\n\t\t\t\t\tindices.push( b, c, d );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction generateUVs() {\n\n\t\t\tfor ( let i = 0; i <= tubularSegments; i ++ ) {\n\n\t\t\t\tfor ( let j = 0; j <= radialSegments; j ++ ) {\n\n\t\t\t\t\tuv.x = i / tubularSegments;\n\t\t\t\t\tuv.y = j / radialSegments;\n\n\t\t\t\t\tuvs.push( uv.x, uv.y );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.path = this.parameters.path.toJSON();\n\n\t\treturn data;\n\n\t}\n\n\tstatic fromJSON( data ) {\n\n\t\t// This only works for built-in curves (e.g. CatmullRomCurve3).\n\t\t// User defined curves or instances of CurvePath will not be deserialized.\n\t\treturn new TubeGeometry(\n\t\t\tnew Curves[ data.path.type ]().fromJSON( data.path ),\n\t\t\tdata.tubularSegments,\n\t\t\tdata.radius,\n\t\t\tdata.radialSegments,\n\t\t\tdata.closed\n\t\t);\n\n\t}\n\n}\n\nclass WireframeGeometry extends BufferGeometry {\n\n\tconstructor( geometry = null ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'WireframeGeometry';\n\n\t\tthis.parameters = {\n\t\t\tgeometry: geometry\n\t\t};\n\n\t\tif ( geometry !== null ) {\n\n\t\t\t// buffer\n\n\t\t\tconst vertices = [];\n\t\t\tconst edges = new Set();\n\n\t\t\t// helper variables\n\n\t\t\tconst start = new Vector3();\n\t\t\tconst end = new Vector3();\n\n\t\t\tif ( geometry.index !== null ) {\n\n\t\t\t\t// indexed BufferGeometry\n\n\t\t\t\tconst position = geometry.attributes.position;\n\t\t\t\tconst indices = geometry.index;\n\t\t\t\tlet groups = geometry.groups;\n\n\t\t\t\tif ( groups.length === 0 ) {\n\n\t\t\t\t\tgroups = [ { start: 0, count: indices.count, materialIndex: 0 } ];\n\n\t\t\t\t}\n\n\t\t\t\t// create a data structure that contains all edges without duplicates\n\n\t\t\t\tfor ( let o = 0, ol = groups.length; o < ol; ++ o ) {\n\n\t\t\t\t\tconst group = groups[ o ];\n\n\t\t\t\t\tconst groupStart = group.start;\n\t\t\t\t\tconst groupCount = group.count;\n\n\t\t\t\t\tfor ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {\n\n\t\t\t\t\t\tfor ( let j = 0; j < 3; j ++ ) {\n\n\t\t\t\t\t\t\tconst index1 = indices.getX( i + j );\n\t\t\t\t\t\t\tconst index2 = indices.getX( i + ( j + 1 ) % 3 );\n\n\t\t\t\t\t\t\tstart.fromBufferAttribute( position, index1 );\n\t\t\t\t\t\t\tend.fromBufferAttribute( position, index2 );\n\n\t\t\t\t\t\t\tif ( isUniqueEdge( start, end, edges ) === true ) {\n\n\t\t\t\t\t\t\t\tvertices.push( start.x, start.y, start.z );\n\t\t\t\t\t\t\t\tvertices.push( end.x, end.y, end.z );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\t// non-indexed BufferGeometry\n\n\t\t\t\tconst position = geometry.attributes.position;\n\n\t\t\t\tfor ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {\n\n\t\t\t\t\tfor ( let j = 0; j < 3; j ++ ) {\n\n\t\t\t\t\t\t// three edges per triangle, an edge is represented as (index1, index2)\n\t\t\t\t\t\t// e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)\n\n\t\t\t\t\t\tconst index1 = 3 * i + j;\n\t\t\t\t\t\tconst index2 = 3 * i + ( ( j + 1 ) % 3 );\n\n\t\t\t\t\t\tstart.fromBufferAttribute( position, index1 );\n\t\t\t\t\t\tend.fromBufferAttribute( position, index2 );\n\n\t\t\t\t\t\tif ( isUniqueEdge( start, end, edges ) === true ) {\n\n\t\t\t\t\t\t\tvertices.push( start.x, start.y, start.z );\n\t\t\t\t\t\t\tvertices.push( end.x, end.y, end.z );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// build geometry\n\n\t\t\tthis.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\n\t\t}\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.parameters = Object.assign( {}, source.parameters );\n\n\t\treturn this;\n\n\t}\n\n}\n\nfunction isUniqueEdge( start, end, edges ) {\n\n\tconst hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;\n\tconst hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge\n\n\tif ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {\n\n\t\treturn false;\n\n\t} else {\n\n\t\tedges.add( hash1 );\n\t\tedges.add( hash2 );\n\t\treturn true;\n\n\t}\n\n}\n\nvar Geometries = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tBoxGeometry: BoxGeometry,\n\tCapsuleGeometry: CapsuleGeometry,\n\tCircleGeometry: CircleGeometry,\n\tConeGeometry: ConeGeometry,\n\tCylinderGeometry: CylinderGeometry,\n\tDodecahedronGeometry: DodecahedronGeometry,\n\tEdgesGeometry: EdgesGeometry,\n\tExtrudeGeometry: ExtrudeGeometry,\n\tIcosahedronGeometry: IcosahedronGeometry,\n\tLatheGeometry: LatheGeometry,\n\tOctahedronGeometry: OctahedronGeometry,\n\tPlaneGeometry: PlaneGeometry,\n\tPolyhedronGeometry: PolyhedronGeometry,\n\tRingGeometry: RingGeometry,\n\tShapeGeometry: ShapeGeometry,\n\tSphereGeometry: SphereGeometry,\n\tTetrahedronGeometry: TetrahedronGeometry,\n\tTorusGeometry: TorusGeometry,\n\tTorusKnotGeometry: TorusKnotGeometry,\n\tTubeGeometry: TubeGeometry,\n\tWireframeGeometry: WireframeGeometry\n});\n\nclass ShadowMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isShadowMaterial = true;\n\n\t\tthis.type = 'ShadowMaterial';\n\n\t\tthis.color = new Color( 0x000000 );\n\t\tthis.transparent = true;\n\n\t\tthis.fog = true;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.color.copy( source.color );\n\n\t\tthis.fog = source.fog;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass RawShaderMaterial extends ShaderMaterial {\n\n\tconstructor( parameters ) {\n\n\t\tsuper( parameters );\n\n\t\tthis.isRawShaderMaterial = true;\n\n\t\tthis.type = 'RawShaderMaterial';\n\n\t}\n\n}\n\nclass MeshStandardMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isMeshStandardMaterial = true;\n\n\t\tthis.defines = { 'STANDARD': '' };\n\n\t\tthis.type = 'MeshStandardMaterial';\n\n\t\tthis.color = new Color( 0xffffff ); // diffuse\n\t\tthis.roughness = 1.0;\n\t\tthis.metalness = 0.0;\n\n\t\tthis.map = null;\n\n\t\tthis.lightMap = null;\n\t\tthis.lightMapIntensity = 1.0;\n\n\t\tthis.aoMap = null;\n\t\tthis.aoMapIntensity = 1.0;\n\n\t\tthis.emissive = new Color( 0x000000 );\n\t\tthis.emissiveIntensity = 1.0;\n\t\tthis.emissiveMap = null;\n\n\t\tthis.bumpMap = null;\n\t\tthis.bumpScale = 1;\n\n\t\tthis.normalMap = null;\n\t\tthis.normalMapType = TangentSpaceNormalMap;\n\t\tthis.normalScale = new Vector2( 1, 1 );\n\n\t\tthis.displacementMap = null;\n\t\tthis.displacementScale = 1;\n\t\tthis.displacementBias = 0;\n\n\t\tthis.roughnessMap = null;\n\n\t\tthis.metalnessMap = null;\n\n\t\tthis.alphaMap = null;\n\n\t\tthis.envMap = null;\n\t\tthis.envMapIntensity = 1.0;\n\n\t\tthis.wireframe = false;\n\t\tthis.wireframeLinewidth = 1;\n\t\tthis.wireframeLinecap = 'round';\n\t\tthis.wireframeLinejoin = 'round';\n\n\t\tthis.flatShading = false;\n\n\t\tthis.fog = true;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.defines = { 'STANDARD': '' };\n\n\t\tthis.color.copy( source.color );\n\t\tthis.roughness = source.roughness;\n\t\tthis.metalness = source.metalness;\n\n\t\tthis.map = source.map;\n\n\t\tthis.lightMap = source.lightMap;\n\t\tthis.lightMapIntensity = source.lightMapIntensity;\n\n\t\tthis.aoMap = source.aoMap;\n\t\tthis.aoMapIntensity = source.aoMapIntensity;\n\n\t\tthis.emissive.copy( source.emissive );\n\t\tthis.emissiveMap = source.emissiveMap;\n\t\tthis.emissiveIntensity = source.emissiveIntensity;\n\n\t\tthis.bumpMap = source.bumpMap;\n\t\tthis.bumpScale = source.bumpScale;\n\n\t\tthis.normalMap = source.normalMap;\n\t\tthis.normalMapType = source.normalMapType;\n\t\tthis.normalScale.copy( source.normalScale );\n\n\t\tthis.displacementMap = source.displacementMap;\n\t\tthis.displacementScale = source.displacementScale;\n\t\tthis.displacementBias = source.displacementBias;\n\n\t\tthis.roughnessMap = source.roughnessMap;\n\n\t\tthis.metalnessMap = source.metalnessMap;\n\n\t\tthis.alphaMap = source.alphaMap;\n\n\t\tthis.envMap = source.envMap;\n\t\tthis.envMapIntensity = source.envMapIntensity;\n\n\t\tthis.wireframe = source.wireframe;\n\t\tthis.wireframeLinewidth = source.wireframeLinewidth;\n\t\tthis.wireframeLinecap = source.wireframeLinecap;\n\t\tthis.wireframeLinejoin = source.wireframeLinejoin;\n\n\t\tthis.flatShading = source.flatShading;\n\n\t\tthis.fog = source.fog;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass MeshPhysicalMaterial extends MeshStandardMaterial {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isMeshPhysicalMaterial = true;\n\n\t\tthis.defines = {\n\n\t\t\t'STANDARD': '',\n\t\t\t'PHYSICAL': ''\n\n\t\t};\n\n\t\tthis.type = 'MeshPhysicalMaterial';\n\n\t\tthis.clearcoatMap = null;\n\t\tthis.clearcoatRoughness = 0.0;\n\t\tthis.clearcoatRoughnessMap = null;\n\t\tthis.clearcoatNormalScale = new Vector2( 1, 1 );\n\t\tthis.clearcoatNormalMap = null;\n\n\t\tthis.ior = 1.5;\n\n\t\tObject.defineProperty( this, 'reflectivity', {\n\t\t\tget: function () {\n\n\t\t\t\treturn ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );\n\n\t\t\t},\n\t\t\tset: function ( reflectivity ) {\n\n\t\t\t\tthis.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );\n\n\t\t\t}\n\t\t} );\n\n\t\tthis.iridescenceMap = null;\n\t\tthis.iridescenceIOR = 1.3;\n\t\tthis.iridescenceThicknessRange = [ 100, 400 ];\n\t\tthis.iridescenceThicknessMap = null;\n\n\t\tthis.sheenColor = new Color( 0x000000 );\n\t\tthis.sheenColorMap = null;\n\t\tthis.sheenRoughness = 1.0;\n\t\tthis.sheenRoughnessMap = null;\n\n\t\tthis.transmissionMap = null;\n\n\t\tthis.thickness = 0;\n\t\tthis.thicknessMap = null;\n\t\tthis.attenuationDistance = Infinity;\n\t\tthis.attenuationColor = new Color( 1, 1, 1 );\n\n\t\tthis.specularIntensity = 1.0;\n\t\tthis.specularIntensityMap = null;\n\t\tthis.specularColor = new Color( 1, 1, 1 );\n\t\tthis.specularColorMap = null;\n\n\t\tthis._sheen = 0.0;\n\t\tthis._clearcoat = 0;\n\t\tthis._iridescence = 0;\n\t\tthis._transmission = 0;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tget sheen() {\n\n\t\treturn this._sheen;\n\n\t}\n\n\tset sheen( value ) {\n\n\t\tif ( this._sheen > 0 !== value > 0 ) {\n\n\t\t\tthis.version ++;\n\n\t\t}\n\n\t\tthis._sheen = value;\n\n\t}\n\n\tget clearcoat() {\n\n\t\treturn this._clearcoat;\n\n\t}\n\n\tset clearcoat( value ) {\n\n\t\tif ( this._clearcoat > 0 !== value > 0 ) {\n\n\t\t\tthis.version ++;\n\n\t\t}\n\n\t\tthis._clearcoat = value;\n\n\t}\n\n\tget iridescence() {\n\n\t\treturn this._iridescence;\n\n\t}\n\n\tset iridescence( value ) {\n\n\t\tif ( this._iridescence > 0 !== value > 0 ) {\n\n\t\t\tthis.version ++;\n\n\t\t}\n\n\t\tthis._iridescence = value;\n\n\t}\n\n\tget transmission() {\n\n\t\treturn this._transmission;\n\n\t}\n\n\tset transmission( value ) {\n\n\t\tif ( this._transmission > 0 !== value > 0 ) {\n\n\t\t\tthis.version ++;\n\n\t\t}\n\n\t\tthis._transmission = value;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.defines = {\n\n\t\t\t'STANDARD': '',\n\t\t\t'PHYSICAL': ''\n\n\t\t};\n\n\t\tthis.clearcoat = source.clearcoat;\n\t\tthis.clearcoatMap = source.clearcoatMap;\n\t\tthis.clearcoatRoughness = source.clearcoatRoughness;\n\t\tthis.clearcoatRoughnessMap = source.clearcoatRoughnessMap;\n\t\tthis.clearcoatNormalMap = source.clearcoatNormalMap;\n\t\tthis.clearcoatNormalScale.copy( source.clearcoatNormalScale );\n\n\t\tthis.ior = source.ior;\n\n\t\tthis.iridescence = source.iridescence;\n\t\tthis.iridescenceMap = source.iridescenceMap;\n\t\tthis.iridescenceIOR = source.iridescenceIOR;\n\t\tthis.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];\n\t\tthis.iridescenceThicknessMap = source.iridescenceThicknessMap;\n\n\t\tthis.sheen = source.sheen;\n\t\tthis.sheenColor.copy( source.sheenColor );\n\t\tthis.sheenColorMap = source.sheenColorMap;\n\t\tthis.sheenRoughness = source.sheenRoughness;\n\t\tthis.sheenRoughnessMap = source.sheenRoughnessMap;\n\n\t\tthis.transmission = source.transmission;\n\t\tthis.transmissionMap = source.transmissionMap;\n\n\t\tthis.thickness = source.thickness;\n\t\tthis.thicknessMap = source.thicknessMap;\n\t\tthis.attenuationDistance = source.attenuationDistance;\n\t\tthis.attenuationColor.copy( source.attenuationColor );\n\n\t\tthis.specularIntensity = source.specularIntensity;\n\t\tthis.specularIntensityMap = source.specularIntensityMap;\n\t\tthis.specularColor.copy( source.specularColor );\n\t\tthis.specularColorMap = source.specularColorMap;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass MeshPhongMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isMeshPhongMaterial = true;\n\n\t\tthis.type = 'MeshPhongMaterial';\n\n\t\tthis.color = new Color( 0xffffff ); // diffuse\n\t\tthis.specular = new Color( 0x111111 );\n\t\tthis.shininess = 30;\n\n\t\tthis.map = null;\n\n\t\tthis.lightMap = null;\n\t\tthis.lightMapIntensity = 1.0;\n\n\t\tthis.aoMap = null;\n\t\tthis.aoMapIntensity = 1.0;\n\n\t\tthis.emissive = new Color( 0x000000 );\n\t\tthis.emissiveIntensity = 1.0;\n\t\tthis.emissiveMap = null;\n\n\t\tthis.bumpMap = null;\n\t\tthis.bumpScale = 1;\n\n\t\tthis.normalMap = null;\n\t\tthis.normalMapType = TangentSpaceNormalMap;\n\t\tthis.normalScale = new Vector2( 1, 1 );\n\n\t\tthis.displacementMap = null;\n\t\tthis.displacementScale = 1;\n\t\tthis.displacementBias = 0;\n\n\t\tthis.specularMap = null;\n\n\t\tthis.alphaMap = null;\n\n\t\tthis.envMap = null;\n\t\tthis.combine = MultiplyOperation;\n\t\tthis.reflectivity = 1;\n\t\tthis.refractionRatio = 0.98;\n\n\t\tthis.wireframe = false;\n\t\tthis.wireframeLinewidth = 1;\n\t\tthis.wireframeLinecap = 'round';\n\t\tthis.wireframeLinejoin = 'round';\n\n\t\tthis.flatShading = false;\n\n\t\tthis.fog = true;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.color.copy( source.color );\n\t\tthis.specular.copy( source.specular );\n\t\tthis.shininess = source.shininess;\n\n\t\tthis.map = source.map;\n\n\t\tthis.lightMap = source.lightMap;\n\t\tthis.lightMapIntensity = source.lightMapIntensity;\n\n\t\tthis.aoMap = source.aoMap;\n\t\tthis.aoMapIntensity = source.aoMapIntensity;\n\n\t\tthis.emissive.copy( source.emissive );\n\t\tthis.emissiveMap = source.emissiveMap;\n\t\tthis.emissiveIntensity = source.emissiveIntensity;\n\n\t\tthis.bumpMap = source.bumpMap;\n\t\tthis.bumpScale = source.bumpScale;\n\n\t\tthis.normalMap = source.normalMap;\n\t\tthis.normalMapType = source.normalMapType;\n\t\tthis.normalScale.copy( source.normalScale );\n\n\t\tthis.displacementMap = source.displacementMap;\n\t\tthis.displacementScale = source.displacementScale;\n\t\tthis.displacementBias = source.displacementBias;\n\n\t\tthis.specularMap = source.specularMap;\n\n\t\tthis.alphaMap = source.alphaMap;\n\n\t\tthis.envMap = source.envMap;\n\t\tthis.combine = source.combine;\n\t\tthis.reflectivity = source.reflectivity;\n\t\tthis.refractionRatio = source.refractionRatio;\n\n\t\tthis.wireframe = source.wireframe;\n\t\tthis.wireframeLinewidth = source.wireframeLinewidth;\n\t\tthis.wireframeLinecap = source.wireframeLinecap;\n\t\tthis.wireframeLinejoin = source.wireframeLinejoin;\n\n\t\tthis.flatShading = source.flatShading;\n\n\t\tthis.fog = source.fog;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass MeshToonMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isMeshToonMaterial = true;\n\n\t\tthis.defines = { 'TOON': '' };\n\n\t\tthis.type = 'MeshToonMaterial';\n\n\t\tthis.color = new Color( 0xffffff );\n\n\t\tthis.map = null;\n\t\tthis.gradientMap = null;\n\n\t\tthis.lightMap = null;\n\t\tthis.lightMapIntensity = 1.0;\n\n\t\tthis.aoMap = null;\n\t\tthis.aoMapIntensity = 1.0;\n\n\t\tthis.emissive = new Color( 0x000000 );\n\t\tthis.emissiveIntensity = 1.0;\n\t\tthis.emissiveMap = null;\n\n\t\tthis.bumpMap = null;\n\t\tthis.bumpScale = 1;\n\n\t\tthis.normalMap = null;\n\t\tthis.normalMapType = TangentSpaceNormalMap;\n\t\tthis.normalScale = new Vector2( 1, 1 );\n\n\t\tthis.displacementMap = null;\n\t\tthis.displacementScale = 1;\n\t\tthis.displacementBias = 0;\n\n\t\tthis.alphaMap = null;\n\n\t\tthis.wireframe = false;\n\t\tthis.wireframeLinewidth = 1;\n\t\tthis.wireframeLinecap = 'round';\n\t\tthis.wireframeLinejoin = 'round';\n\n\t\tthis.fog = true;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.color.copy( source.color );\n\n\t\tthis.map = source.map;\n\t\tthis.gradientMap = source.gradientMap;\n\n\t\tthis.lightMap = source.lightMap;\n\t\tthis.lightMapIntensity = source.lightMapIntensity;\n\n\t\tthis.aoMap = source.aoMap;\n\t\tthis.aoMapIntensity = source.aoMapIntensity;\n\n\t\tthis.emissive.copy( source.emissive );\n\t\tthis.emissiveMap = source.emissiveMap;\n\t\tthis.emissiveIntensity = source.emissiveIntensity;\n\n\t\tthis.bumpMap = source.bumpMap;\n\t\tthis.bumpScale = source.bumpScale;\n\n\t\tthis.normalMap = source.normalMap;\n\t\tthis.normalMapType = source.normalMapType;\n\t\tthis.normalScale.copy( source.normalScale );\n\n\t\tthis.displacementMap = source.displacementMap;\n\t\tthis.displacementScale = source.displacementScale;\n\t\tthis.displacementBias = source.displacementBias;\n\n\t\tthis.alphaMap = source.alphaMap;\n\n\t\tthis.wireframe = source.wireframe;\n\t\tthis.wireframeLinewidth = source.wireframeLinewidth;\n\t\tthis.wireframeLinecap = source.wireframeLinecap;\n\t\tthis.wireframeLinejoin = source.wireframeLinejoin;\n\n\t\tthis.fog = source.fog;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass MeshNormalMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isMeshNormalMaterial = true;\n\n\t\tthis.type = 'MeshNormalMaterial';\n\n\t\tthis.bumpMap = null;\n\t\tthis.bumpScale = 1;\n\n\t\tthis.normalMap = null;\n\t\tthis.normalMapType = TangentSpaceNormalMap;\n\t\tthis.normalScale = new Vector2( 1, 1 );\n\n\t\tthis.displacementMap = null;\n\t\tthis.displacementScale = 1;\n\t\tthis.displacementBias = 0;\n\n\t\tthis.wireframe = false;\n\t\tthis.wireframeLinewidth = 1;\n\n\t\tthis.flatShading = false;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.bumpMap = source.bumpMap;\n\t\tthis.bumpScale = source.bumpScale;\n\n\t\tthis.normalMap = source.normalMap;\n\t\tthis.normalMapType = source.normalMapType;\n\t\tthis.normalScale.copy( source.normalScale );\n\n\t\tthis.displacementMap = source.displacementMap;\n\t\tthis.displacementScale = source.displacementScale;\n\t\tthis.displacementBias = source.displacementBias;\n\n\t\tthis.wireframe = source.wireframe;\n\t\tthis.wireframeLinewidth = source.wireframeLinewidth;\n\n\t\tthis.flatShading = source.flatShading;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass MeshLambertMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isMeshLambertMaterial = true;\n\n\t\tthis.type = 'MeshLambertMaterial';\n\n\t\tthis.color = new Color( 0xffffff ); // diffuse\n\n\t\tthis.map = null;\n\n\t\tthis.lightMap = null;\n\t\tthis.lightMapIntensity = 1.0;\n\n\t\tthis.aoMap = null;\n\t\tthis.aoMapIntensity = 1.0;\n\n\t\tthis.emissive = new Color( 0x000000 );\n\t\tthis.emissiveIntensity = 1.0;\n\t\tthis.emissiveMap = null;\n\n\t\tthis.bumpMap = null;\n\t\tthis.bumpScale = 1;\n\n\t\tthis.normalMap = null;\n\t\tthis.normalMapType = TangentSpaceNormalMap;\n\t\tthis.normalScale = new Vector2( 1, 1 );\n\n\t\tthis.displacementMap = null;\n\t\tthis.displacementScale = 1;\n\t\tthis.displacementBias = 0;\n\n\t\tthis.specularMap = null;\n\n\t\tthis.alphaMap = null;\n\n\t\tthis.envMap = null;\n\t\tthis.combine = MultiplyOperation;\n\t\tthis.reflectivity = 1;\n\t\tthis.refractionRatio = 0.98;\n\n\t\tthis.wireframe = false;\n\t\tthis.wireframeLinewidth = 1;\n\t\tthis.wireframeLinecap = 'round';\n\t\tthis.wireframeLinejoin = 'round';\n\n\t\tthis.flatShading = false;\n\n\t\tthis.fog = true;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.color.copy( source.color );\n\n\t\tthis.map = source.map;\n\n\t\tthis.lightMap = source.lightMap;\n\t\tthis.lightMapIntensity = source.lightMapIntensity;\n\n\t\tthis.aoMap = source.aoMap;\n\t\tthis.aoMapIntensity = source.aoMapIntensity;\n\n\t\tthis.emissive.copy( source.emissive );\n\t\tthis.emissiveMap = source.emissiveMap;\n\t\tthis.emissiveIntensity = source.emissiveIntensity;\n\n\t\tthis.bumpMap = source.bumpMap;\n\t\tthis.bumpScale = source.bumpScale;\n\n\t\tthis.normalMap = source.normalMap;\n\t\tthis.normalMapType = source.normalMapType;\n\t\tthis.normalScale.copy( source.normalScale );\n\n\t\tthis.displacementMap = source.displacementMap;\n\t\tthis.displacementScale = source.displacementScale;\n\t\tthis.displacementBias = source.displacementBias;\n\n\t\tthis.specularMap = source.specularMap;\n\n\t\tthis.alphaMap = source.alphaMap;\n\n\t\tthis.envMap = source.envMap;\n\t\tthis.combine = source.combine;\n\t\tthis.reflectivity = source.reflectivity;\n\t\tthis.refractionRatio = source.refractionRatio;\n\n\t\tthis.wireframe = source.wireframe;\n\t\tthis.wireframeLinewidth = source.wireframeLinewidth;\n\t\tthis.wireframeLinecap = source.wireframeLinecap;\n\t\tthis.wireframeLinejoin = source.wireframeLinejoin;\n\n\t\tthis.flatShading = source.flatShading;\n\n\t\tthis.fog = source.fog;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass MeshMatcapMaterial extends Material {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isMeshMatcapMaterial = true;\n\n\t\tthis.defines = { 'MATCAP': '' };\n\n\t\tthis.type = 'MeshMatcapMaterial';\n\n\t\tthis.color = new Color( 0xffffff ); // diffuse\n\n\t\tthis.matcap = null;\n\n\t\tthis.map = null;\n\n\t\tthis.bumpMap = null;\n\t\tthis.bumpScale = 1;\n\n\t\tthis.normalMap = null;\n\t\tthis.normalMapType = TangentSpaceNormalMap;\n\t\tthis.normalScale = new Vector2( 1, 1 );\n\n\t\tthis.displacementMap = null;\n\t\tthis.displacementScale = 1;\n\t\tthis.displacementBias = 0;\n\n\t\tthis.alphaMap = null;\n\n\t\tthis.flatShading = false;\n\n\t\tthis.fog = true;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.defines = { 'MATCAP': '' };\n\n\t\tthis.color.copy( source.color );\n\n\t\tthis.matcap = source.matcap;\n\n\t\tthis.map = source.map;\n\n\t\tthis.bumpMap = source.bumpMap;\n\t\tthis.bumpScale = source.bumpScale;\n\n\t\tthis.normalMap = source.normalMap;\n\t\tthis.normalMapType = source.normalMapType;\n\t\tthis.normalScale.copy( source.normalScale );\n\n\t\tthis.displacementMap = source.displacementMap;\n\t\tthis.displacementScale = source.displacementScale;\n\t\tthis.displacementBias = source.displacementBias;\n\n\t\tthis.alphaMap = source.alphaMap;\n\n\t\tthis.flatShading = source.flatShading;\n\n\t\tthis.fog = source.fog;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass LineDashedMaterial extends LineBasicMaterial {\n\n\tconstructor( parameters ) {\n\n\t\tsuper();\n\n\t\tthis.isLineDashedMaterial = true;\n\n\t\tthis.type = 'LineDashedMaterial';\n\n\t\tthis.scale = 1;\n\t\tthis.dashSize = 3;\n\t\tthis.gapSize = 1;\n\n\t\tthis.setValues( parameters );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.scale = source.scale;\n\t\tthis.dashSize = source.dashSize;\n\t\tthis.gapSize = source.gapSize;\n\n\t\treturn this;\n\n\t}\n\n}\n\n// same as Array.prototype.slice, but also works on typed arrays\nfunction arraySlice( array, from, to ) {\n\n\tif ( isTypedArray( array ) ) {\n\n\t\t// in ios9 array.subarray(from, undefined) will return empty array\n\t\t// but array.subarray(from) or array.subarray(from, len) is correct\n\t\treturn new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );\n\n\t}\n\n\treturn array.slice( from, to );\n\n}\n\n// converts an array to a specific type\nfunction convertArray( array, type, forceClone ) {\n\n\tif ( ! array || // let 'undefined' and 'null' pass\n\t\t! forceClone && array.constructor === type ) return array;\n\n\tif ( typeof type.BYTES_PER_ELEMENT === 'number' ) {\n\n\t\treturn new type( array ); // create typed array\n\n\t}\n\n\treturn Array.prototype.slice.call( array ); // create Array\n\n}\n\nfunction isTypedArray( object ) {\n\n\treturn ArrayBuffer.isView( object ) &&\n\t\t! ( object instanceof DataView );\n\n}\n\n// returns an array by which times and values can be sorted\nfunction getKeyframeOrder( times ) {\n\n\tfunction compareTime( i, j ) {\n\n\t\treturn times[ i ] - times[ j ];\n\n\t}\n\n\tconst n = times.length;\n\tconst result = new Array( n );\n\tfor ( let i = 0; i !== n; ++ i ) result[ i ] = i;\n\n\tresult.sort( compareTime );\n\n\treturn result;\n\n}\n\n// uses the array previously returned by 'getKeyframeOrder' to sort data\nfunction sortedArray( values, stride, order ) {\n\n\tconst nValues = values.length;\n\tconst result = new values.constructor( nValues );\n\n\tfor ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {\n\n\t\tconst srcOffset = order[ i ] * stride;\n\n\t\tfor ( let j = 0; j !== stride; ++ j ) {\n\n\t\t\tresult[ dstOffset ++ ] = values[ srcOffset + j ];\n\n\t\t}\n\n\t}\n\n\treturn result;\n\n}\n\n// function for parsing AOS keyframe formats\nfunction flattenJSON( jsonKeys, times, values, valuePropertyName ) {\n\n\tlet i = 1, key = jsonKeys[ 0 ];\n\n\twhile ( key !== undefined && key[ valuePropertyName ] === undefined ) {\n\n\t\tkey = jsonKeys[ i ++ ];\n\n\t}\n\n\tif ( key === undefined ) return; // no data\n\n\tlet value = key[ valuePropertyName ];\n\tif ( value === undefined ) return; // no data\n\n\tif ( Array.isArray( value ) ) {\n\n\t\tdo {\n\n\t\t\tvalue = key[ valuePropertyName ];\n\n\t\t\tif ( value !== undefined ) {\n\n\t\t\t\ttimes.push( key.time );\n\t\t\t\tvalues.push.apply( values, value ); // push all elements\n\n\t\t\t}\n\n\t\t\tkey = jsonKeys[ i ++ ];\n\n\t\t} while ( key !== undefined );\n\n\t} else if ( value.toArray !== undefined ) {\n\n\t\t// ...assume THREE.Math-ish\n\n\t\tdo {\n\n\t\t\tvalue = key[ valuePropertyName ];\n\n\t\t\tif ( value !== undefined ) {\n\n\t\t\t\ttimes.push( key.time );\n\t\t\t\tvalue.toArray( values, values.length );\n\n\t\t\t}\n\n\t\t\tkey = jsonKeys[ i ++ ];\n\n\t\t} while ( key !== undefined );\n\n\t} else {\n\n\t\t// otherwise push as-is\n\n\t\tdo {\n\n\t\t\tvalue = key[ valuePropertyName ];\n\n\t\t\tif ( value !== undefined ) {\n\n\t\t\t\ttimes.push( key.time );\n\t\t\t\tvalues.push( value );\n\n\t\t\t}\n\n\t\t\tkey = jsonKeys[ i ++ ];\n\n\t\t} while ( key !== undefined );\n\n\t}\n\n}\n\nfunction subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {\n\n\tconst clip = sourceClip.clone();\n\n\tclip.name = name;\n\n\tconst tracks = [];\n\n\tfor ( let i = 0; i < clip.tracks.length; ++ i ) {\n\n\t\tconst track = clip.tracks[ i ];\n\t\tconst valueSize = track.getValueSize();\n\n\t\tconst times = [];\n\t\tconst values = [];\n\n\t\tfor ( let j = 0; j < track.times.length; ++ j ) {\n\n\t\t\tconst frame = track.times[ j ] * fps;\n\n\t\t\tif ( frame < startFrame || frame >= endFrame ) continue;\n\n\t\t\ttimes.push( track.times[ j ] );\n\n\t\t\tfor ( let k = 0; k < valueSize; ++ k ) {\n\n\t\t\t\tvalues.push( track.values[ j * valueSize + k ] );\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( times.length === 0 ) continue;\n\n\t\ttrack.times = convertArray( times, track.times.constructor );\n\t\ttrack.values = convertArray( values, track.values.constructor );\n\n\t\ttracks.push( track );\n\n\t}\n\n\tclip.tracks = tracks;\n\n\t// find minimum .times value across all tracks in the trimmed clip\n\n\tlet minStartTime = Infinity;\n\n\tfor ( let i = 0; i < clip.tracks.length; ++ i ) {\n\n\t\tif ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {\n\n\t\t\tminStartTime = clip.tracks[ i ].times[ 0 ];\n\n\t\t}\n\n\t}\n\n\t// shift all tracks such that clip begins at t=0\n\n\tfor ( let i = 0; i < clip.tracks.length; ++ i ) {\n\n\t\tclip.tracks[ i ].shift( - 1 * minStartTime );\n\n\t}\n\n\tclip.resetDuration();\n\n\treturn clip;\n\n}\n\nfunction makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {\n\n\tif ( fps <= 0 ) fps = 30;\n\n\tconst numTracks = referenceClip.tracks.length;\n\tconst referenceTime = referenceFrame / fps;\n\n\t// Make each track's values relative to the values at the reference frame\n\tfor ( let i = 0; i < numTracks; ++ i ) {\n\n\t\tconst referenceTrack = referenceClip.tracks[ i ];\n\t\tconst referenceTrackType = referenceTrack.ValueTypeName;\n\n\t\t// Skip this track if it's non-numeric\n\t\tif ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;\n\n\t\t// Find the track in the target clip whose name and type matches the reference track\n\t\tconst targetTrack = targetClip.tracks.find( function ( track ) {\n\n\t\t\treturn track.name === referenceTrack.name\n\t\t\t\t&& track.ValueTypeName === referenceTrackType;\n\n\t\t} );\n\n\t\tif ( targetTrack === undefined ) continue;\n\n\t\tlet referenceOffset = 0;\n\t\tconst referenceValueSize = referenceTrack.getValueSize();\n\n\t\tif ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {\n\n\t\t\treferenceOffset = referenceValueSize / 3;\n\n\t\t}\n\n\t\tlet targetOffset = 0;\n\t\tconst targetValueSize = targetTrack.getValueSize();\n\n\t\tif ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {\n\n\t\t\ttargetOffset = targetValueSize / 3;\n\n\t\t}\n\n\t\tconst lastIndex = referenceTrack.times.length - 1;\n\t\tlet referenceValue;\n\n\t\t// Find the value to subtract out of the track\n\t\tif ( referenceTime <= referenceTrack.times[ 0 ] ) {\n\n\t\t\t// Reference frame is earlier than the first keyframe, so just use the first keyframe\n\t\t\tconst startIndex = referenceOffset;\n\t\t\tconst endIndex = referenceValueSize - referenceOffset;\n\t\t\treferenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );\n\n\t\t} else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {\n\n\t\t\t// Reference frame is after the last keyframe, so just use the last keyframe\n\t\t\tconst startIndex = lastIndex * referenceValueSize + referenceOffset;\n\t\t\tconst endIndex = startIndex + referenceValueSize - referenceOffset;\n\t\t\treferenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );\n\n\t\t} else {\n\n\t\t\t// Interpolate to the reference value\n\t\t\tconst interpolant = referenceTrack.createInterpolant();\n\t\t\tconst startIndex = referenceOffset;\n\t\t\tconst endIndex = referenceValueSize - referenceOffset;\n\t\t\tinterpolant.evaluate( referenceTime );\n\t\t\treferenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );\n\n\t\t}\n\n\t\t// Conjugate the quaternion\n\t\tif ( referenceTrackType === 'quaternion' ) {\n\n\t\t\tconst referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();\n\t\t\treferenceQuat.toArray( referenceValue );\n\n\t\t}\n\n\t\t// Subtract the reference value from all of the track values\n\n\t\tconst numTimes = targetTrack.times.length;\n\t\tfor ( let j = 0; j < numTimes; ++ j ) {\n\n\t\t\tconst valueStart = j * targetValueSize + targetOffset;\n\n\t\t\tif ( referenceTrackType === 'quaternion' ) {\n\n\t\t\t\t// Multiply the conjugate for quaternion track types\n\t\t\t\tQuaternion.multiplyQuaternionsFlat(\n\t\t\t\t\ttargetTrack.values,\n\t\t\t\t\tvalueStart,\n\t\t\t\t\treferenceValue,\n\t\t\t\t\t0,\n\t\t\t\t\ttargetTrack.values,\n\t\t\t\t\tvalueStart\n\t\t\t\t);\n\n\t\t\t} else {\n\n\t\t\t\tconst valueEnd = targetValueSize - targetOffset * 2;\n\n\t\t\t\t// Subtract each value for all other numeric track types\n\t\t\t\tfor ( let k = 0; k < valueEnd; ++ k ) {\n\n\t\t\t\t\ttargetTrack.values[ valueStart + k ] -= referenceValue[ k ];\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\ttargetClip.blendMode = AdditiveAnimationBlendMode;\n\n\treturn targetClip;\n\n}\n\nconst AnimationUtils = {\n\tarraySlice: arraySlice,\n\tconvertArray: convertArray,\n\tisTypedArray: isTypedArray,\n\tgetKeyframeOrder: getKeyframeOrder,\n\tsortedArray: sortedArray,\n\tflattenJSON: flattenJSON,\n\tsubclip: subclip,\n\tmakeClipAdditive: makeClipAdditive\n};\n\n/**\n * Abstract base class of interpolants over parametric samples.\n *\n * The parameter domain is one dimensional, typically the time or a path\n * along a curve defined by the data.\n *\n * The sample values can have any dimensionality and derived classes may\n * apply special interpretations to the data.\n *\n * This class provides the interval seek in a Template Method, deferring\n * the actual interpolation to derived classes.\n *\n * Time complexity is O(1) for linear access crossing at most two points\n * and O(log N) for random access, where N is the number of positions.\n *\n * References:\n *\n * \t\thttp://www.oodesign.com/template-method-pattern.html\n *\n */\n\nclass Interpolant {\n\n\tconstructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {\n\n\t\tthis.parameterPositions = parameterPositions;\n\t\tthis._cachedIndex = 0;\n\n\t\tthis.resultBuffer = resultBuffer !== undefined ?\n\t\t\tresultBuffer : new sampleValues.constructor( sampleSize );\n\t\tthis.sampleValues = sampleValues;\n\t\tthis.valueSize = sampleSize;\n\n\t\tthis.settings = null;\n\t\tthis.DefaultSettings_ = {};\n\n\t}\n\n\tevaluate( t ) {\n\n\t\tconst pp = this.parameterPositions;\n\t\tlet i1 = this._cachedIndex,\n\t\t\tt1 = pp[ i1 ],\n\t\t\tt0 = pp[ i1 - 1 ];\n\n\t\tvalidate_interval: {\n\n\t\t\tseek: {\n\n\t\t\t\tlet right;\n\n\t\t\t\tlinear_scan: {\n\n\t\t\t\t\t//- See http://jsperf.com/comparison-to-undefined/3\n\t\t\t\t\t//- slower code:\n\t\t\t\t\t//-\n\t\t\t\t\t//- \t\t\t\tif ( t >= t1 || t1 === undefined ) {\n\t\t\t\t\tforward_scan: if ( ! ( t < t1 ) ) {\n\n\t\t\t\t\t\tfor ( let giveUpAt = i1 + 2; ; ) {\n\n\t\t\t\t\t\t\tif ( t1 === undefined ) {\n\n\t\t\t\t\t\t\t\tif ( t < t0 ) break forward_scan;\n\n\t\t\t\t\t\t\t\t// after end\n\n\t\t\t\t\t\t\t\ti1 = pp.length;\n\t\t\t\t\t\t\t\tthis._cachedIndex = i1;\n\t\t\t\t\t\t\t\treturn this.copySampleValue_( i1 - 1 );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( i1 === giveUpAt ) break; // this loop\n\n\t\t\t\t\t\t\tt0 = t1;\n\t\t\t\t\t\t\tt1 = pp[ ++ i1 ];\n\n\t\t\t\t\t\t\tif ( t < t1 ) {\n\n\t\t\t\t\t\t\t\t// we have arrived at the sought interval\n\t\t\t\t\t\t\t\tbreak seek;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// prepare binary search on the right side of the index\n\t\t\t\t\t\tright = pp.length;\n\t\t\t\t\t\tbreak linear_scan;\n\n\t\t\t\t\t}\n\n\t\t\t\t\t//- slower code:\n\t\t\t\t\t//-\t\t\t\t\tif ( t < t0 || t0 === undefined ) {\n\t\t\t\t\tif ( ! ( t >= t0 ) ) {\n\n\t\t\t\t\t\t// looping?\n\n\t\t\t\t\t\tconst t1global = pp[ 1 ];\n\n\t\t\t\t\t\tif ( t < t1global ) {\n\n\t\t\t\t\t\t\ti1 = 2; // + 1, using the scan for the details\n\t\t\t\t\t\t\tt0 = t1global;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// linear reverse scan\n\n\t\t\t\t\t\tfor ( let giveUpAt = i1 - 2; ; ) {\n\n\t\t\t\t\t\t\tif ( t0 === undefined ) {\n\n\t\t\t\t\t\t\t\t// before start\n\n\t\t\t\t\t\t\t\tthis._cachedIndex = 0;\n\t\t\t\t\t\t\t\treturn this.copySampleValue_( 0 );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( i1 === giveUpAt ) break; // this loop\n\n\t\t\t\t\t\t\tt1 = t0;\n\t\t\t\t\t\t\tt0 = pp[ -- i1 - 1 ];\n\n\t\t\t\t\t\t\tif ( t >= t0 ) {\n\n\t\t\t\t\t\t\t\t// we have arrived at the sought interval\n\t\t\t\t\t\t\t\tbreak seek;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// prepare binary search on the left side of the index\n\t\t\t\t\t\tright = i1;\n\t\t\t\t\t\ti1 = 0;\n\t\t\t\t\t\tbreak linear_scan;\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// the interval is valid\n\n\t\t\t\t\tbreak validate_interval;\n\n\t\t\t\t} // linear scan\n\n\t\t\t\t// binary search\n\n\t\t\t\twhile ( i1 < right ) {\n\n\t\t\t\t\tconst mid = ( i1 + right ) >>> 1;\n\n\t\t\t\t\tif ( t < pp[ mid ] ) {\n\n\t\t\t\t\t\tright = mid;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\ti1 = mid + 1;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tt1 = pp[ i1 ];\n\t\t\t\tt0 = pp[ i1 - 1 ];\n\n\t\t\t\t// check boundary cases, again\n\n\t\t\t\tif ( t0 === undefined ) {\n\n\t\t\t\t\tthis._cachedIndex = 0;\n\t\t\t\t\treturn this.copySampleValue_( 0 );\n\n\t\t\t\t}\n\n\t\t\t\tif ( t1 === undefined ) {\n\n\t\t\t\t\ti1 = pp.length;\n\t\t\t\t\tthis._cachedIndex = i1;\n\t\t\t\t\treturn this.copySampleValue_( i1 - 1 );\n\n\t\t\t\t}\n\n\t\t\t} // seek\n\n\t\t\tthis._cachedIndex = i1;\n\n\t\t\tthis.intervalChanged_( i1, t0, t1 );\n\n\t\t} // validate_interval\n\n\t\treturn this.interpolate_( i1, t0, t, t1 );\n\n\t}\n\n\tgetSettings_() {\n\n\t\treturn this.settings || this.DefaultSettings_;\n\n\t}\n\n\tcopySampleValue_( index ) {\n\n\t\t// copies a sample value to the result buffer\n\n\t\tconst result = this.resultBuffer,\n\t\t\tvalues = this.sampleValues,\n\t\t\tstride = this.valueSize,\n\t\t\toffset = index * stride;\n\n\t\tfor ( let i = 0; i !== stride; ++ i ) {\n\n\t\t\tresult[ i ] = values[ offset + i ];\n\n\t\t}\n\n\t\treturn result;\n\n\t}\n\n\t// Template methods for derived classes:\n\n\tinterpolate_( /* i1, t0, t, t1 */ ) {\n\n\t\tthrow new Error( 'call to abstract method' );\n\t\t// implementations shall return this.resultBuffer\n\n\t}\n\n\tintervalChanged_( /* i1, t0, t1 */ ) {\n\n\t\t// empty\n\n\t}\n\n}\n\n/**\n * Fast and simple cubic spline interpolant.\n *\n * It was derived from a Hermitian construction setting the first derivative\n * at each sample position to the linear slope between neighboring positions\n * over their parameter interval.\n */\n\nclass CubicInterpolant extends Interpolant {\n\n\tconstructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {\n\n\t\tsuper( parameterPositions, sampleValues, sampleSize, resultBuffer );\n\n\t\tthis._weightPrev = - 0;\n\t\tthis._offsetPrev = - 0;\n\t\tthis._weightNext = - 0;\n\t\tthis._offsetNext = - 0;\n\n\t\tthis.DefaultSettings_ = {\n\n\t\t\tendingStart: ZeroCurvatureEnding,\n\t\t\tendingEnd: ZeroCurvatureEnding\n\n\t\t};\n\n\t}\n\n\tintervalChanged_( i1, t0, t1 ) {\n\n\t\tconst pp = this.parameterPositions;\n\t\tlet iPrev = i1 - 2,\n\t\t\tiNext = i1 + 1,\n\n\t\t\ttPrev = pp[ iPrev ],\n\t\t\ttNext = pp[ iNext ];\n\n\t\tif ( tPrev === undefined ) {\n\n\t\t\tswitch ( this.getSettings_().endingStart ) {\n\n\t\t\t\tcase ZeroSlopeEnding:\n\n\t\t\t\t\t// f'(t0) = 0\n\t\t\t\t\tiPrev = i1;\n\t\t\t\t\ttPrev = 2 * t0 - t1;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase WrapAroundEnding:\n\n\t\t\t\t\t// use the other end of the curve\n\t\t\t\t\tiPrev = pp.length - 2;\n\t\t\t\t\ttPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault: // ZeroCurvatureEnding\n\n\t\t\t\t\t// f''(t0) = 0 a.k.a. Natural Spline\n\t\t\t\t\tiPrev = i1;\n\t\t\t\t\ttPrev = t1;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( tNext === undefined ) {\n\n\t\t\tswitch ( this.getSettings_().endingEnd ) {\n\n\t\t\t\tcase ZeroSlopeEnding:\n\n\t\t\t\t\t// f'(tN) = 0\n\t\t\t\t\tiNext = i1;\n\t\t\t\t\ttNext = 2 * t1 - t0;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase WrapAroundEnding:\n\n\t\t\t\t\t// use the other end of the curve\n\t\t\t\t\tiNext = 1;\n\t\t\t\t\ttNext = t1 + pp[ 1 ] - pp[ 0 ];\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault: // ZeroCurvatureEnding\n\n\t\t\t\t\t// f''(tN) = 0, a.k.a. Natural Spline\n\t\t\t\t\tiNext = i1 - 1;\n\t\t\t\t\ttNext = t0;\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst halfDt = ( t1 - t0 ) * 0.5,\n\t\t\tstride = this.valueSize;\n\n\t\tthis._weightPrev = halfDt / ( t0 - tPrev );\n\t\tthis._weightNext = halfDt / ( tNext - t1 );\n\t\tthis._offsetPrev = iPrev * stride;\n\t\tthis._offsetNext = iNext * stride;\n\n\t}\n\n\tinterpolate_( i1, t0, t, t1 ) {\n\n\t\tconst result = this.resultBuffer,\n\t\t\tvalues = this.sampleValues,\n\t\t\tstride = this.valueSize,\n\n\t\t\to1 = i1 * stride,\t\to0 = o1 - stride,\n\t\t\toP = this._offsetPrev, \toN = this._offsetNext,\n\t\t\twP = this._weightPrev,\twN = this._weightNext,\n\n\t\t\tp = ( t - t0 ) / ( t1 - t0 ),\n\t\t\tpp = p * p,\n\t\t\tppp = pp * p;\n\n\t\t// evaluate polynomials\n\n\t\tconst sP = - wP * ppp + 2 * wP * pp - wP * p;\n\t\tconst s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;\n\t\tconst s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;\n\t\tconst sN = wN * ppp - wN * pp;\n\n\t\t// combine data linearly\n\n\t\tfor ( let i = 0; i !== stride; ++ i ) {\n\n\t\t\tresult[ i ] =\n\t\t\t\t\tsP * values[ oP + i ] +\n\t\t\t\t\ts0 * values[ o0 + i ] +\n\t\t\t\t\ts1 * values[ o1 + i ] +\n\t\t\t\t\tsN * values[ oN + i ];\n\n\t\t}\n\n\t\treturn result;\n\n\t}\n\n}\n\nclass LinearInterpolant extends Interpolant {\n\n\tconstructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {\n\n\t\tsuper( parameterPositions, sampleValues, sampleSize, resultBuffer );\n\n\t}\n\n\tinterpolate_( i1, t0, t, t1 ) {\n\n\t\tconst result = this.resultBuffer,\n\t\t\tvalues = this.sampleValues,\n\t\t\tstride = this.valueSize,\n\n\t\t\toffset1 = i1 * stride,\n\t\t\toffset0 = offset1 - stride,\n\n\t\t\tweight1 = ( t - t0 ) / ( t1 - t0 ),\n\t\t\tweight0 = 1 - weight1;\n\n\t\tfor ( let i = 0; i !== stride; ++ i ) {\n\n\t\t\tresult[ i ] =\n\t\t\t\t\tvalues[ offset0 + i ] * weight0 +\n\t\t\t\t\tvalues[ offset1 + i ] * weight1;\n\n\t\t}\n\n\t\treturn result;\n\n\t}\n\n}\n\n/**\n *\n * Interpolant that evaluates to the sample value at the position preceding\n * the parameter.\n */\n\nclass DiscreteInterpolant extends Interpolant {\n\n\tconstructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {\n\n\t\tsuper( parameterPositions, sampleValues, sampleSize, resultBuffer );\n\n\t}\n\n\tinterpolate_( i1 /*, t0, t, t1 */ ) {\n\n\t\treturn this.copySampleValue_( i1 - 1 );\n\n\t}\n\n}\n\nclass KeyframeTrack {\n\n\tconstructor( name, times, values, interpolation ) {\n\n\t\tif ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );\n\t\tif ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );\n\n\t\tthis.name = name;\n\n\t\tthis.times = convertArray( times, this.TimeBufferType );\n\t\tthis.values = convertArray( values, this.ValueBufferType );\n\n\t\tthis.setInterpolation( interpolation || this.DefaultInterpolation );\n\n\t}\n\n\t// Serialization (in static context, because of constructor invocation\n\t// and automatic invocation of .toJSON):\n\n\tstatic toJSON( track ) {\n\n\t\tconst trackType = track.constructor;\n\n\t\tlet json;\n\n\t\t// derived classes can define a static toJSON method\n\t\tif ( trackType.toJSON !== this.toJSON ) {\n\n\t\t\tjson = trackType.toJSON( track );\n\n\t\t} else {\n\n\t\t\t// by default, we assume the data can be serialized as-is\n\t\t\tjson = {\n\n\t\t\t\t'name': track.name,\n\t\t\t\t'times': convertArray( track.times, Array ),\n\t\t\t\t'values': convertArray( track.values, Array )\n\n\t\t\t};\n\n\t\t\tconst interpolation = track.getInterpolation();\n\n\t\t\tif ( interpolation !== track.DefaultInterpolation ) {\n\n\t\t\t\tjson.interpolation = interpolation;\n\n\t\t\t}\n\n\t\t}\n\n\t\tjson.type = track.ValueTypeName; // mandatory\n\n\t\treturn json;\n\n\t}\n\n\tInterpolantFactoryMethodDiscrete( result ) {\n\n\t\treturn new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );\n\n\t}\n\n\tInterpolantFactoryMethodLinear( result ) {\n\n\t\treturn new LinearInterpolant( this.times, this.values, this.getValueSize(), result );\n\n\t}\n\n\tInterpolantFactoryMethodSmooth( result ) {\n\n\t\treturn new CubicInterpolant( this.times, this.values, this.getValueSize(), result );\n\n\t}\n\n\tsetInterpolation( interpolation ) {\n\n\t\tlet factoryMethod;\n\n\t\tswitch ( interpolation ) {\n\n\t\t\tcase InterpolateDiscrete:\n\n\t\t\t\tfactoryMethod = this.InterpolantFactoryMethodDiscrete;\n\n\t\t\t\tbreak;\n\n\t\t\tcase InterpolateLinear:\n\n\t\t\t\tfactoryMethod = this.InterpolantFactoryMethodLinear;\n\n\t\t\t\tbreak;\n\n\t\t\tcase InterpolateSmooth:\n\n\t\t\t\tfactoryMethod = this.InterpolantFactoryMethodSmooth;\n\n\t\t\t\tbreak;\n\n\t\t}\n\n\t\tif ( factoryMethod === undefined ) {\n\n\t\t\tconst message = 'unsupported interpolation for ' +\n\t\t\t\tthis.ValueTypeName + ' keyframe track named ' + this.name;\n\n\t\t\tif ( this.createInterpolant === undefined ) {\n\n\t\t\t\t// fall back to default, unless the default itself is messed up\n\t\t\t\tif ( interpolation !== this.DefaultInterpolation ) {\n\n\t\t\t\t\tthis.setInterpolation( this.DefaultInterpolation );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tthrow new Error( message ); // fatal, in this case\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tconsole.warn( 'THREE.KeyframeTrack:', message );\n\t\t\treturn this;\n\n\t\t}\n\n\t\tthis.createInterpolant = factoryMethod;\n\n\t\treturn this;\n\n\t}\n\n\tgetInterpolation() {\n\n\t\tswitch ( this.createInterpolant ) {\n\n\t\t\tcase this.InterpolantFactoryMethodDiscrete:\n\n\t\t\t\treturn InterpolateDiscrete;\n\n\t\t\tcase this.InterpolantFactoryMethodLinear:\n\n\t\t\t\treturn InterpolateLinear;\n\n\t\t\tcase this.InterpolantFactoryMethodSmooth:\n\n\t\t\t\treturn InterpolateSmooth;\n\n\t\t}\n\n\t}\n\n\tgetValueSize() {\n\n\t\treturn this.values.length / this.times.length;\n\n\t}\n\n\t// move all keyframes either forwards or backwards in time\n\tshift( timeOffset ) {\n\n\t\tif ( timeOffset !== 0.0 ) {\n\n\t\t\tconst times = this.times;\n\n\t\t\tfor ( let i = 0, n = times.length; i !== n; ++ i ) {\n\n\t\t\t\ttimes[ i ] += timeOffset;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t// scale all keyframe times by a factor (useful for frame <-> seconds conversions)\n\tscale( timeScale ) {\n\n\t\tif ( timeScale !== 1.0 ) {\n\n\t\t\tconst times = this.times;\n\n\t\t\tfor ( let i = 0, n = times.length; i !== n; ++ i ) {\n\n\t\t\t\ttimes[ i ] *= timeScale;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t// removes keyframes before and after animation without changing any values within the range [startTime, endTime].\n\t// IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values\n\ttrim( startTime, endTime ) {\n\n\t\tconst times = this.times,\n\t\t\tnKeys = times.length;\n\n\t\tlet from = 0,\n\t\t\tto = nKeys - 1;\n\n\t\twhile ( from !== nKeys && times[ from ] < startTime ) {\n\n\t\t\t++ from;\n\n\t\t}\n\n\t\twhile ( to !== - 1 && times[ to ] > endTime ) {\n\n\t\t\t-- to;\n\n\t\t}\n\n\t\t++ to; // inclusive -> exclusive bound\n\n\t\tif ( from !== 0 || to !== nKeys ) {\n\n\t\t\t// empty tracks are forbidden, so keep at least one keyframe\n\t\t\tif ( from >= to ) {\n\n\t\t\t\tto = Math.max( to, 1 );\n\t\t\t\tfrom = to - 1;\n\n\t\t\t}\n\n\t\t\tconst stride = this.getValueSize();\n\t\t\tthis.times = arraySlice( times, from, to );\n\t\t\tthis.values = arraySlice( this.values, from * stride, to * stride );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t// ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable\n\tvalidate() {\n\n\t\tlet valid = true;\n\n\t\tconst valueSize = this.getValueSize();\n\t\tif ( valueSize - Math.floor( valueSize ) !== 0 ) {\n\n\t\t\tconsole.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );\n\t\t\tvalid = false;\n\n\t\t}\n\n\t\tconst times = this.times,\n\t\t\tvalues = this.values,\n\n\t\t\tnKeys = times.length;\n\n\t\tif ( nKeys === 0 ) {\n\n\t\t\tconsole.error( 'THREE.KeyframeTrack: Track is empty.', this );\n\t\t\tvalid = false;\n\n\t\t}\n\n\t\tlet prevTime = null;\n\n\t\tfor ( let i = 0; i !== nKeys; i ++ ) {\n\n\t\t\tconst currTime = times[ i ];\n\n\t\t\tif ( typeof currTime === 'number' && isNaN( currTime ) ) {\n\n\t\t\t\tconsole.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );\n\t\t\t\tvalid = false;\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\tif ( prevTime !== null && prevTime > currTime ) {\n\n\t\t\t\tconsole.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );\n\t\t\t\tvalid = false;\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\tprevTime = currTime;\n\n\t\t}\n\n\t\tif ( values !== undefined ) {\n\n\t\t\tif ( isTypedArray( values ) ) {\n\n\t\t\t\tfor ( let i = 0, n = values.length; i !== n; ++ i ) {\n\n\t\t\t\t\tconst value = values[ i ];\n\n\t\t\t\t\tif ( isNaN( value ) ) {\n\n\t\t\t\t\t\tconsole.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );\n\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn valid;\n\n\t}\n\n\t// removes equivalent sequential keys as common in morph target sequences\n\t// (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)\n\toptimize() {\n\n\t\t// times or values may be shared with other tracks, so overwriting is unsafe\n\t\tconst times = arraySlice( this.times ),\n\t\t\tvalues = arraySlice( this.values ),\n\t\t\tstride = this.getValueSize(),\n\n\t\t\tsmoothInterpolation = this.getInterpolation() === InterpolateSmooth,\n\n\t\t\tlastIndex = times.length - 1;\n\n\t\tlet writeIndex = 1;\n\n\t\tfor ( let i = 1; i < lastIndex; ++ i ) {\n\n\t\t\tlet keep = false;\n\n\t\t\tconst time = times[ i ];\n\t\t\tconst timeNext = times[ i + 1 ];\n\n\t\t\t// remove adjacent keyframes scheduled at the same time\n\n\t\t\tif ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {\n\n\t\t\t\tif ( ! smoothInterpolation ) {\n\n\t\t\t\t\t// remove unnecessary keyframes same as their neighbors\n\n\t\t\t\t\tconst offset = i * stride,\n\t\t\t\t\t\toffsetP = offset - stride,\n\t\t\t\t\t\toffsetN = offset + stride;\n\n\t\t\t\t\tfor ( let j = 0; j !== stride; ++ j ) {\n\n\t\t\t\t\t\tconst value = values[ offset + j ];\n\n\t\t\t\t\t\tif ( value !== values[ offsetP + j ] ||\n\t\t\t\t\t\t\tvalue !== values[ offsetN + j ] ) {\n\n\t\t\t\t\t\t\tkeep = true;\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\tkeep = true;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// in-place compaction\n\n\t\t\tif ( keep ) {\n\n\t\t\t\tif ( i !== writeIndex ) {\n\n\t\t\t\t\ttimes[ writeIndex ] = times[ i ];\n\n\t\t\t\t\tconst readOffset = i * stride,\n\t\t\t\t\t\twriteOffset = writeIndex * stride;\n\n\t\t\t\t\tfor ( let j = 0; j !== stride; ++ j ) {\n\n\t\t\t\t\t\tvalues[ writeOffset + j ] = values[ readOffset + j ];\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\t++ writeIndex;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// flush last keyframe (compaction looks ahead)\n\n\t\tif ( lastIndex > 0 ) {\n\n\t\t\ttimes[ writeIndex ] = times[ lastIndex ];\n\n\t\t\tfor ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {\n\n\t\t\t\tvalues[ writeOffset + j ] = values[ readOffset + j ];\n\n\t\t\t}\n\n\t\t\t++ writeIndex;\n\n\t\t}\n\n\t\tif ( writeIndex !== times.length ) {\n\n\t\t\tthis.times = arraySlice( times, 0, writeIndex );\n\t\t\tthis.values = arraySlice( values, 0, writeIndex * stride );\n\n\t\t} else {\n\n\t\t\tthis.times = times;\n\t\t\tthis.values = values;\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\tconst times = arraySlice( this.times, 0 );\n\t\tconst values = arraySlice( this.values, 0 );\n\n\t\tconst TypedKeyframeTrack = this.constructor;\n\t\tconst track = new TypedKeyframeTrack( this.name, times, values );\n\n\t\t// Interpolant argument to constructor is not saved, so copy the factory method directly.\n\t\ttrack.createInterpolant = this.createInterpolant;\n\n\t\treturn track;\n\n\t}\n\n}\n\nKeyframeTrack.prototype.TimeBufferType = Float32Array;\nKeyframeTrack.prototype.ValueBufferType = Float32Array;\nKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;\n\n/**\n * A Track of Boolean keyframe values.\n */\nclass BooleanKeyframeTrack extends KeyframeTrack {}\n\nBooleanKeyframeTrack.prototype.ValueTypeName = 'bool';\nBooleanKeyframeTrack.prototype.ValueBufferType = Array;\nBooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;\nBooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;\nBooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;\n\n/**\n * A Track of keyframe values that represent color.\n */\nclass ColorKeyframeTrack extends KeyframeTrack {}\n\nColorKeyframeTrack.prototype.ValueTypeName = 'color';\n\n/**\n * A Track of numeric keyframe values.\n */\nclass NumberKeyframeTrack extends KeyframeTrack {}\n\nNumberKeyframeTrack.prototype.ValueTypeName = 'number';\n\n/**\n * Spherical linear unit quaternion interpolant.\n */\n\nclass QuaternionLinearInterpolant extends Interpolant {\n\n\tconstructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {\n\n\t\tsuper( parameterPositions, sampleValues, sampleSize, resultBuffer );\n\n\t}\n\n\tinterpolate_( i1, t0, t, t1 ) {\n\n\t\tconst result = this.resultBuffer,\n\t\t\tvalues = this.sampleValues,\n\t\t\tstride = this.valueSize,\n\n\t\t\talpha = ( t - t0 ) / ( t1 - t0 );\n\n\t\tlet offset = i1 * stride;\n\n\t\tfor ( let end = offset + stride; offset !== end; offset += 4 ) {\n\n\t\t\tQuaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );\n\n\t\t}\n\n\t\treturn result;\n\n\t}\n\n}\n\n/**\n * A Track of quaternion keyframe values.\n */\nclass QuaternionKeyframeTrack extends KeyframeTrack {\n\n\tInterpolantFactoryMethodLinear( result ) {\n\n\t\treturn new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );\n\n\t}\n\n}\n\nQuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';\n// ValueBufferType is inherited\nQuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;\nQuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;\n\n/**\n * A Track that interpolates Strings\n */\nclass StringKeyframeTrack extends KeyframeTrack {}\n\nStringKeyframeTrack.prototype.ValueTypeName = 'string';\nStringKeyframeTrack.prototype.ValueBufferType = Array;\nStringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;\nStringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;\nStringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;\n\n/**\n * A Track of vectored keyframe values.\n */\nclass VectorKeyframeTrack extends KeyframeTrack {}\n\nVectorKeyframeTrack.prototype.ValueTypeName = 'vector';\n\nclass AnimationClip {\n\n\tconstructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {\n\n\t\tthis.name = name;\n\t\tthis.tracks = tracks;\n\t\tthis.duration = duration;\n\t\tthis.blendMode = blendMode;\n\n\t\tthis.uuid = generateUUID();\n\n\t\t// this means it should figure out its duration by scanning the tracks\n\t\tif ( this.duration < 0 ) {\n\n\t\t\tthis.resetDuration();\n\n\t\t}\n\n\t}\n\n\n\tstatic parse( json ) {\n\n\t\tconst tracks = [],\n\t\t\tjsonTracks = json.tracks,\n\t\t\tframeTime = 1.0 / ( json.fps || 1.0 );\n\n\t\tfor ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {\n\n\t\t\ttracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );\n\n\t\t}\n\n\t\tconst clip = new this( json.name, json.duration, tracks, json.blendMode );\n\t\tclip.uuid = json.uuid;\n\n\t\treturn clip;\n\n\t}\n\n\tstatic toJSON( clip ) {\n\n\t\tconst tracks = [],\n\t\t\tclipTracks = clip.tracks;\n\n\t\tconst json = {\n\n\t\t\t'name': clip.name,\n\t\t\t'duration': clip.duration,\n\t\t\t'tracks': tracks,\n\t\t\t'uuid': clip.uuid,\n\t\t\t'blendMode': clip.blendMode\n\n\t\t};\n\n\t\tfor ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {\n\n\t\t\ttracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );\n\n\t\t}\n\n\t\treturn json;\n\n\t}\n\n\tstatic CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {\n\n\t\tconst numMorphTargets = morphTargetSequence.length;\n\t\tconst tracks = [];\n\n\t\tfor ( let i = 0; i < numMorphTargets; i ++ ) {\n\n\t\t\tlet times = [];\n\t\t\tlet values = [];\n\n\t\t\ttimes.push(\n\t\t\t\t( i + numMorphTargets - 1 ) % numMorphTargets,\n\t\t\t\ti,\n\t\t\t\t( i + 1 ) % numMorphTargets );\n\n\t\t\tvalues.push( 0, 1, 0 );\n\n\t\t\tconst order = getKeyframeOrder( times );\n\t\t\ttimes = sortedArray( times, 1, order );\n\t\t\tvalues = sortedArray( values, 1, order );\n\n\t\t\t// if there is a key at the first frame, duplicate it as the\n\t\t\t// last frame as well for perfect loop.\n\t\t\tif ( ! noLoop && times[ 0 ] === 0 ) {\n\n\t\t\t\ttimes.push( numMorphTargets );\n\t\t\t\tvalues.push( values[ 0 ] );\n\n\t\t\t}\n\n\t\t\ttracks.push(\n\t\t\t\tnew NumberKeyframeTrack(\n\t\t\t\t\t'.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',\n\t\t\t\t\ttimes, values\n\t\t\t\t).scale( 1.0 / fps ) );\n\n\t\t}\n\n\t\treturn new this( name, - 1, tracks );\n\n\t}\n\n\tstatic findByName( objectOrClipArray, name ) {\n\n\t\tlet clipArray = objectOrClipArray;\n\n\t\tif ( ! Array.isArray( objectOrClipArray ) ) {\n\n\t\t\tconst o = objectOrClipArray;\n\t\t\tclipArray = o.geometry && o.geometry.animations || o.animations;\n\n\t\t}\n\n\t\tfor ( let i = 0; i < clipArray.length; i ++ ) {\n\n\t\t\tif ( clipArray[ i ].name === name ) {\n\n\t\t\t\treturn clipArray[ i ];\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn null;\n\n\t}\n\n\tstatic CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {\n\n\t\tconst animationToMorphTargets = {};\n\n\t\t// tested with https://regex101.com/ on trick sequences\n\t\t// such flamingo_flyA_003, flamingo_run1_003, crdeath0059\n\t\tconst pattern = /^([\\w-]*?)([\\d]+)$/;\n\n\t\t// sort morph target names into animation groups based\n\t\t// patterns like Walk_001, Walk_002, Run_001, Run_002\n\t\tfor ( let i = 0, il = morphTargets.length; i < il; i ++ ) {\n\n\t\t\tconst morphTarget = morphTargets[ i ];\n\t\t\tconst parts = morphTarget.name.match( pattern );\n\n\t\t\tif ( parts && parts.length > 1 ) {\n\n\t\t\t\tconst name = parts[ 1 ];\n\n\t\t\t\tlet animationMorphTargets = animationToMorphTargets[ name ];\n\n\t\t\t\tif ( ! animationMorphTargets ) {\n\n\t\t\t\t\tanimationToMorphTargets[ name ] = animationMorphTargets = [];\n\n\t\t\t\t}\n\n\t\t\t\tanimationMorphTargets.push( morphTarget );\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst clips = [];\n\n\t\tfor ( const name in animationToMorphTargets ) {\n\n\t\t\tclips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );\n\n\t\t}\n\n\t\treturn clips;\n\n\t}\n\n\t// parse the animation.hierarchy format\n\tstatic parseAnimation( animation, bones ) {\n\n\t\tif ( ! animation ) {\n\n\t\t\tconsole.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );\n\t\t\treturn null;\n\n\t\t}\n\n\t\tconst addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {\n\n\t\t\t// only return track if there are actually keys.\n\t\t\tif ( animationKeys.length !== 0 ) {\n\n\t\t\t\tconst times = [];\n\t\t\t\tconst values = [];\n\n\t\t\t\tflattenJSON( animationKeys, times, values, propertyName );\n\n\t\t\t\t// empty keys are filtered out, so check again\n\t\t\t\tif ( times.length !== 0 ) {\n\n\t\t\t\t\tdestTracks.push( new trackType( trackName, times, values ) );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t};\n\n\t\tconst tracks = [];\n\n\t\tconst clipName = animation.name || 'default';\n\t\tconst fps = animation.fps || 30;\n\t\tconst blendMode = animation.blendMode;\n\n\t\t// automatic length determination in AnimationClip.\n\t\tlet duration = animation.length || - 1;\n\n\t\tconst hierarchyTracks = animation.hierarchy || [];\n\n\t\tfor ( let h = 0; h < hierarchyTracks.length; h ++ ) {\n\n\t\t\tconst animationKeys = hierarchyTracks[ h ].keys;\n\n\t\t\t// skip empty tracks\n\t\t\tif ( ! animationKeys || animationKeys.length === 0 ) continue;\n\n\t\t\t// process morph targets\n\t\t\tif ( animationKeys[ 0 ].morphTargets ) {\n\n\t\t\t\t// figure out all morph targets used in this track\n\t\t\t\tconst morphTargetNames = {};\n\n\t\t\t\tlet k;\n\n\t\t\t\tfor ( k = 0; k < animationKeys.length; k ++ ) {\n\n\t\t\t\t\tif ( animationKeys[ k ].morphTargets ) {\n\n\t\t\t\t\t\tfor ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {\n\n\t\t\t\t\t\t\tmorphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\t// create a track for each morph target with all zero\n\t\t\t\t// morphTargetInfluences except for the keys in which\n\t\t\t\t// the morphTarget is named.\n\t\t\t\tfor ( const morphTargetName in morphTargetNames ) {\n\n\t\t\t\t\tconst times = [];\n\t\t\t\t\tconst values = [];\n\n\t\t\t\t\tfor ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {\n\n\t\t\t\t\t\tconst animationKey = animationKeys[ k ];\n\n\t\t\t\t\t\ttimes.push( animationKey.time );\n\t\t\t\t\t\tvalues.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );\n\n\t\t\t\t\t}\n\n\t\t\t\t\ttracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );\n\n\t\t\t\t}\n\n\t\t\t\tduration = morphTargetNames.length * fps;\n\n\t\t\t} else {\n\n\t\t\t\t// ...assume skeletal animation\n\n\t\t\t\tconst boneName = '.bones[' + bones[ h ].name + ']';\n\n\t\t\t\taddNonemptyTrack(\n\t\t\t\t\tVectorKeyframeTrack, boneName + '.position',\n\t\t\t\t\tanimationKeys, 'pos', tracks );\n\n\t\t\t\taddNonemptyTrack(\n\t\t\t\t\tQuaternionKeyframeTrack, boneName + '.quaternion',\n\t\t\t\t\tanimationKeys, 'rot', tracks );\n\n\t\t\t\taddNonemptyTrack(\n\t\t\t\t\tVectorKeyframeTrack, boneName + '.scale',\n\t\t\t\t\tanimationKeys, 'scl', tracks );\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( tracks.length === 0 ) {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\tconst clip = new this( clipName, duration, tracks, blendMode );\n\n\t\treturn clip;\n\n\t}\n\n\tresetDuration() {\n\n\t\tconst tracks = this.tracks;\n\t\tlet duration = 0;\n\n\t\tfor ( let i = 0, n = tracks.length; i !== n; ++ i ) {\n\n\t\t\tconst track = this.tracks[ i ];\n\n\t\t\tduration = Math.max( duration, track.times[ track.times.length - 1 ] );\n\n\t\t}\n\n\t\tthis.duration = duration;\n\n\t\treturn this;\n\n\t}\n\n\ttrim() {\n\n\t\tfor ( let i = 0; i < this.tracks.length; i ++ ) {\n\n\t\t\tthis.tracks[ i ].trim( 0, this.duration );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tvalidate() {\n\n\t\tlet valid = true;\n\n\t\tfor ( let i = 0; i < this.tracks.length; i ++ ) {\n\n\t\t\tvalid = valid && this.tracks[ i ].validate();\n\n\t\t}\n\n\t\treturn valid;\n\n\t}\n\n\toptimize() {\n\n\t\tfor ( let i = 0; i < this.tracks.length; i ++ ) {\n\n\t\t\tthis.tracks[ i ].optimize();\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\tconst tracks = [];\n\n\t\tfor ( let i = 0; i < this.tracks.length; i ++ ) {\n\n\t\t\ttracks.push( this.tracks[ i ].clone() );\n\n\t\t}\n\n\t\treturn new this.constructor( this.name, this.duration, tracks, this.blendMode );\n\n\t}\n\n\ttoJSON() {\n\n\t\treturn this.constructor.toJSON( this );\n\n\t}\n\n}\n\nfunction getTrackTypeForValueTypeName( typeName ) {\n\n\tswitch ( typeName.toLowerCase() ) {\n\n\t\tcase 'scalar':\n\t\tcase 'double':\n\t\tcase 'float':\n\t\tcase 'number':\n\t\tcase 'integer':\n\n\t\t\treturn NumberKeyframeTrack;\n\n\t\tcase 'vector':\n\t\tcase 'vector2':\n\t\tcase 'vector3':\n\t\tcase 'vector4':\n\n\t\t\treturn VectorKeyframeTrack;\n\n\t\tcase 'color':\n\n\t\t\treturn ColorKeyframeTrack;\n\n\t\tcase 'quaternion':\n\n\t\t\treturn QuaternionKeyframeTrack;\n\n\t\tcase 'bool':\n\t\tcase 'boolean':\n\n\t\t\treturn BooleanKeyframeTrack;\n\n\t\tcase 'string':\n\n\t\t\treturn StringKeyframeTrack;\n\n\t}\n\n\tthrow new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );\n\n}\n\nfunction parseKeyframeTrack( json ) {\n\n\tif ( json.type === undefined ) {\n\n\t\tthrow new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );\n\n\t}\n\n\tconst trackType = getTrackTypeForValueTypeName( json.type );\n\n\tif ( json.times === undefined ) {\n\n\t\tconst times = [], values = [];\n\n\t\tflattenJSON( json.keys, times, values, 'value' );\n\n\t\tjson.times = times;\n\t\tjson.values = values;\n\n\t}\n\n\t// derived classes can define a static parse method\n\tif ( trackType.parse !== undefined ) {\n\n\t\treturn trackType.parse( json );\n\n\t} else {\n\n\t\t// by default, we assume a constructor compatible with the base\n\t\treturn new trackType( json.name, json.times, json.values, json.interpolation );\n\n\t}\n\n}\n\nconst Cache = {\n\n\tenabled: false,\n\n\tfiles: {},\n\n\tadd: function ( key, file ) {\n\n\t\tif ( this.enabled === false ) return;\n\n\t\t// console.log( 'THREE.Cache', 'Adding key:', key );\n\n\t\tthis.files[ key ] = file;\n\n\t},\n\n\tget: function ( key ) {\n\n\t\tif ( this.enabled === false ) return;\n\n\t\t// console.log( 'THREE.Cache', 'Checking key:', key );\n\n\t\treturn this.files[ key ];\n\n\t},\n\n\tremove: function ( key ) {\n\n\t\tdelete this.files[ key ];\n\n\t},\n\n\tclear: function () {\n\n\t\tthis.files = {};\n\n\t}\n\n};\n\nclass LoadingManager {\n\n\tconstructor( onLoad, onProgress, onError ) {\n\n\t\tconst scope = this;\n\n\t\tlet isLoading = false;\n\t\tlet itemsLoaded = 0;\n\t\tlet itemsTotal = 0;\n\t\tlet urlModifier = undefined;\n\t\tconst handlers = [];\n\n\t\t// Refer to #5689 for the reason why we don't set .onStart\n\t\t// in the constructor\n\n\t\tthis.onStart = undefined;\n\t\tthis.onLoad = onLoad;\n\t\tthis.onProgress = onProgress;\n\t\tthis.onError = onError;\n\n\t\tthis.itemStart = function ( url ) {\n\n\t\t\titemsTotal ++;\n\n\t\t\tif ( isLoading === false ) {\n\n\t\t\t\tif ( scope.onStart !== undefined ) {\n\n\t\t\t\t\tscope.onStart( url, itemsLoaded, itemsTotal );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tisLoading = true;\n\n\t\t};\n\n\t\tthis.itemEnd = function ( url ) {\n\n\t\t\titemsLoaded ++;\n\n\t\t\tif ( scope.onProgress !== undefined ) {\n\n\t\t\t\tscope.onProgress( url, itemsLoaded, itemsTotal );\n\n\t\t\t}\n\n\t\t\tif ( itemsLoaded === itemsTotal ) {\n\n\t\t\t\tisLoading = false;\n\n\t\t\t\tif ( scope.onLoad !== undefined ) {\n\n\t\t\t\t\tscope.onLoad();\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t};\n\n\t\tthis.itemError = function ( url ) {\n\n\t\t\tif ( scope.onError !== undefined ) {\n\n\t\t\t\tscope.onError( url );\n\n\t\t\t}\n\n\t\t};\n\n\t\tthis.resolveURL = function ( url ) {\n\n\t\t\tif ( urlModifier ) {\n\n\t\t\t\treturn urlModifier( url );\n\n\t\t\t}\n\n\t\t\treturn url;\n\n\t\t};\n\n\t\tthis.setURLModifier = function ( transform ) {\n\n\t\t\turlModifier = transform;\n\n\t\t\treturn this;\n\n\t\t};\n\n\t\tthis.addHandler = function ( regex, loader ) {\n\n\t\t\thandlers.push( regex, loader );\n\n\t\t\treturn this;\n\n\t\t};\n\n\t\tthis.removeHandler = function ( regex ) {\n\n\t\t\tconst index = handlers.indexOf( regex );\n\n\t\t\tif ( index !== - 1 ) {\n\n\t\t\t\thandlers.splice( index, 2 );\n\n\t\t\t}\n\n\t\t\treturn this;\n\n\t\t};\n\n\t\tthis.getHandler = function ( file ) {\n\n\t\t\tfor ( let i = 0, l = handlers.length; i < l; i += 2 ) {\n\n\t\t\t\tconst regex = handlers[ i ];\n\t\t\t\tconst loader = handlers[ i + 1 ];\n\n\t\t\t\tif ( regex.global ) regex.lastIndex = 0; // see #17920\n\n\t\t\t\tif ( regex.test( file ) ) {\n\n\t\t\t\t\treturn loader;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn null;\n\n\t\t};\n\n\t}\n\n}\n\nconst DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();\n\nclass Loader {\n\n\tconstructor( manager ) {\n\n\t\tthis.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;\n\n\t\tthis.crossOrigin = 'anonymous';\n\t\tthis.withCredentials = false;\n\t\tthis.path = '';\n\t\tthis.resourcePath = '';\n\t\tthis.requestHeader = {};\n\n\t}\n\n\tload( /* url, onLoad, onProgress, onError */ ) {}\n\n\tloadAsync( url, onProgress ) {\n\n\t\tconst scope = this;\n\n\t\treturn new Promise( function ( resolve, reject ) {\n\n\t\t\tscope.load( url, resolve, onProgress, reject );\n\n\t\t} );\n\n\t}\n\n\tparse( /* data */ ) {}\n\n\tsetCrossOrigin( crossOrigin ) {\n\n\t\tthis.crossOrigin = crossOrigin;\n\t\treturn this;\n\n\t}\n\n\tsetWithCredentials( value ) {\n\n\t\tthis.withCredentials = value;\n\t\treturn this;\n\n\t}\n\n\tsetPath( path ) {\n\n\t\tthis.path = path;\n\t\treturn this;\n\n\t}\n\n\tsetResourcePath( resourcePath ) {\n\n\t\tthis.resourcePath = resourcePath;\n\t\treturn this;\n\n\t}\n\n\tsetRequestHeader( requestHeader ) {\n\n\t\tthis.requestHeader = requestHeader;\n\t\treturn this;\n\n\t}\n\n}\n\nconst loading = {};\n\nclass HttpError extends Error {\n\n\tconstructor( message, response ) {\n\n\t\tsuper( message );\n\t\tthis.response = response;\n\n\t}\n\n}\n\nclass FileLoader extends Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tif ( url === undefined ) url = '';\n\n\t\tif ( this.path !== undefined ) url = this.path + url;\n\n\t\turl = this.manager.resolveURL( url );\n\n\t\tconst cached = Cache.get( url );\n\n\t\tif ( cached !== undefined ) {\n\n\t\t\tthis.manager.itemStart( url );\n\n\t\t\tsetTimeout( () => {\n\n\t\t\t\tif ( onLoad ) onLoad( cached );\n\n\t\t\t\tthis.manager.itemEnd( url );\n\n\t\t\t}, 0 );\n\n\t\t\treturn cached;\n\n\t\t}\n\n\t\t// Check if request is duplicate\n\n\t\tif ( loading[ url ] !== undefined ) {\n\n\t\t\tloading[ url ].push( {\n\n\t\t\t\tonLoad: onLoad,\n\t\t\t\tonProgress: onProgress,\n\t\t\t\tonError: onError\n\n\t\t\t} );\n\n\t\t\treturn;\n\n\t\t}\n\n\t\t// Initialise array for duplicate requests\n\t\tloading[ url ] = [];\n\n\t\tloading[ url ].push( {\n\t\t\tonLoad: onLoad,\n\t\t\tonProgress: onProgress,\n\t\t\tonError: onError,\n\t\t} );\n\n\t\t// create request\n\t\tconst req = new Request( url, {\n\t\t\theaders: new Headers( this.requestHeader ),\n\t\t\tcredentials: this.withCredentials ? 'include' : 'same-origin',\n\t\t\t// An abort controller could be added within a future PR\n\t\t} );\n\n\t\t// record states ( avoid data race )\n\t\tconst mimeType = this.mimeType;\n\t\tconst responseType = this.responseType;\n\n\t\t// start the fetch\n\t\tfetch( req )\n\t\t\t.then( response => {\n\n\t\t\t\tif ( response.status === 200 || response.status === 0 ) {\n\n\t\t\t\t\t// Some browsers return HTTP Status 0 when using non-http protocol\n\t\t\t\t\t// e.g. 'file://' or 'data://'. Handle as success.\n\n\t\t\t\t\tif ( response.status === 0 ) {\n\n\t\t\t\t\t\tconsole.warn( 'THREE.FileLoader: HTTP Status 0 received.' );\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// Workaround: Checking if response.body === undefined for Alipay browser #23548\n\n\t\t\t\t\tif ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {\n\n\t\t\t\t\t\treturn response;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tconst callbacks = loading[ url ];\n\t\t\t\t\tconst reader = response.body.getReader();\n\n\t\t\t\t\t// Nginx needs X-File-Size check\n\t\t\t\t\t// https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content\n\t\t\t\t\tconst contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );\n\t\t\t\t\tconst total = contentLength ? parseInt( contentLength ) : 0;\n\t\t\t\t\tconst lengthComputable = total !== 0;\n\t\t\t\t\tlet loaded = 0;\n\n\t\t\t\t\t// periodically read data into the new stream tracking while download progress\n\t\t\t\t\tconst stream = new ReadableStream( {\n\t\t\t\t\t\tstart( controller ) {\n\n\t\t\t\t\t\t\treadData();\n\n\t\t\t\t\t\t\tfunction readData() {\n\n\t\t\t\t\t\t\t\treader.read().then( ( { done, value } ) => {\n\n\t\t\t\t\t\t\t\t\tif ( done ) {\n\n\t\t\t\t\t\t\t\t\t\tcontroller.close();\n\n\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\tloaded += value.byteLength;\n\n\t\t\t\t\t\t\t\t\t\tconst event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );\n\t\t\t\t\t\t\t\t\t\tfor ( let i = 0, il = callbacks.length; i < il; i ++ ) {\n\n\t\t\t\t\t\t\t\t\t\t\tconst callback = callbacks[ i ];\n\t\t\t\t\t\t\t\t\t\t\tif ( callback.onProgress ) callback.onProgress( event );\n\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue( value );\n\t\t\t\t\t\t\t\t\t\treadData();\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t} );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} );\n\n\t\t\t\t\treturn new Response( stream );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tthrow new HttpError( `fetch for \"${response.url}\" responded with ${response.status}: ${response.statusText}`, response );\n\n\t\t\t\t}\n\n\t\t\t} )\n\t\t\t.then( response => {\n\n\t\t\t\tswitch ( responseType ) {\n\n\t\t\t\t\tcase 'arraybuffer':\n\n\t\t\t\t\t\treturn response.arrayBuffer();\n\n\t\t\t\t\tcase 'blob':\n\n\t\t\t\t\t\treturn response.blob();\n\n\t\t\t\t\tcase 'document':\n\n\t\t\t\t\t\treturn response.text()\n\t\t\t\t\t\t\t.then( text => {\n\n\t\t\t\t\t\t\t\tconst parser = new DOMParser();\n\t\t\t\t\t\t\t\treturn parser.parseFromString( text, mimeType );\n\n\t\t\t\t\t\t\t} );\n\n\t\t\t\t\tcase 'json':\n\n\t\t\t\t\t\treturn response.json();\n\n\t\t\t\t\tdefault:\n\n\t\t\t\t\t\tif ( mimeType === undefined ) {\n\n\t\t\t\t\t\t\treturn response.text();\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t// sniff encoding\n\t\t\t\t\t\t\tconst re = /charset=\"?([^;\"\\s]*)\"?/i;\n\t\t\t\t\t\t\tconst exec = re.exec( mimeType );\n\t\t\t\t\t\t\tconst label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;\n\t\t\t\t\t\t\tconst decoder = new TextDecoder( label );\n\t\t\t\t\t\t\treturn response.arrayBuffer().then( ab => decoder.decode( ab ) );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} )\n\t\t\t.then( data => {\n\n\t\t\t\t// Add to cache only on HTTP success, so that we do not cache\n\t\t\t\t// error response bodies as proper responses to requests.\n\t\t\t\tCache.add( url, data );\n\n\t\t\t\tconst callbacks = loading[ url ];\n\t\t\t\tdelete loading[ url ];\n\n\t\t\t\tfor ( let i = 0, il = callbacks.length; i < il; i ++ ) {\n\n\t\t\t\t\tconst callback = callbacks[ i ];\n\t\t\t\t\tif ( callback.onLoad ) callback.onLoad( data );\n\n\t\t\t\t}\n\n\t\t\t} )\n\t\t\t.catch( err => {\n\n\t\t\t\t// Abort errors and other errors are handled the same\n\n\t\t\t\tconst callbacks = loading[ url ];\n\n\t\t\t\tif ( callbacks === undefined ) {\n\n\t\t\t\t\t// When onLoad was called and url was deleted in `loading`\n\t\t\t\t\tthis.manager.itemError( url );\n\t\t\t\t\tthrow err;\n\n\t\t\t\t}\n\n\t\t\t\tdelete loading[ url ];\n\n\t\t\t\tfor ( let i = 0, il = callbacks.length; i < il; i ++ ) {\n\n\t\t\t\t\tconst callback = callbacks[ i ];\n\t\t\t\t\tif ( callback.onError ) callback.onError( err );\n\n\t\t\t\t}\n\n\t\t\t\tthis.manager.itemError( url );\n\n\t\t\t} )\n\t\t\t.finally( () => {\n\n\t\t\t\tthis.manager.itemEnd( url );\n\n\t\t\t} );\n\n\t\tthis.manager.itemStart( url );\n\n\t}\n\n\tsetResponseType( value ) {\n\n\t\tthis.responseType = value;\n\t\treturn this;\n\n\t}\n\n\tsetMimeType( value ) {\n\n\t\tthis.mimeType = value;\n\t\treturn this;\n\n\t}\n\n}\n\nclass AnimationLoader extends Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tconst scope = this;\n\n\t\tconst loader = new FileLoader( this.manager );\n\t\tloader.setPath( this.path );\n\t\tloader.setRequestHeader( this.requestHeader );\n\t\tloader.setWithCredentials( this.withCredentials );\n\t\tloader.load( url, function ( text ) {\n\n\t\t\ttry {\n\n\t\t\t\tonLoad( scope.parse( JSON.parse( text ) ) );\n\n\t\t\t} catch ( e ) {\n\n\t\t\t\tif ( onError ) {\n\n\t\t\t\t\tonError( e );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tconsole.error( e );\n\n\t\t\t\t}\n\n\t\t\t\tscope.manager.itemError( url );\n\n\t\t\t}\n\n\t\t}, onProgress, onError );\n\n\t}\n\n\tparse( json ) {\n\n\t\tconst animations = [];\n\n\t\tfor ( let i = 0; i < json.length; i ++ ) {\n\n\t\t\tconst clip = AnimationClip.parse( json[ i ] );\n\n\t\t\tanimations.push( clip );\n\n\t\t}\n\n\t\treturn animations;\n\n\t}\n\n}\n\n/**\n * Abstract Base class to block based textures loader (dds, pvr, ...)\n *\n * Sub classes have to implement the parse() method which will be used in load().\n */\n\nclass CompressedTextureLoader extends Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tconst scope = this;\n\n\t\tconst images = [];\n\n\t\tconst texture = new CompressedTexture();\n\n\t\tconst loader = new FileLoader( this.manager );\n\t\tloader.setPath( this.path );\n\t\tloader.setResponseType( 'arraybuffer' );\n\t\tloader.setRequestHeader( this.requestHeader );\n\t\tloader.setWithCredentials( scope.withCredentials );\n\n\t\tlet loaded = 0;\n\n\t\tfunction loadTexture( i ) {\n\n\t\t\tloader.load( url[ i ], function ( buffer ) {\n\n\t\t\t\tconst texDatas = scope.parse( buffer, true );\n\n\t\t\t\timages[ i ] = {\n\t\t\t\t\twidth: texDatas.width,\n\t\t\t\t\theight: texDatas.height,\n\t\t\t\t\tformat: texDatas.format,\n\t\t\t\t\tmipmaps: texDatas.mipmaps\n\t\t\t\t};\n\n\t\t\t\tloaded += 1;\n\n\t\t\t\tif ( loaded === 6 ) {\n\n\t\t\t\t\tif ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;\n\n\t\t\t\t\ttexture.image = images;\n\t\t\t\t\ttexture.format = texDatas.format;\n\t\t\t\t\ttexture.needsUpdate = true;\n\n\t\t\t\t\tif ( onLoad ) onLoad( texture );\n\n\t\t\t\t}\n\n\t\t\t}, onProgress, onError );\n\n\t\t}\n\n\t\tif ( Array.isArray( url ) ) {\n\n\t\t\tfor ( let i = 0, il = url.length; i < il; ++ i ) {\n\n\t\t\t\tloadTexture( i );\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\t// compressed cubemap texture stored in a single DDS file\n\n\t\t\tloader.load( url, function ( buffer ) {\n\n\t\t\t\tconst texDatas = scope.parse( buffer, true );\n\n\t\t\t\tif ( texDatas.isCubemap ) {\n\n\t\t\t\t\tconst faces = texDatas.mipmaps.length / texDatas.mipmapCount;\n\n\t\t\t\t\tfor ( let f = 0; f < faces; f ++ ) {\n\n\t\t\t\t\t\timages[ f ] = { mipmaps: [] };\n\n\t\t\t\t\t\tfor ( let i = 0; i < texDatas.mipmapCount; i ++ ) {\n\n\t\t\t\t\t\t\timages[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );\n\t\t\t\t\t\t\timages[ f ].format = texDatas.format;\n\t\t\t\t\t\t\timages[ f ].width = texDatas.width;\n\t\t\t\t\t\t\timages[ f ].height = texDatas.height;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\ttexture.image = images;\n\n\t\t\t\t} else {\n\n\t\t\t\t\ttexture.image.width = texDatas.width;\n\t\t\t\t\ttexture.image.height = texDatas.height;\n\t\t\t\t\ttexture.mipmaps = texDatas.mipmaps;\n\n\t\t\t\t}\n\n\t\t\t\tif ( texDatas.mipmapCount === 1 ) {\n\n\t\t\t\t\ttexture.minFilter = LinearFilter;\n\n\t\t\t\t}\n\n\t\t\t\ttexture.format = texDatas.format;\n\t\t\t\ttexture.needsUpdate = true;\n\n\t\t\t\tif ( onLoad ) onLoad( texture );\n\n\t\t\t}, onProgress, onError );\n\n\t\t}\n\n\t\treturn texture;\n\n\t}\n\n}\n\nclass ImageLoader extends Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tif ( this.path !== undefined ) url = this.path + url;\n\n\t\turl = this.manager.resolveURL( url );\n\n\t\tconst scope = this;\n\n\t\tconst cached = Cache.get( url );\n\n\t\tif ( cached !== undefined ) {\n\n\t\t\tscope.manager.itemStart( url );\n\n\t\t\tsetTimeout( function () {\n\n\t\t\t\tif ( onLoad ) onLoad( cached );\n\n\t\t\t\tscope.manager.itemEnd( url );\n\n\t\t\t}, 0 );\n\n\t\t\treturn cached;\n\n\t\t}\n\n\t\tconst image = createElementNS( 'img' );\n\n\t\tfunction onImageLoad() {\n\n\t\t\tremoveEventListeners();\n\n\t\t\tCache.add( url, this );\n\n\t\t\tif ( onLoad ) onLoad( this );\n\n\t\t\tscope.manager.itemEnd( url );\n\n\t\t}\n\n\t\tfunction onImageError( event ) {\n\n\t\t\tremoveEventListeners();\n\n\t\t\tif ( onError ) onError( event );\n\n\t\t\tscope.manager.itemError( url );\n\t\t\tscope.manager.itemEnd( url );\n\n\t\t}\n\n\t\tfunction removeEventListeners() {\n\n\t\t\timage.removeEventListener( 'load', onImageLoad, false );\n\t\t\timage.removeEventListener( 'error', onImageError, false );\n\n\t\t}\n\n\t\timage.addEventListener( 'load', onImageLoad, false );\n\t\timage.addEventListener( 'error', onImageError, false );\n\n\t\tif ( url.slice( 0, 5 ) !== 'data:' ) {\n\n\t\t\tif ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;\n\n\t\t}\n\n\t\tscope.manager.itemStart( url );\n\n\t\timage.src = url;\n\n\t\treturn image;\n\n\t}\n\n}\n\nclass CubeTextureLoader extends Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t}\n\n\tload( urls, onLoad, onProgress, onError ) {\n\n\t\tconst texture = new CubeTexture();\n\n\t\tconst loader = new ImageLoader( this.manager );\n\t\tloader.setCrossOrigin( this.crossOrigin );\n\t\tloader.setPath( this.path );\n\n\t\tlet loaded = 0;\n\n\t\tfunction loadTexture( i ) {\n\n\t\t\tloader.load( urls[ i ], function ( image ) {\n\n\t\t\t\ttexture.images[ i ] = image;\n\n\t\t\t\tloaded ++;\n\n\t\t\t\tif ( loaded === 6 ) {\n\n\t\t\t\t\ttexture.needsUpdate = true;\n\n\t\t\t\t\tif ( onLoad ) onLoad( texture );\n\n\t\t\t\t}\n\n\t\t\t}, undefined, onError );\n\n\t\t}\n\n\t\tfor ( let i = 0; i < urls.length; ++ i ) {\n\n\t\t\tloadTexture( i );\n\n\t\t}\n\n\t\treturn texture;\n\n\t}\n\n}\n\n/**\n * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)\n *\n * Sub classes have to implement the parse() method which will be used in load().\n */\n\nclass DataTextureLoader extends Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tconst scope = this;\n\n\t\tconst texture = new DataTexture();\n\n\t\tconst loader = new FileLoader( this.manager );\n\t\tloader.setResponseType( 'arraybuffer' );\n\t\tloader.setRequestHeader( this.requestHeader );\n\t\tloader.setPath( this.path );\n\t\tloader.setWithCredentials( scope.withCredentials );\n\t\tloader.load( url, function ( buffer ) {\n\n\t\t\tconst texData = scope.parse( buffer );\n\n\t\t\tif ( ! texData ) return;\n\n\t\t\tif ( texData.image !== undefined ) {\n\n\t\t\t\ttexture.image = texData.image;\n\n\t\t\t} else if ( texData.data !== undefined ) {\n\n\t\t\t\ttexture.image.width = texData.width;\n\t\t\t\ttexture.image.height = texData.height;\n\t\t\t\ttexture.image.data = texData.data;\n\n\t\t\t}\n\n\t\t\ttexture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;\n\t\t\ttexture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;\n\n\t\t\ttexture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;\n\t\t\ttexture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;\n\n\t\t\ttexture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;\n\n\t\t\tif ( texData.colorSpace !== undefined ) {\n\n\t\t\t\ttexture.colorSpace = texData.colorSpace;\n\n\t\t\t} else if ( texData.encoding !== undefined ) { // @deprecated, r152\n\n\t\t\t\ttexture.encoding = texData.encoding;\n\n\t\t\t}\n\n\t\t\tif ( texData.flipY !== undefined ) {\n\n\t\t\t\ttexture.flipY = texData.flipY;\n\n\t\t\t}\n\n\t\t\tif ( texData.format !== undefined ) {\n\n\t\t\t\ttexture.format = texData.format;\n\n\t\t\t}\n\n\t\t\tif ( texData.type !== undefined ) {\n\n\t\t\t\ttexture.type = texData.type;\n\n\t\t\t}\n\n\t\t\tif ( texData.mipmaps !== undefined ) {\n\n\t\t\t\ttexture.mipmaps = texData.mipmaps;\n\t\t\t\ttexture.minFilter = LinearMipmapLinearFilter; // presumably...\n\n\t\t\t}\n\n\t\t\tif ( texData.mipmapCount === 1 ) {\n\n\t\t\t\ttexture.minFilter = LinearFilter;\n\n\t\t\t}\n\n\t\t\tif ( texData.generateMipmaps !== undefined ) {\n\n\t\t\t\ttexture.generateMipmaps = texData.generateMipmaps;\n\n\t\t\t}\n\n\t\t\ttexture.needsUpdate = true;\n\n\t\t\tif ( onLoad ) onLoad( texture, texData );\n\n\t\t}, onProgress, onError );\n\n\n\t\treturn texture;\n\n\t}\n\n}\n\nclass TextureLoader extends Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tconst texture = new Texture();\n\n\t\tconst loader = new ImageLoader( this.manager );\n\t\tloader.setCrossOrigin( this.crossOrigin );\n\t\tloader.setPath( this.path );\n\n\t\tloader.load( url, function ( image ) {\n\n\t\t\ttexture.image = image;\n\t\t\ttexture.needsUpdate = true;\n\n\t\t\tif ( onLoad !== undefined ) {\n\n\t\t\t\tonLoad( texture );\n\n\t\t\t}\n\n\t\t}, onProgress, onError );\n\n\t\treturn texture;\n\n\t}\n\n}\n\nclass Light extends Object3D {\n\n\tconstructor( color, intensity = 1 ) {\n\n\t\tsuper();\n\n\t\tthis.isLight = true;\n\n\t\tthis.type = 'Light';\n\n\t\tthis.color = new Color( color );\n\t\tthis.intensity = intensity;\n\n\t}\n\n\tdispose() {\n\n\t\t// Empty here in base class; some subclasses override.\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tthis.color.copy( source.color );\n\t\tthis.intensity = source.intensity;\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON( meta ) {\n\n\t\tconst data = super.toJSON( meta );\n\n\t\tdata.object.color = this.color.getHex();\n\t\tdata.object.intensity = this.intensity;\n\n\t\tif ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();\n\n\t\tif ( this.distance !== undefined ) data.object.distance = this.distance;\n\t\tif ( this.angle !== undefined ) data.object.angle = this.angle;\n\t\tif ( this.decay !== undefined ) data.object.decay = this.decay;\n\t\tif ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;\n\n\t\tif ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();\n\n\t\treturn data;\n\n\t}\n\n}\n\nclass HemisphereLight extends Light {\n\n\tconstructor( skyColor, groundColor, intensity ) {\n\n\t\tsuper( skyColor, intensity );\n\n\t\tthis.isHemisphereLight = true;\n\n\t\tthis.type = 'HemisphereLight';\n\n\t\tthis.position.copy( Object3D.DEFAULT_UP );\n\t\tthis.updateMatrix();\n\n\t\tthis.groundColor = new Color( groundColor );\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tthis.groundColor.copy( source.groundColor );\n\n\t\treturn this;\n\n\t}\n\n}\n\nconst _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();\nconst _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();\nconst _lookTarget$1 = /*@__PURE__*/ new Vector3();\n\nclass LightShadow {\n\n\tconstructor( camera ) {\n\n\t\tthis.camera = camera;\n\n\t\tthis.bias = 0;\n\t\tthis.normalBias = 0;\n\t\tthis.radius = 1;\n\t\tthis.blurSamples = 8;\n\n\t\tthis.mapSize = new Vector2( 512, 512 );\n\n\t\tthis.map = null;\n\t\tthis.mapPass = null;\n\t\tthis.matrix = new Matrix4();\n\n\t\tthis.autoUpdate = true;\n\t\tthis.needsUpdate = false;\n\n\t\tthis._frustum = new Frustum();\n\t\tthis._frameExtents = new Vector2( 1, 1 );\n\n\t\tthis._viewportCount = 1;\n\n\t\tthis._viewports = [\n\n\t\t\tnew Vector4( 0, 0, 1, 1 )\n\n\t\t];\n\n\t}\n\n\tgetViewportCount() {\n\n\t\treturn this._viewportCount;\n\n\t}\n\n\tgetFrustum() {\n\n\t\treturn this._frustum;\n\n\t}\n\n\tupdateMatrices( light ) {\n\n\t\tconst shadowCamera = this.camera;\n\t\tconst shadowMatrix = this.matrix;\n\n\t\t_lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );\n\t\tshadowCamera.position.copy( _lightPositionWorld$1 );\n\n\t\t_lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );\n\t\tshadowCamera.lookAt( _lookTarget$1 );\n\t\tshadowCamera.updateMatrixWorld();\n\n\t\t_projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );\n\t\tthis._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );\n\n\t\tshadowMatrix.set(\n\t\t\t0.5, 0.0, 0.0, 0.5,\n\t\t\t0.0, 0.5, 0.0, 0.5,\n\t\t\t0.0, 0.0, 0.5, 0.5,\n\t\t\t0.0, 0.0, 0.0, 1.0\n\t\t);\n\n\t\tshadowMatrix.multiply( _projScreenMatrix$1 );\n\n\t}\n\n\tgetViewport( viewportIndex ) {\n\n\t\treturn this._viewports[ viewportIndex ];\n\n\t}\n\n\tgetFrameExtents() {\n\n\t\treturn this._frameExtents;\n\n\t}\n\n\tdispose() {\n\n\t\tif ( this.map ) {\n\n\t\t\tthis.map.dispose();\n\n\t\t}\n\n\t\tif ( this.mapPass ) {\n\n\t\t\tthis.mapPass.dispose();\n\n\t\t}\n\n\t}\n\n\tcopy( source ) {\n\n\t\tthis.camera = source.camera.clone();\n\n\t\tthis.bias = source.bias;\n\t\tthis.radius = source.radius;\n\n\t\tthis.mapSize.copy( source.mapSize );\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst object = {};\n\n\t\tif ( this.bias !== 0 ) object.bias = this.bias;\n\t\tif ( this.normalBias !== 0 ) object.normalBias = this.normalBias;\n\t\tif ( this.radius !== 1 ) object.radius = this.radius;\n\t\tif ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();\n\n\t\tobject.camera = this.camera.toJSON( false ).object;\n\t\tdelete object.camera.matrix;\n\n\t\treturn object;\n\n\t}\n\n}\n\nclass SpotLightShadow extends LightShadow {\n\n\tconstructor() {\n\n\t\tsuper( new PerspectiveCamera( 50, 1, 0.5, 500 ) );\n\n\t\tthis.isSpotLightShadow = true;\n\n\t\tthis.focus = 1;\n\n\t}\n\n\tupdateMatrices( light ) {\n\n\t\tconst camera = this.camera;\n\n\t\tconst fov = RAD2DEG * 2 * light.angle * this.focus;\n\t\tconst aspect = this.mapSize.width / this.mapSize.height;\n\t\tconst far = light.distance || camera.far;\n\n\t\tif ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {\n\n\t\t\tcamera.fov = fov;\n\t\t\tcamera.aspect = aspect;\n\t\t\tcamera.far = far;\n\t\t\tcamera.updateProjectionMatrix();\n\n\t\t}\n\n\t\tsuper.updateMatrices( light );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.focus = source.focus;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass SpotLight extends Light {\n\n\tconstructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {\n\n\t\tsuper( color, intensity );\n\n\t\tthis.isSpotLight = true;\n\n\t\tthis.type = 'SpotLight';\n\n\t\tthis.position.copy( Object3D.DEFAULT_UP );\n\t\tthis.updateMatrix();\n\n\t\tthis.target = new Object3D();\n\n\t\tthis.distance = distance;\n\t\tthis.angle = angle;\n\t\tthis.penumbra = penumbra;\n\t\tthis.decay = decay;\n\n\t\tthis.map = null;\n\n\t\tthis.shadow = new SpotLightShadow();\n\n\t}\n\n\tget power() {\n\n\t\t// compute the light's luminous power (in lumens) from its intensity (in candela)\n\t\t// by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)\n\t\treturn this.intensity * Math.PI;\n\n\t}\n\n\tset power( power ) {\n\n\t\t// set the light's intensity (in candela) from the desired luminous power (in lumens)\n\t\tthis.intensity = power / Math.PI;\n\n\t}\n\n\tdispose() {\n\n\t\tthis.shadow.dispose();\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tthis.distance = source.distance;\n\t\tthis.angle = source.angle;\n\t\tthis.penumbra = source.penumbra;\n\t\tthis.decay = source.decay;\n\n\t\tthis.target = source.target.clone();\n\n\t\tthis.shadow = source.shadow.clone();\n\n\t\treturn this;\n\n\t}\n\n}\n\nconst _projScreenMatrix = /*@__PURE__*/ new Matrix4();\nconst _lightPositionWorld = /*@__PURE__*/ new Vector3();\nconst _lookTarget = /*@__PURE__*/ new Vector3();\n\nclass PointLightShadow extends LightShadow {\n\n\tconstructor() {\n\n\t\tsuper( new PerspectiveCamera( 90, 1, 0.5, 500 ) );\n\n\t\tthis.isPointLightShadow = true;\n\n\t\tthis._frameExtents = new Vector2( 4, 2 );\n\n\t\tthis._viewportCount = 6;\n\n\t\tthis._viewports = [\n\t\t\t// These viewports map a cube-map onto a 2D texture with the\n\t\t\t// following orientation:\n\t\t\t//\n\t\t\t// xzXZ\n\t\t\t// y Y\n\t\t\t//\n\t\t\t// X - Positive x direction\n\t\t\t// x - Negative x direction\n\t\t\t// Y - Positive y direction\n\t\t\t// y - Negative y direction\n\t\t\t// Z - Positive z direction\n\t\t\t// z - Negative z direction\n\n\t\t\t// positive X\n\t\t\tnew Vector4( 2, 1, 1, 1 ),\n\t\t\t// negative X\n\t\t\tnew Vector4( 0, 1, 1, 1 ),\n\t\t\t// positive Z\n\t\t\tnew Vector4( 3, 1, 1, 1 ),\n\t\t\t// negative Z\n\t\t\tnew Vector4( 1, 1, 1, 1 ),\n\t\t\t// positive Y\n\t\t\tnew Vector4( 3, 0, 1, 1 ),\n\t\t\t// negative Y\n\t\t\tnew Vector4( 1, 0, 1, 1 )\n\t\t];\n\n\t\tthis._cubeDirections = [\n\t\t\tnew Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),\n\t\t\tnew Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )\n\t\t];\n\n\t\tthis._cubeUps = [\n\t\t\tnew Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),\n\t\t\tnew Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ),\tnew Vector3( 0, 0, - 1 )\n\t\t];\n\n\t}\n\n\tupdateMatrices( light, viewportIndex = 0 ) {\n\n\t\tconst camera = this.camera;\n\t\tconst shadowMatrix = this.matrix;\n\n\t\tconst far = light.distance || camera.far;\n\n\t\tif ( far !== camera.far ) {\n\n\t\t\tcamera.far = far;\n\t\t\tcamera.updateProjectionMatrix();\n\n\t\t}\n\n\t\t_lightPositionWorld.setFromMatrixPosition( light.matrixWorld );\n\t\tcamera.position.copy( _lightPositionWorld );\n\n\t\t_lookTarget.copy( camera.position );\n\t\t_lookTarget.add( this._cubeDirections[ viewportIndex ] );\n\t\tcamera.up.copy( this._cubeUps[ viewportIndex ] );\n\t\tcamera.lookAt( _lookTarget );\n\t\tcamera.updateMatrixWorld();\n\n\t\tshadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );\n\n\t\t_projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );\n\t\tthis._frustum.setFromProjectionMatrix( _projScreenMatrix );\n\n\t}\n\n}\n\nclass PointLight extends Light {\n\n\tconstructor( color, intensity, distance = 0, decay = 2 ) {\n\n\t\tsuper( color, intensity );\n\n\t\tthis.isPointLight = true;\n\n\t\tthis.type = 'PointLight';\n\n\t\tthis.distance = distance;\n\t\tthis.decay = decay;\n\n\t\tthis.shadow = new PointLightShadow();\n\n\t}\n\n\tget power() {\n\n\t\t// compute the light's luminous power (in lumens) from its intensity (in candela)\n\t\t// for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)\n\t\treturn this.intensity * 4 * Math.PI;\n\n\t}\n\n\tset power( power ) {\n\n\t\t// set the light's intensity (in candela) from the desired luminous power (in lumens)\n\t\tthis.intensity = power / ( 4 * Math.PI );\n\n\t}\n\n\tdispose() {\n\n\t\tthis.shadow.dispose();\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tthis.distance = source.distance;\n\t\tthis.decay = source.decay;\n\n\t\tthis.shadow = source.shadow.clone();\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass DirectionalLightShadow extends LightShadow {\n\n\tconstructor() {\n\n\t\tsuper( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );\n\n\t\tthis.isDirectionalLightShadow = true;\n\n\t}\n\n}\n\nclass DirectionalLight extends Light {\n\n\tconstructor( color, intensity ) {\n\n\t\tsuper( color, intensity );\n\n\t\tthis.isDirectionalLight = true;\n\n\t\tthis.type = 'DirectionalLight';\n\n\t\tthis.position.copy( Object3D.DEFAULT_UP );\n\t\tthis.updateMatrix();\n\n\t\tthis.target = new Object3D();\n\n\t\tthis.shadow = new DirectionalLightShadow();\n\n\t}\n\n\tdispose() {\n\n\t\tthis.shadow.dispose();\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.target = source.target.clone();\n\t\tthis.shadow = source.shadow.clone();\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass AmbientLight extends Light {\n\n\tconstructor( color, intensity ) {\n\n\t\tsuper( color, intensity );\n\n\t\tthis.isAmbientLight = true;\n\n\t\tthis.type = 'AmbientLight';\n\n\t}\n\n}\n\nclass RectAreaLight extends Light {\n\n\tconstructor( color, intensity, width = 10, height = 10 ) {\n\n\t\tsuper( color, intensity );\n\n\t\tthis.isRectAreaLight = true;\n\n\t\tthis.type = 'RectAreaLight';\n\n\t\tthis.width = width;\n\t\tthis.height = height;\n\n\t}\n\n\tget power() {\n\n\t\t// compute the light's luminous power (in lumens) from its intensity (in nits)\n\t\treturn this.intensity * this.width * this.height * Math.PI;\n\n\t}\n\n\tset power( power ) {\n\n\t\t// set the light's intensity (in nits) from the desired luminous power (in lumens)\n\t\tthis.intensity = power / ( this.width * this.height * Math.PI );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.width = source.width;\n\t\tthis.height = source.height;\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON( meta ) {\n\n\t\tconst data = super.toJSON( meta );\n\n\t\tdata.object.width = this.width;\n\t\tdata.object.height = this.height;\n\n\t\treturn data;\n\n\t}\n\n}\n\n/**\n * Primary reference:\n * https://graphics.stanford.edu/papers/envmap/envmap.pdf\n *\n * Secondary reference:\n * https://www.ppsloan.org/publications/StupidSH36.pdf\n */\n\n// 3-band SH defined by 9 coefficients\n\nclass SphericalHarmonics3 {\n\n\tconstructor() {\n\n\t\tthis.isSphericalHarmonics3 = true;\n\n\t\tthis.coefficients = [];\n\n\t\tfor ( let i = 0; i < 9; i ++ ) {\n\n\t\t\tthis.coefficients.push( new Vector3() );\n\n\t\t}\n\n\t}\n\n\tset( coefficients ) {\n\n\t\tfor ( let i = 0; i < 9; i ++ ) {\n\n\t\t\tthis.coefficients[ i ].copy( coefficients[ i ] );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tzero() {\n\n\t\tfor ( let i = 0; i < 9; i ++ ) {\n\n\t\t\tthis.coefficients[ i ].set( 0, 0, 0 );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t// get the radiance in the direction of the normal\n\t// target is a Vector3\n\tgetAt( normal, target ) {\n\n\t\t// normal is assumed to be unit length\n\n\t\tconst x = normal.x, y = normal.y, z = normal.z;\n\n\t\tconst coeff = this.coefficients;\n\n\t\t// band 0\n\t\ttarget.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );\n\n\t\t// band 1\n\t\ttarget.addScaledVector( coeff[ 1 ], 0.488603 * y );\n\t\ttarget.addScaledVector( coeff[ 2 ], 0.488603 * z );\n\t\ttarget.addScaledVector( coeff[ 3 ], 0.488603 * x );\n\n\t\t// band 2\n\t\ttarget.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );\n\t\ttarget.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );\n\t\ttarget.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );\n\t\ttarget.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );\n\t\ttarget.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );\n\n\t\treturn target;\n\n\t}\n\n\t// get the irradiance (radiance convolved with cosine lobe) in the direction of the normal\n\t// target is a Vector3\n\t// https://graphics.stanford.edu/papers/envmap/envmap.pdf\n\tgetIrradianceAt( normal, target ) {\n\n\t\t// normal is assumed to be unit length\n\n\t\tconst x = normal.x, y = normal.y, z = normal.z;\n\n\t\tconst coeff = this.coefficients;\n\n\t\t// band 0\n\t\ttarget.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095\n\n\t\t// band 1\n\t\ttarget.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603\n\t\ttarget.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );\n\t\ttarget.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );\n\n\t\t// band 2\n\t\ttarget.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548\n\t\ttarget.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );\n\t\ttarget.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3\n\t\ttarget.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );\n\t\ttarget.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274\n\n\t\treturn target;\n\n\t}\n\n\tadd( sh ) {\n\n\t\tfor ( let i = 0; i < 9; i ++ ) {\n\n\t\t\tthis.coefficients[ i ].add( sh.coefficients[ i ] );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\taddScaledSH( sh, s ) {\n\n\t\tfor ( let i = 0; i < 9; i ++ ) {\n\n\t\t\tthis.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tscale( s ) {\n\n\t\tfor ( let i = 0; i < 9; i ++ ) {\n\n\t\t\tthis.coefficients[ i ].multiplyScalar( s );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tlerp( sh, alpha ) {\n\n\t\tfor ( let i = 0; i < 9; i ++ ) {\n\n\t\t\tthis.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tequals( sh ) {\n\n\t\tfor ( let i = 0; i < 9; i ++ ) {\n\n\t\t\tif ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {\n\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\tcopy( sh ) {\n\n\t\treturn this.set( sh.coefficients );\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n\tfromArray( array, offset = 0 ) {\n\n\t\tconst coefficients = this.coefficients;\n\n\t\tfor ( let i = 0; i < 9; i ++ ) {\n\n\t\t\tcoefficients[ i ].fromArray( array, offset + ( i * 3 ) );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\ttoArray( array = [], offset = 0 ) {\n\n\t\tconst coefficients = this.coefficients;\n\n\t\tfor ( let i = 0; i < 9; i ++ ) {\n\n\t\t\tcoefficients[ i ].toArray( array, offset + ( i * 3 ) );\n\n\t\t}\n\n\t\treturn array;\n\n\t}\n\n\t// evaluate the basis functions\n\t// shBasis is an Array[ 9 ]\n\tstatic getBasisAt( normal, shBasis ) {\n\n\t\t// normal is assumed to be unit length\n\n\t\tconst x = normal.x, y = normal.y, z = normal.z;\n\n\t\t// band 0\n\t\tshBasis[ 0 ] = 0.282095;\n\n\t\t// band 1\n\t\tshBasis[ 1 ] = 0.488603 * y;\n\t\tshBasis[ 2 ] = 0.488603 * z;\n\t\tshBasis[ 3 ] = 0.488603 * x;\n\n\t\t// band 2\n\t\tshBasis[ 4 ] = 1.092548 * x * y;\n\t\tshBasis[ 5 ] = 1.092548 * y * z;\n\t\tshBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );\n\t\tshBasis[ 7 ] = 1.092548 * x * z;\n\t\tshBasis[ 8 ] = 0.546274 * ( x * x - y * y );\n\n\t}\n\n}\n\nclass LightProbe extends Light {\n\n\tconstructor( sh = new SphericalHarmonics3(), intensity = 1 ) {\n\n\t\tsuper( undefined, intensity );\n\n\t\tthis.isLightProbe = true;\n\n\t\tthis.sh = sh;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.sh.copy( source.sh );\n\n\t\treturn this;\n\n\t}\n\n\tfromJSON( json ) {\n\n\t\tthis.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();\n\t\tthis.sh.fromArray( json.sh );\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON( meta ) {\n\n\t\tconst data = super.toJSON( meta );\n\n\t\tdata.object.sh = this.sh.toArray();\n\n\t\treturn data;\n\n\t}\n\n}\n\nclass MaterialLoader extends Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\t\tthis.textures = {};\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tconst scope = this;\n\n\t\tconst loader = new FileLoader( scope.manager );\n\t\tloader.setPath( scope.path );\n\t\tloader.setRequestHeader( scope.requestHeader );\n\t\tloader.setWithCredentials( scope.withCredentials );\n\t\tloader.load( url, function ( text ) {\n\n\t\t\ttry {\n\n\t\t\t\tonLoad( scope.parse( JSON.parse( text ) ) );\n\n\t\t\t} catch ( e ) {\n\n\t\t\t\tif ( onError ) {\n\n\t\t\t\t\tonError( e );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tconsole.error( e );\n\n\t\t\t\t}\n\n\t\t\t\tscope.manager.itemError( url );\n\n\t\t\t}\n\n\t\t}, onProgress, onError );\n\n\t}\n\n\tparse( json ) {\n\n\t\tconst textures = this.textures;\n\n\t\tfunction getTexture( name ) {\n\n\t\t\tif ( textures[ name ] === undefined ) {\n\n\t\t\t\tconsole.warn( 'THREE.MaterialLoader: Undefined texture', name );\n\n\t\t\t}\n\n\t\t\treturn textures[ name ];\n\n\t\t}\n\n\t\tconst material = MaterialLoader.createMaterialFromType( json.type );\n\n\t\tif ( json.uuid !== undefined ) material.uuid = json.uuid;\n\t\tif ( json.name !== undefined ) material.name = json.name;\n\t\tif ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );\n\t\tif ( json.roughness !== undefined ) material.roughness = json.roughness;\n\t\tif ( json.metalness !== undefined ) material.metalness = json.metalness;\n\t\tif ( json.sheen !== undefined ) material.sheen = json.sheen;\n\t\tif ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );\n\t\tif ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;\n\t\tif ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );\n\t\tif ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );\n\t\tif ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;\n\t\tif ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );\n\t\tif ( json.shininess !== undefined ) material.shininess = json.shininess;\n\t\tif ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;\n\t\tif ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;\n\t\tif ( json.iridescence !== undefined ) material.iridescence = json.iridescence;\n\t\tif ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;\n\t\tif ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;\n\t\tif ( json.transmission !== undefined ) material.transmission = json.transmission;\n\t\tif ( json.thickness !== undefined ) material.thickness = json.thickness;\n\t\tif ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;\n\t\tif ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );\n\t\tif ( json.fog !== undefined ) material.fog = json.fog;\n\t\tif ( json.flatShading !== undefined ) material.flatShading = json.flatShading;\n\t\tif ( json.blending !== undefined ) material.blending = json.blending;\n\t\tif ( json.combine !== undefined ) material.combine = json.combine;\n\t\tif ( json.side !== undefined ) material.side = json.side;\n\t\tif ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;\n\t\tif ( json.opacity !== undefined ) material.opacity = json.opacity;\n\t\tif ( json.transparent !== undefined ) material.transparent = json.transparent;\n\t\tif ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;\n\t\tif ( json.depthTest !== undefined ) material.depthTest = json.depthTest;\n\t\tif ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;\n\t\tif ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;\n\n\t\tif ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;\n\t\tif ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;\n\t\tif ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;\n\t\tif ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;\n\t\tif ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;\n\t\tif ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;\n\t\tif ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;\n\t\tif ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;\n\n\t\tif ( json.wireframe !== undefined ) material.wireframe = json.wireframe;\n\t\tif ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;\n\t\tif ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;\n\t\tif ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;\n\n\t\tif ( json.rotation !== undefined ) material.rotation = json.rotation;\n\n\t\tif ( json.linewidth !== 1 ) material.linewidth = json.linewidth;\n\t\tif ( json.dashSize !== undefined ) material.dashSize = json.dashSize;\n\t\tif ( json.gapSize !== undefined ) material.gapSize = json.gapSize;\n\t\tif ( json.scale !== undefined ) material.scale = json.scale;\n\n\t\tif ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;\n\t\tif ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;\n\t\tif ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;\n\n\t\tif ( json.dithering !== undefined ) material.dithering = json.dithering;\n\n\t\tif ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;\n\t\tif ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;\n\t\tif ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;\n\n\t\tif ( json.visible !== undefined ) material.visible = json.visible;\n\n\t\tif ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;\n\n\t\tif ( json.userData !== undefined ) material.userData = json.userData;\n\n\t\tif ( json.vertexColors !== undefined ) {\n\n\t\t\tif ( typeof json.vertexColors === 'number' ) {\n\n\t\t\t\tmaterial.vertexColors = ( json.vertexColors > 0 ) ? true : false;\n\n\t\t\t} else {\n\n\t\t\t\tmaterial.vertexColors = json.vertexColors;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// Shader Material\n\n\t\tif ( json.uniforms !== undefined ) {\n\n\t\t\tfor ( const name in json.uniforms ) {\n\n\t\t\t\tconst uniform = json.uniforms[ name ];\n\n\t\t\t\tmaterial.uniforms[ name ] = {};\n\n\t\t\t\tswitch ( uniform.type ) {\n\n\t\t\t\t\tcase 't':\n\t\t\t\t\t\tmaterial.uniforms[ name ].value = getTexture( uniform.value );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'c':\n\t\t\t\t\t\tmaterial.uniforms[ name ].value = new Color().setHex( uniform.value );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'v2':\n\t\t\t\t\t\tmaterial.uniforms[ name ].value = new Vector2().fromArray( uniform.value );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'v3':\n\t\t\t\t\t\tmaterial.uniforms[ name ].value = new Vector3().fromArray( uniform.value );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'v4':\n\t\t\t\t\t\tmaterial.uniforms[ name ].value = new Vector4().fromArray( uniform.value );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'm3':\n\t\t\t\t\t\tmaterial.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'm4':\n\t\t\t\t\t\tmaterial.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tmaterial.uniforms[ name ].value = uniform.value;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( json.defines !== undefined ) material.defines = json.defines;\n\t\tif ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;\n\t\tif ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;\n\t\tif ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;\n\n\t\tif ( json.extensions !== undefined ) {\n\n\t\t\tfor ( const key in json.extensions ) {\n\n\t\t\t\tmaterial.extensions[ key ] = json.extensions[ key ];\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( json.lights !== undefined ) material.lights = json.lights;\n\t\tif ( json.clipping !== undefined ) material.clipping = json.clipping;\n\n\t\t// for PointsMaterial\n\n\t\tif ( json.size !== undefined ) material.size = json.size;\n\t\tif ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;\n\n\t\t// maps\n\n\t\tif ( json.map !== undefined ) material.map = getTexture( json.map );\n\t\tif ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );\n\n\t\tif ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );\n\n\t\tif ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );\n\t\tif ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;\n\n\t\tif ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );\n\t\tif ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;\n\t\tif ( json.normalScale !== undefined ) {\n\n\t\t\tlet normalScale = json.normalScale;\n\n\t\t\tif ( Array.isArray( normalScale ) === false ) {\n\n\t\t\t\t// Blender exporter used to export a scalar. See #7459\n\n\t\t\t\tnormalScale = [ normalScale, normalScale ];\n\n\t\t\t}\n\n\t\t\tmaterial.normalScale = new Vector2().fromArray( normalScale );\n\n\t\t}\n\n\t\tif ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );\n\t\tif ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;\n\t\tif ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;\n\n\t\tif ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );\n\t\tif ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );\n\n\t\tif ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );\n\t\tif ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;\n\n\t\tif ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );\n\t\tif ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );\n\t\tif ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );\n\n\t\tif ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );\n\t\tif ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;\n\n\t\tif ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;\n\t\tif ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;\n\n\t\tif ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );\n\t\tif ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;\n\n\t\tif ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );\n\t\tif ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;\n\n\t\tif ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );\n\n\t\tif ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );\n\t\tif ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );\n\t\tif ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );\n\t\tif ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );\n\n\t\tif ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );\n\t\tif ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );\n\n\t\tif ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );\n\t\tif ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );\n\n\t\tif ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );\n\t\tif ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );\n\n\t\treturn material;\n\n\t}\n\n\tsetTextures( value ) {\n\n\t\tthis.textures = value;\n\t\treturn this;\n\n\t}\n\n\tstatic createMaterialFromType( type ) {\n\n\t\tconst materialLib = {\n\t\t\tShadowMaterial,\n\t\t\tSpriteMaterial,\n\t\t\tRawShaderMaterial,\n\t\t\tShaderMaterial,\n\t\t\tPointsMaterial,\n\t\t\tMeshPhysicalMaterial,\n\t\t\tMeshStandardMaterial,\n\t\t\tMeshPhongMaterial,\n\t\t\tMeshToonMaterial,\n\t\t\tMeshNormalMaterial,\n\t\t\tMeshLambertMaterial,\n\t\t\tMeshDepthMaterial,\n\t\t\tMeshDistanceMaterial,\n\t\t\tMeshBasicMaterial,\n\t\t\tMeshMatcapMaterial,\n\t\t\tLineDashedMaterial,\n\t\t\tLineBasicMaterial,\n\t\t\tMaterial\n\t\t};\n\n\t\treturn new materialLib[ type ]();\n\n\t}\n\n}\n\nclass LoaderUtils {\n\n\tstatic decodeText( array ) {\n\n\t\tif ( typeof TextDecoder !== 'undefined' ) {\n\n\t\t\treturn new TextDecoder().decode( array );\n\n\t\t}\n\n\t\t// Avoid the String.fromCharCode.apply(null, array) shortcut, which\n\t\t// throws a \"maximum call stack size exceeded\" error for large arrays.\n\n\t\tlet s = '';\n\n\t\tfor ( let i = 0, il = array.length; i < il; i ++ ) {\n\n\t\t\t// Implicitly assumes little-endian.\n\t\t\ts += String.fromCharCode( array[ i ] );\n\n\t\t}\n\n\t\ttry {\n\n\t\t\t// merges multi-byte utf-8 characters.\n\n\t\t\treturn decodeURIComponent( escape( s ) );\n\n\t\t} catch ( e ) { // see #16358\n\n\t\t\treturn s;\n\n\t\t}\n\n\t}\n\n\tstatic extractUrlBase( url ) {\n\n\t\tconst index = url.lastIndexOf( '/' );\n\n\t\tif ( index === - 1 ) return './';\n\n\t\treturn url.slice( 0, index + 1 );\n\n\t}\n\n\tstatic resolveURL( url, path ) {\n\n\t\t// Invalid URL\n\t\tif ( typeof url !== 'string' || url === '' ) return '';\n\n\t\t// Host Relative URL\n\t\tif ( /^https?:\\/\\//i.test( path ) && /^\\//.test( url ) ) {\n\n\t\t\tpath = path.replace( /(^https?:\\/\\/[^\\/]+).*/i, '$1' );\n\n\t\t}\n\n\t\t// Absolute URL http://,https://,//\n\t\tif ( /^(https?:)?\\/\\//i.test( url ) ) return url;\n\n\t\t// Data URI\n\t\tif ( /^data:.*,.*$/i.test( url ) ) return url;\n\n\t\t// Blob URL\n\t\tif ( /^blob:.*$/i.test( url ) ) return url;\n\n\t\t// Relative URL\n\t\treturn path + url;\n\n\t}\n\n}\n\nclass InstancedBufferGeometry extends BufferGeometry {\n\n\tconstructor() {\n\n\t\tsuper();\n\n\t\tthis.isInstancedBufferGeometry = true;\n\n\t\tthis.type = 'InstancedBufferGeometry';\n\t\tthis.instanceCount = Infinity;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.instanceCount = source.instanceCount;\n\n\t\treturn this;\n\n\t}\n\n\ttoJSON() {\n\n\t\tconst data = super.toJSON();\n\n\t\tdata.instanceCount = this.instanceCount;\n\n\t\tdata.isInstancedBufferGeometry = true;\n\n\t\treturn data;\n\n\t}\n\n}\n\nclass BufferGeometryLoader extends Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tconst scope = this;\n\n\t\tconst loader = new FileLoader( scope.manager );\n\t\tloader.setPath( scope.path );\n\t\tloader.setRequestHeader( scope.requestHeader );\n\t\tloader.setWithCredentials( scope.withCredentials );\n\t\tloader.load( url, function ( text ) {\n\n\t\t\ttry {\n\n\t\t\t\tonLoad( scope.parse( JSON.parse( text ) ) );\n\n\t\t\t} catch ( e ) {\n\n\t\t\t\tif ( onError ) {\n\n\t\t\t\t\tonError( e );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tconsole.error( e );\n\n\t\t\t\t}\n\n\t\t\t\tscope.manager.itemError( url );\n\n\t\t\t}\n\n\t\t}, onProgress, onError );\n\n\t}\n\n\tparse( json ) {\n\n\t\tconst interleavedBufferMap = {};\n\t\tconst arrayBufferMap = {};\n\n\t\tfunction getInterleavedBuffer( json, uuid ) {\n\n\t\t\tif ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];\n\n\t\t\tconst interleavedBuffers = json.interleavedBuffers;\n\t\t\tconst interleavedBuffer = interleavedBuffers[ uuid ];\n\n\t\t\tconst buffer = getArrayBuffer( json, interleavedBuffer.buffer );\n\n\t\t\tconst array = getTypedArray( interleavedBuffer.type, buffer );\n\t\t\tconst ib = new InterleavedBuffer( array, interleavedBuffer.stride );\n\t\t\tib.uuid = interleavedBuffer.uuid;\n\n\t\t\tinterleavedBufferMap[ uuid ] = ib;\n\n\t\t\treturn ib;\n\n\t\t}\n\n\t\tfunction getArrayBuffer( json, uuid ) {\n\n\t\t\tif ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];\n\n\t\t\tconst arrayBuffers = json.arrayBuffers;\n\t\t\tconst arrayBuffer = arrayBuffers[ uuid ];\n\n\t\t\tconst ab = new Uint32Array( arrayBuffer ).buffer;\n\n\t\t\tarrayBufferMap[ uuid ] = ab;\n\n\t\t\treturn ab;\n\n\t\t}\n\n\t\tconst geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();\n\n\t\tconst index = json.data.index;\n\n\t\tif ( index !== undefined ) {\n\n\t\t\tconst typedArray = getTypedArray( index.type, index.array );\n\t\t\tgeometry.setIndex( new BufferAttribute( typedArray, 1 ) );\n\n\t\t}\n\n\t\tconst attributes = json.data.attributes;\n\n\t\tfor ( const key in attributes ) {\n\n\t\t\tconst attribute = attributes[ key ];\n\t\t\tlet bufferAttribute;\n\n\t\t\tif ( attribute.isInterleavedBufferAttribute ) {\n\n\t\t\t\tconst interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );\n\t\t\t\tbufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );\n\n\t\t\t} else {\n\n\t\t\t\tconst typedArray = getTypedArray( attribute.type, attribute.array );\n\t\t\t\tconst bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;\n\t\t\t\tbufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );\n\n\t\t\t}\n\n\t\t\tif ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;\n\t\t\tif ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );\n\n\t\t\tif ( attribute.updateRange !== undefined ) {\n\n\t\t\t\tbufferAttribute.updateRange.offset = attribute.updateRange.offset;\n\t\t\t\tbufferAttribute.updateRange.count = attribute.updateRange.count;\n\n\t\t\t}\n\n\t\t\tgeometry.setAttribute( key, bufferAttribute );\n\n\t\t}\n\n\t\tconst morphAttributes = json.data.morphAttributes;\n\n\t\tif ( morphAttributes ) {\n\n\t\t\tfor ( const key in morphAttributes ) {\n\n\t\t\t\tconst attributeArray = morphAttributes[ key ];\n\n\t\t\t\tconst array = [];\n\n\t\t\t\tfor ( let i = 0, il = attributeArray.length; i < il; i ++ ) {\n\n\t\t\t\t\tconst attribute = attributeArray[ i ];\n\t\t\t\t\tlet bufferAttribute;\n\n\t\t\t\t\tif ( attribute.isInterleavedBufferAttribute ) {\n\n\t\t\t\t\t\tconst interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );\n\t\t\t\t\t\tbufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tconst typedArray = getTypedArray( attribute.type, attribute.array );\n\t\t\t\t\t\tbufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;\n\t\t\t\t\tarray.push( bufferAttribute );\n\n\t\t\t\t}\n\n\t\t\t\tgeometry.morphAttributes[ key ] = array;\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst morphTargetsRelative = json.data.morphTargetsRelative;\n\n\t\tif ( morphTargetsRelative ) {\n\n\t\t\tgeometry.morphTargetsRelative = true;\n\n\t\t}\n\n\t\tconst groups = json.data.groups || json.data.drawcalls || json.data.offsets;\n\n\t\tif ( groups !== undefined ) {\n\n\t\t\tfor ( let i = 0, n = groups.length; i !== n; ++ i ) {\n\n\t\t\t\tconst group = groups[ i ];\n\n\t\t\t\tgeometry.addGroup( group.start, group.count, group.materialIndex );\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst boundingSphere = json.data.boundingSphere;\n\n\t\tif ( boundingSphere !== undefined ) {\n\n\t\t\tconst center = new Vector3();\n\n\t\t\tif ( boundingSphere.center !== undefined ) {\n\n\t\t\t\tcenter.fromArray( boundingSphere.center );\n\n\t\t\t}\n\n\t\t\tgeometry.boundingSphere = new Sphere( center, boundingSphere.radius );\n\n\t\t}\n\n\t\tif ( json.name ) geometry.name = json.name;\n\t\tif ( json.userData ) geometry.userData = json.userData;\n\n\t\treturn geometry;\n\n\t}\n\n}\n\nclass ObjectLoader extends Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tconst scope = this;\n\n\t\tconst path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;\n\t\tthis.resourcePath = this.resourcePath || path;\n\n\t\tconst loader = new FileLoader( this.manager );\n\t\tloader.setPath( this.path );\n\t\tloader.setRequestHeader( this.requestHeader );\n\t\tloader.setWithCredentials( this.withCredentials );\n\t\tloader.load( url, function ( text ) {\n\n\t\t\tlet json = null;\n\n\t\t\ttry {\n\n\t\t\t\tjson = JSON.parse( text );\n\n\t\t\t} catch ( error ) {\n\n\t\t\t\tif ( onError !== undefined ) onError( error );\n\n\t\t\t\tconsole.error( 'THREE:ObjectLoader: Can\\'t parse ' + url + '.', error.message );\n\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tconst metadata = json.metadata;\n\n\t\t\tif ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {\n\n\t\t\t\tif ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\\'t load ' + url ) );\n\n\t\t\t\tconsole.error( 'THREE.ObjectLoader: Can\\'t load ' + url );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tscope.parse( json, onLoad );\n\n\t\t}, onProgress, onError );\n\n\t}\n\n\tasync loadAsync( url, onProgress ) {\n\n\t\tconst scope = this;\n\n\t\tconst path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;\n\t\tthis.resourcePath = this.resourcePath || path;\n\n\t\tconst loader = new FileLoader( this.manager );\n\t\tloader.setPath( this.path );\n\t\tloader.setRequestHeader( this.requestHeader );\n\t\tloader.setWithCredentials( this.withCredentials );\n\n\t\tconst text = await loader.loadAsync( url, onProgress );\n\n\t\tconst json = JSON.parse( text );\n\n\t\tconst metadata = json.metadata;\n\n\t\tif ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {\n\n\t\t\tthrow new Error( 'THREE.ObjectLoader: Can\\'t load ' + url );\n\n\t\t}\n\n\t\treturn await scope.parseAsync( json );\n\n\t}\n\n\tparse( json, onLoad ) {\n\n\t\tconst animations = this.parseAnimations( json.animations );\n\t\tconst shapes = this.parseShapes( json.shapes );\n\t\tconst geometries = this.parseGeometries( json.geometries, shapes );\n\n\t\tconst images = this.parseImages( json.images, function () {\n\n\t\t\tif ( onLoad !== undefined ) onLoad( object );\n\n\t\t} );\n\n\t\tconst textures = this.parseTextures( json.textures, images );\n\t\tconst materials = this.parseMaterials( json.materials, textures );\n\n\t\tconst object = this.parseObject( json.object, geometries, materials, textures, animations );\n\t\tconst skeletons = this.parseSkeletons( json.skeletons, object );\n\n\t\tthis.bindSkeletons( object, skeletons );\n\n\t\t//\n\n\t\tif ( onLoad !== undefined ) {\n\n\t\t\tlet hasImages = false;\n\n\t\t\tfor ( const uuid in images ) {\n\n\t\t\t\tif ( images[ uuid ].data instanceof HTMLImageElement ) {\n\n\t\t\t\t\thasImages = true;\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( hasImages === false ) onLoad( object );\n\n\t\t}\n\n\t\treturn object;\n\n\t}\n\n\tasync parseAsync( json ) {\n\n\t\tconst animations = this.parseAnimations( json.animations );\n\t\tconst shapes = this.parseShapes( json.shapes );\n\t\tconst geometries = this.parseGeometries( json.geometries, shapes );\n\n\t\tconst images = await this.parseImagesAsync( json.images );\n\n\t\tconst textures = this.parseTextures( json.textures, images );\n\t\tconst materials = this.parseMaterials( json.materials, textures );\n\n\t\tconst object = this.parseObject( json.object, geometries, materials, textures, animations );\n\t\tconst skeletons = this.parseSkeletons( json.skeletons, object );\n\n\t\tthis.bindSkeletons( object, skeletons );\n\n\t\treturn object;\n\n\t}\n\n\tparseShapes( json ) {\n\n\t\tconst shapes = {};\n\n\t\tif ( json !== undefined ) {\n\n\t\t\tfor ( let i = 0, l = json.length; i < l; i ++ ) {\n\n\t\t\t\tconst shape = new Shape().fromJSON( json[ i ] );\n\n\t\t\t\tshapes[ shape.uuid ] = shape;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn shapes;\n\n\t}\n\n\tparseSkeletons( json, object ) {\n\n\t\tconst skeletons = {};\n\t\tconst bones = {};\n\n\t\t// generate bone lookup table\n\n\t\tobject.traverse( function ( child ) {\n\n\t\t\tif ( child.isBone ) bones[ child.uuid ] = child;\n\n\t\t} );\n\n\t\t// create skeletons\n\n\t\tif ( json !== undefined ) {\n\n\t\t\tfor ( let i = 0, l = json.length; i < l; i ++ ) {\n\n\t\t\t\tconst skeleton = new Skeleton().fromJSON( json[ i ], bones );\n\n\t\t\t\tskeletons[ skeleton.uuid ] = skeleton;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn skeletons;\n\n\t}\n\n\tparseGeometries( json, shapes ) {\n\n\t\tconst geometries = {};\n\n\t\tif ( json !== undefined ) {\n\n\t\t\tconst bufferGeometryLoader = new BufferGeometryLoader();\n\n\t\t\tfor ( let i = 0, l = json.length; i < l; i ++ ) {\n\n\t\t\t\tlet geometry;\n\t\t\t\tconst data = json[ i ];\n\n\t\t\t\tswitch ( data.type ) {\n\n\t\t\t\t\tcase 'BufferGeometry':\n\t\t\t\t\tcase 'InstancedBufferGeometry':\n\n\t\t\t\t\t\tgeometry = bufferGeometryLoader.parse( data );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\n\t\t\t\t\t\tif ( data.type in Geometries ) {\n\n\t\t\t\t\t\t\tgeometry = Geometries[ data.type ].fromJSON( data, shapes );\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tconsole.warn( `THREE.ObjectLoader: Unsupported geometry type \"${ data.type }\"` );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tgeometry.uuid = data.uuid;\n\n\t\t\t\tif ( data.name !== undefined ) geometry.name = data.name;\n\t\t\t\tif ( data.userData !== undefined ) geometry.userData = data.userData;\n\n\t\t\t\tgeometries[ data.uuid ] = geometry;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn geometries;\n\n\t}\n\n\tparseMaterials( json, textures ) {\n\n\t\tconst cache = {}; // MultiMaterial\n\t\tconst materials = {};\n\n\t\tif ( json !== undefined ) {\n\n\t\t\tconst loader = new MaterialLoader();\n\t\t\tloader.setTextures( textures );\n\n\t\t\tfor ( let i = 0, l = json.length; i < l; i ++ ) {\n\n\t\t\t\tconst data = json[ i ];\n\n\t\t\t\tif ( cache[ data.uuid ] === undefined ) {\n\n\t\t\t\t\tcache[ data.uuid ] = loader.parse( data );\n\n\t\t\t\t}\n\n\t\t\t\tmaterials[ data.uuid ] = cache[ data.uuid ];\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn materials;\n\n\t}\n\n\tparseAnimations( json ) {\n\n\t\tconst animations = {};\n\n\t\tif ( json !== undefined ) {\n\n\t\t\tfor ( let i = 0; i < json.length; i ++ ) {\n\n\t\t\t\tconst data = json[ i ];\n\n\t\t\t\tconst clip = AnimationClip.parse( data );\n\n\t\t\t\tanimations[ clip.uuid ] = clip;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn animations;\n\n\t}\n\n\tparseImages( json, onLoad ) {\n\n\t\tconst scope = this;\n\t\tconst images = {};\n\n\t\tlet loader;\n\n\t\tfunction loadImage( url ) {\n\n\t\t\tscope.manager.itemStart( url );\n\n\t\t\treturn loader.load( url, function () {\n\n\t\t\t\tscope.manager.itemEnd( url );\n\n\t\t\t}, undefined, function () {\n\n\t\t\t\tscope.manager.itemError( url );\n\t\t\t\tscope.manager.itemEnd( url );\n\n\t\t\t} );\n\n\t\t}\n\n\t\tfunction deserializeImage( image ) {\n\n\t\t\tif ( typeof image === 'string' ) {\n\n\t\t\t\tconst url = image;\n\n\t\t\t\tconst path = /^(\\/\\/)|([a-z]+:(\\/\\/)?)/i.test( url ) ? url : scope.resourcePath + url;\n\n\t\t\t\treturn loadImage( path );\n\n\t\t\t} else {\n\n\t\t\t\tif ( image.data ) {\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: getTypedArray( image.type, image.data ),\n\t\t\t\t\t\twidth: image.width,\n\t\t\t\t\t\theight: image.height\n\t\t\t\t\t};\n\n\t\t\t\t} else {\n\n\t\t\t\t\treturn null;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( json !== undefined && json.length > 0 ) {\n\n\t\t\tconst manager = new LoadingManager( onLoad );\n\n\t\t\tloader = new ImageLoader( manager );\n\t\t\tloader.setCrossOrigin( this.crossOrigin );\n\n\t\t\tfor ( let i = 0, il = json.length; i < il; i ++ ) {\n\n\t\t\t\tconst image = json[ i ];\n\t\t\t\tconst url = image.url;\n\n\t\t\t\tif ( Array.isArray( url ) ) {\n\n\t\t\t\t\t// load array of images e.g CubeTexture\n\n\t\t\t\t\tconst imageArray = [];\n\n\t\t\t\t\tfor ( let j = 0, jl = url.length; j < jl; j ++ ) {\n\n\t\t\t\t\t\tconst currentUrl = url[ j ];\n\n\t\t\t\t\t\tconst deserializedImage = deserializeImage( currentUrl );\n\n\t\t\t\t\t\tif ( deserializedImage !== null ) {\n\n\t\t\t\t\t\t\tif ( deserializedImage instanceof HTMLImageElement ) {\n\n\t\t\t\t\t\t\t\timageArray.push( deserializedImage );\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t// special case: handle array of data textures for cube textures\n\n\t\t\t\t\t\t\t\timageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\timages[ image.uuid ] = new Source( imageArray );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// load single image\n\n\t\t\t\t\tconst deserializedImage = deserializeImage( image.url );\n\t\t\t\t\timages[ image.uuid ] = new Source( deserializedImage );\n\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn images;\n\n\t}\n\n\tasync parseImagesAsync( json ) {\n\n\t\tconst scope = this;\n\t\tconst images = {};\n\n\t\tlet loader;\n\n\t\tasync function deserializeImage( image ) {\n\n\t\t\tif ( typeof image === 'string' ) {\n\n\t\t\t\tconst url = image;\n\n\t\t\t\tconst path = /^(\\/\\/)|([a-z]+:(\\/\\/)?)/i.test( url ) ? url : scope.resourcePath + url;\n\n\t\t\t\treturn await loader.loadAsync( path );\n\n\t\t\t} else {\n\n\t\t\t\tif ( image.data ) {\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: getTypedArray( image.type, image.data ),\n\t\t\t\t\t\twidth: image.width,\n\t\t\t\t\t\theight: image.height\n\t\t\t\t\t};\n\n\t\t\t\t} else {\n\n\t\t\t\t\treturn null;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( json !== undefined && json.length > 0 ) {\n\n\t\t\tloader = new ImageLoader( this.manager );\n\t\t\tloader.setCrossOrigin( this.crossOrigin );\n\n\t\t\tfor ( let i = 0, il = json.length; i < il; i ++ ) {\n\n\t\t\t\tconst image = json[ i ];\n\t\t\t\tconst url = image.url;\n\n\t\t\t\tif ( Array.isArray( url ) ) {\n\n\t\t\t\t\t// load array of images e.g CubeTexture\n\n\t\t\t\t\tconst imageArray = [];\n\n\t\t\t\t\tfor ( let j = 0, jl = url.length; j < jl; j ++ ) {\n\n\t\t\t\t\t\tconst currentUrl = url[ j ];\n\n\t\t\t\t\t\tconst deserializedImage = await deserializeImage( currentUrl );\n\n\t\t\t\t\t\tif ( deserializedImage !== null ) {\n\n\t\t\t\t\t\t\tif ( deserializedImage instanceof HTMLImageElement ) {\n\n\t\t\t\t\t\t\t\timageArray.push( deserializedImage );\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t// special case: handle array of data textures for cube textures\n\n\t\t\t\t\t\t\t\timageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\timages[ image.uuid ] = new Source( imageArray );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// load single image\n\n\t\t\t\t\tconst deserializedImage = await deserializeImage( image.url );\n\t\t\t\t\timages[ image.uuid ] = new Source( deserializedImage );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn images;\n\n\t}\n\n\tparseTextures( json, images ) {\n\n\t\tfunction parseConstant( value, type ) {\n\n\t\t\tif ( typeof value === 'number' ) return value;\n\n\t\t\tconsole.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );\n\n\t\t\treturn type[ value ];\n\n\t\t}\n\n\t\tconst textures = {};\n\n\t\tif ( json !== undefined ) {\n\n\t\t\tfor ( let i = 0, l = json.length; i < l; i ++ ) {\n\n\t\t\t\tconst data = json[ i ];\n\n\t\t\t\tif ( data.image === undefined ) {\n\n\t\t\t\t\tconsole.warn( 'THREE.ObjectLoader: No \"image\" specified for', data.uuid );\n\n\t\t\t\t}\n\n\t\t\t\tif ( images[ data.image ] === undefined ) {\n\n\t\t\t\t\tconsole.warn( 'THREE.ObjectLoader: Undefined image', data.image );\n\n\t\t\t\t}\n\n\t\t\t\tconst source = images[ data.image ];\n\t\t\t\tconst image = source.data;\n\n\t\t\t\tlet texture;\n\n\t\t\t\tif ( Array.isArray( image ) ) {\n\n\t\t\t\t\ttexture = new CubeTexture();\n\n\t\t\t\t\tif ( image.length === 6 ) texture.needsUpdate = true;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tif ( image && image.data ) {\n\n\t\t\t\t\t\ttexture = new DataTexture();\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\ttexture = new Texture();\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( image ) texture.needsUpdate = true; // textures can have undefined image data\n\n\t\t\t\t}\n\n\t\t\t\ttexture.source = source;\n\n\t\t\t\ttexture.uuid = data.uuid;\n\n\t\t\t\tif ( data.name !== undefined ) texture.name = data.name;\n\n\t\t\t\tif ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );\n\t\t\t\tif ( data.channel !== undefined ) texture.channel = data.channel;\n\n\t\t\t\tif ( data.offset !== undefined ) texture.offset.fromArray( data.offset );\n\t\t\t\tif ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );\n\t\t\t\tif ( data.center !== undefined ) texture.center.fromArray( data.center );\n\t\t\t\tif ( data.rotation !== undefined ) texture.rotation = data.rotation;\n\n\t\t\t\tif ( data.wrap !== undefined ) {\n\n\t\t\t\t\ttexture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );\n\t\t\t\t\ttexture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );\n\n\t\t\t\t}\n\n\t\t\t\tif ( data.format !== undefined ) texture.format = data.format;\n\t\t\t\tif ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;\n\t\t\t\tif ( data.type !== undefined ) texture.type = data.type;\n\t\t\t\tif ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;\n\t\t\t\tif ( data.encoding !== undefined ) texture.encoding = data.encoding; // @deprecated, r152\n\n\t\t\t\tif ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );\n\t\t\t\tif ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );\n\t\t\t\tif ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;\n\n\t\t\t\tif ( data.flipY !== undefined ) texture.flipY = data.flipY;\n\n\t\t\t\tif ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;\n\t\t\t\tif ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;\n\t\t\t\tif ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;\n\n\t\t\t\tif ( data.userData !== undefined ) texture.userData = data.userData;\n\n\t\t\t\ttextures[ data.uuid ] = texture;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn textures;\n\n\t}\n\n\tparseObject( data, geometries, materials, textures, animations ) {\n\n\t\tlet object;\n\n\t\tfunction getGeometry( name ) {\n\n\t\t\tif ( geometries[ name ] === undefined ) {\n\n\t\t\t\tconsole.warn( 'THREE.ObjectLoader: Undefined geometry', name );\n\n\t\t\t}\n\n\t\t\treturn geometries[ name ];\n\n\t\t}\n\n\t\tfunction getMaterial( name ) {\n\n\t\t\tif ( name === undefined ) return undefined;\n\n\t\t\tif ( Array.isArray( name ) ) {\n\n\t\t\t\tconst array = [];\n\n\t\t\t\tfor ( let i = 0, l = name.length; i < l; i ++ ) {\n\n\t\t\t\t\tconst uuid = name[ i ];\n\n\t\t\t\t\tif ( materials[ uuid ] === undefined ) {\n\n\t\t\t\t\t\tconsole.warn( 'THREE.ObjectLoader: Undefined material', uuid );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tarray.push( materials[ uuid ] );\n\n\t\t\t\t}\n\n\t\t\t\treturn array;\n\n\t\t\t}\n\n\t\t\tif ( materials[ name ] === undefined ) {\n\n\t\t\t\tconsole.warn( 'THREE.ObjectLoader: Undefined material', name );\n\n\t\t\t}\n\n\t\t\treturn materials[ name ];\n\n\t\t}\n\n\t\tfunction getTexture( uuid ) {\n\n\t\t\tif ( textures[ uuid ] === undefined ) {\n\n\t\t\t\tconsole.warn( 'THREE.ObjectLoader: Undefined texture', uuid );\n\n\t\t\t}\n\n\t\t\treturn textures[ uuid ];\n\n\t\t}\n\n\t\tlet geometry, material;\n\n\t\tswitch ( data.type ) {\n\n\t\t\tcase 'Scene':\n\n\t\t\t\tobject = new Scene();\n\n\t\t\t\tif ( data.background !== undefined ) {\n\n\t\t\t\t\tif ( Number.isInteger( data.background ) ) {\n\n\t\t\t\t\t\tobject.background = new Color( data.background );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tobject.background = getTexture( data.background );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif ( data.environment !== undefined ) {\n\n\t\t\t\t\tobject.environment = getTexture( data.environment );\n\n\t\t\t\t}\n\n\t\t\t\tif ( data.fog !== undefined ) {\n\n\t\t\t\t\tif ( data.fog.type === 'Fog' ) {\n\n\t\t\t\t\t\tobject.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );\n\n\t\t\t\t\t} else if ( data.fog.type === 'FogExp2' ) {\n\n\t\t\t\t\t\tobject.fog = new FogExp2( data.fog.color, data.fog.density );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;\n\t\t\t\tif ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'PerspectiveCamera':\n\n\t\t\t\tobject = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );\n\n\t\t\t\tif ( data.focus !== undefined ) object.focus = data.focus;\n\t\t\t\tif ( data.zoom !== undefined ) object.zoom = data.zoom;\n\t\t\t\tif ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;\n\t\t\t\tif ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;\n\t\t\t\tif ( data.view !== undefined ) object.view = Object.assign( {}, data.view );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'OrthographicCamera':\n\n\t\t\t\tobject = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );\n\n\t\t\t\tif ( data.zoom !== undefined ) object.zoom = data.zoom;\n\t\t\t\tif ( data.view !== undefined ) object.view = Object.assign( {}, data.view );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'AmbientLight':\n\n\t\t\t\tobject = new AmbientLight( data.color, data.intensity );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'DirectionalLight':\n\n\t\t\t\tobject = new DirectionalLight( data.color, data.intensity );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'PointLight':\n\n\t\t\t\tobject = new PointLight( data.color, data.intensity, data.distance, data.decay );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'RectAreaLight':\n\n\t\t\t\tobject = new RectAreaLight( data.color, data.intensity, data.width, data.height );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'SpotLight':\n\n\t\t\t\tobject = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'HemisphereLight':\n\n\t\t\t\tobject = new HemisphereLight( data.color, data.groundColor, data.intensity );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'LightProbe':\n\n\t\t\t\tobject = new LightProbe().fromJSON( data );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'SkinnedMesh':\n\n\t\t\t\tgeometry = getGeometry( data.geometry );\n\t\t\t \tmaterial = getMaterial( data.material );\n\n\t\t\t\tobject = new SkinnedMesh( geometry, material );\n\n\t\t\t\tif ( data.bindMode !== undefined ) object.bindMode = data.bindMode;\n\t\t\t\tif ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );\n\t\t\t\tif ( data.skeleton !== undefined ) object.skeleton = data.skeleton;\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'Mesh':\n\n\t\t\t\tgeometry = getGeometry( data.geometry );\n\t\t\t\tmaterial = getMaterial( data.material );\n\n\t\t\t\tobject = new Mesh( geometry, material );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'InstancedMesh':\n\n\t\t\t\tgeometry = getGeometry( data.geometry );\n\t\t\t\tmaterial = getMaterial( data.material );\n\t\t\t\tconst count = data.count;\n\t\t\t\tconst instanceMatrix = data.instanceMatrix;\n\t\t\t\tconst instanceColor = data.instanceColor;\n\n\t\t\t\tobject = new InstancedMesh( geometry, material, count );\n\t\t\t\tobject.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );\n\t\t\t\tif ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'LOD':\n\n\t\t\t\tobject = new LOD();\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'Line':\n\n\t\t\t\tobject = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'LineLoop':\n\n\t\t\t\tobject = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'LineSegments':\n\n\t\t\t\tobject = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'PointCloud':\n\t\t\tcase 'Points':\n\n\t\t\t\tobject = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'Sprite':\n\n\t\t\t\tobject = new Sprite( getMaterial( data.material ) );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'Group':\n\n\t\t\t\tobject = new Group();\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'Bone':\n\n\t\t\t\tobject = new Bone();\n\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\n\t\t\t\tobject = new Object3D();\n\n\t\t}\n\n\t\tobject.uuid = data.uuid;\n\n\t\tif ( data.name !== undefined ) object.name = data.name;\n\n\t\tif ( data.matrix !== undefined ) {\n\n\t\t\tobject.matrix.fromArray( data.matrix );\n\n\t\t\tif ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;\n\t\t\tif ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );\n\n\t\t} else {\n\n\t\t\tif ( data.position !== undefined ) object.position.fromArray( data.position );\n\t\t\tif ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );\n\t\t\tif ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );\n\t\t\tif ( data.scale !== undefined ) object.scale.fromArray( data.scale );\n\n\t\t}\n\n\t\tif ( data.up !== undefined ) object.up.fromArray( data.up );\n\n\t\tif ( data.castShadow !== undefined ) object.castShadow = data.castShadow;\n\t\tif ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;\n\n\t\tif ( data.shadow ) {\n\n\t\t\tif ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;\n\t\t\tif ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;\n\t\t\tif ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;\n\t\t\tif ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );\n\t\t\tif ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );\n\n\t\t}\n\n\t\tif ( data.visible !== undefined ) object.visible = data.visible;\n\t\tif ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;\n\t\tif ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;\n\t\tif ( data.userData !== undefined ) object.userData = data.userData;\n\t\tif ( data.layers !== undefined ) object.layers.mask = data.layers;\n\n\t\tif ( data.children !== undefined ) {\n\n\t\t\tconst children = data.children;\n\n\t\t\tfor ( let i = 0; i < children.length; i ++ ) {\n\n\t\t\t\tobject.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( data.animations !== undefined ) {\n\n\t\t\tconst objectAnimations = data.animations;\n\n\t\t\tfor ( let i = 0; i < objectAnimations.length; i ++ ) {\n\n\t\t\t\tconst uuid = objectAnimations[ i ];\n\n\t\t\t\tobject.animations.push( animations[ uuid ] );\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( data.type === 'LOD' ) {\n\n\t\t\tif ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;\n\n\t\t\tconst levels = data.levels;\n\n\t\t\tfor ( let l = 0; l < levels.length; l ++ ) {\n\n\t\t\t\tconst level = levels[ l ];\n\t\t\t\tconst child = object.getObjectByProperty( 'uuid', level.object );\n\n\t\t\t\tif ( child !== undefined ) {\n\n\t\t\t\t\tobject.addLevel( child, level.distance, level.hysteresis );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn object;\n\n\t}\n\n\tbindSkeletons( object, skeletons ) {\n\n\t\tif ( Object.keys( skeletons ).length === 0 ) return;\n\n\t\tobject.traverse( function ( child ) {\n\n\t\t\tif ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {\n\n\t\t\t\tconst skeleton = skeletons[ child.skeleton ];\n\n\t\t\t\tif ( skeleton === undefined ) {\n\n\t\t\t\t\tconsole.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tchild.bind( skeleton, child.bindMatrix );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} );\n\n\t}\n\n}\n\nconst TEXTURE_MAPPING = {\n\tUVMapping: UVMapping,\n\tCubeReflectionMapping: CubeReflectionMapping,\n\tCubeRefractionMapping: CubeRefractionMapping,\n\tEquirectangularReflectionMapping: EquirectangularReflectionMapping,\n\tEquirectangularRefractionMapping: EquirectangularRefractionMapping,\n\tCubeUVReflectionMapping: CubeUVReflectionMapping\n};\n\nconst TEXTURE_WRAPPING = {\n\tRepeatWrapping: RepeatWrapping,\n\tClampToEdgeWrapping: ClampToEdgeWrapping,\n\tMirroredRepeatWrapping: MirroredRepeatWrapping\n};\n\nconst TEXTURE_FILTER = {\n\tNearestFilter: NearestFilter,\n\tNearestMipmapNearestFilter: NearestMipmapNearestFilter,\n\tNearestMipmapLinearFilter: NearestMipmapLinearFilter,\n\tLinearFilter: LinearFilter,\n\tLinearMipmapNearestFilter: LinearMipmapNearestFilter,\n\tLinearMipmapLinearFilter: LinearMipmapLinearFilter\n};\n\nclass ImageBitmapLoader extends Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t\tthis.isImageBitmapLoader = true;\n\n\t\tif ( typeof createImageBitmap === 'undefined' ) {\n\n\t\t\tconsole.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );\n\n\t\t}\n\n\t\tif ( typeof fetch === 'undefined' ) {\n\n\t\t\tconsole.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );\n\n\t\t}\n\n\t\tthis.options = { premultiplyAlpha: 'none' };\n\n\t}\n\n\tsetOptions( options ) {\n\n\t\tthis.options = options;\n\n\t\treturn this;\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tif ( url === undefined ) url = '';\n\n\t\tif ( this.path !== undefined ) url = this.path + url;\n\n\t\turl = this.manager.resolveURL( url );\n\n\t\tconst scope = this;\n\n\t\tconst cached = Cache.get( url );\n\n\t\tif ( cached !== undefined ) {\n\n\t\t\tscope.manager.itemStart( url );\n\n\t\t\tsetTimeout( function () {\n\n\t\t\t\tif ( onLoad ) onLoad( cached );\n\n\t\t\t\tscope.manager.itemEnd( url );\n\n\t\t\t}, 0 );\n\n\t\t\treturn cached;\n\n\t\t}\n\n\t\tconst fetchOptions = {};\n\t\tfetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';\n\t\tfetchOptions.headers = this.requestHeader;\n\n\t\tfetch( url, fetchOptions ).then( function ( res ) {\n\n\t\t\treturn res.blob();\n\n\t\t} ).then( function ( blob ) {\n\n\t\t\treturn createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );\n\n\t\t} ).then( function ( imageBitmap ) {\n\n\t\t\tCache.add( url, imageBitmap );\n\n\t\t\tif ( onLoad ) onLoad( imageBitmap );\n\n\t\t\tscope.manager.itemEnd( url );\n\n\t\t} ).catch( function ( e ) {\n\n\t\t\tif ( onError ) onError( e );\n\n\t\t\tscope.manager.itemError( url );\n\t\t\tscope.manager.itemEnd( url );\n\n\t\t} );\n\n\t\tscope.manager.itemStart( url );\n\n\t}\n\n}\n\nlet _context;\n\nclass AudioContext {\n\n\tstatic getContext() {\n\n\t\tif ( _context === undefined ) {\n\n\t\t\t_context = new ( window.AudioContext || window.webkitAudioContext )();\n\n\t\t}\n\n\t\treturn _context;\n\n\t}\n\n\tstatic setContext( value ) {\n\n\t\t_context = value;\n\n\t}\n\n}\n\nclass AudioLoader extends Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tconst scope = this;\n\n\t\tconst loader = new FileLoader( this.manager );\n\t\tloader.setResponseType( 'arraybuffer' );\n\t\tloader.setPath( this.path );\n\t\tloader.setRequestHeader( this.requestHeader );\n\t\tloader.setWithCredentials( this.withCredentials );\n\t\tloader.load( url, function ( buffer ) {\n\n\t\t\ttry {\n\n\t\t\t\t// Create a copy of the buffer. The `decodeAudioData` method\n\t\t\t\t// detaches the buffer when complete, preventing reuse.\n\t\t\t\tconst bufferCopy = buffer.slice( 0 );\n\n\t\t\t\tconst context = AudioContext.getContext();\n\t\t\t\tcontext.decodeAudioData( bufferCopy, function ( audioBuffer ) {\n\n\t\t\t\t\tonLoad( audioBuffer );\n\n\t\t\t\t}, handleError );\n\n\t\t\t} catch ( e ) {\n\n\t\t\t\thandleError( e );\n\n\t\t\t}\n\n\t\t}, onProgress, onError );\n\n\t\tfunction handleError( e ) {\n\n\t\t\tif ( onError ) {\n\n\t\t\t\tonError( e );\n\n\t\t\t} else {\n\n\t\t\t\tconsole.error( e );\n\n\t\t\t}\n\n\t\t\tscope.manager.itemError( url );\n\n\t\t}\n\n\t}\n\n}\n\nclass HemisphereLightProbe extends LightProbe {\n\n\tconstructor( skyColor, groundColor, intensity = 1 ) {\n\n\t\tsuper( undefined, intensity );\n\n\t\tthis.isHemisphereLightProbe = true;\n\n\t\tconst color1 = new Color().set( skyColor );\n\t\tconst color2 = new Color().set( groundColor );\n\n\t\tconst sky = new Vector3( color1.r, color1.g, color1.b );\n\t\tconst ground = new Vector3( color2.r, color2.g, color2.b );\n\n\t\t// without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );\n\t\tconst c0 = Math.sqrt( Math.PI );\n\t\tconst c1 = c0 * Math.sqrt( 0.75 );\n\n\t\tthis.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );\n\t\tthis.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );\n\n\t}\n\n}\n\nclass AmbientLightProbe extends LightProbe {\n\n\tconstructor( color, intensity = 1 ) {\n\n\t\tsuper( undefined, intensity );\n\n\t\tthis.isAmbientLightProbe = true;\n\n\t\tconst color1 = new Color().set( color );\n\n\t\t// without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );\n\t\tthis.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );\n\n\t}\n\n}\n\nconst _eyeRight = /*@__PURE__*/ new Matrix4();\nconst _eyeLeft = /*@__PURE__*/ new Matrix4();\nconst _projectionMatrix = /*@__PURE__*/ new Matrix4();\n\nclass StereoCamera {\n\n\tconstructor() {\n\n\t\tthis.type = 'StereoCamera';\n\n\t\tthis.aspect = 1;\n\n\t\tthis.eyeSep = 0.064;\n\n\t\tthis.cameraL = new PerspectiveCamera();\n\t\tthis.cameraL.layers.enable( 1 );\n\t\tthis.cameraL.matrixAutoUpdate = false;\n\n\t\tthis.cameraR = new PerspectiveCamera();\n\t\tthis.cameraR.layers.enable( 2 );\n\t\tthis.cameraR.matrixAutoUpdate = false;\n\n\t\tthis._cache = {\n\t\t\tfocus: null,\n\t\t\tfov: null,\n\t\t\taspect: null,\n\t\t\tnear: null,\n\t\t\tfar: null,\n\t\t\tzoom: null,\n\t\t\teyeSep: null\n\t\t};\n\n\t}\n\n\tupdate( camera ) {\n\n\t\tconst cache = this._cache;\n\n\t\tconst needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||\n\t\t\tcache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||\n\t\t\tcache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;\n\n\t\tif ( needsUpdate ) {\n\n\t\t\tcache.focus = camera.focus;\n\t\t\tcache.fov = camera.fov;\n\t\t\tcache.aspect = camera.aspect * this.aspect;\n\t\t\tcache.near = camera.near;\n\t\t\tcache.far = camera.far;\n\t\t\tcache.zoom = camera.zoom;\n\t\t\tcache.eyeSep = this.eyeSep;\n\n\t\t\t// Off-axis stereoscopic effect based on\n\t\t\t// http://paulbourke.net/stereographics/stereorender/\n\n\t\t\t_projectionMatrix.copy( camera.projectionMatrix );\n\t\t\tconst eyeSepHalf = cache.eyeSep / 2;\n\t\t\tconst eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;\n\t\t\tconst ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;\n\t\t\tlet xmin, xmax;\n\n\t\t\t// translate xOffset\n\n\t\t\t_eyeLeft.elements[ 12 ] = - eyeSepHalf;\n\t\t\t_eyeRight.elements[ 12 ] = eyeSepHalf;\n\n\t\t\t// for left eye\n\n\t\t\txmin = - ymax * cache.aspect + eyeSepOnProjection;\n\t\t\txmax = ymax * cache.aspect + eyeSepOnProjection;\n\n\t\t\t_projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );\n\t\t\t_projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );\n\n\t\t\tthis.cameraL.projectionMatrix.copy( _projectionMatrix );\n\n\t\t\t// for right eye\n\n\t\t\txmin = - ymax * cache.aspect - eyeSepOnProjection;\n\t\t\txmax = ymax * cache.aspect - eyeSepOnProjection;\n\n\t\t\t_projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );\n\t\t\t_projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );\n\n\t\t\tthis.cameraR.projectionMatrix.copy( _projectionMatrix );\n\n\t\t}\n\n\t\tthis.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );\n\t\tthis.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );\n\n\t}\n\n}\n\nclass Clock {\n\n\tconstructor( autoStart = true ) {\n\n\t\tthis.autoStart = autoStart;\n\n\t\tthis.startTime = 0;\n\t\tthis.oldTime = 0;\n\t\tthis.elapsedTime = 0;\n\n\t\tthis.running = false;\n\n\t}\n\n\tstart() {\n\n\t\tthis.startTime = now();\n\n\t\tthis.oldTime = this.startTime;\n\t\tthis.elapsedTime = 0;\n\t\tthis.running = true;\n\n\t}\n\n\tstop() {\n\n\t\tthis.getElapsedTime();\n\t\tthis.running = false;\n\t\tthis.autoStart = false;\n\n\t}\n\n\tgetElapsedTime() {\n\n\t\tthis.getDelta();\n\t\treturn this.elapsedTime;\n\n\t}\n\n\tgetDelta() {\n\n\t\tlet diff = 0;\n\n\t\tif ( this.autoStart && ! this.running ) {\n\n\t\t\tthis.start();\n\t\t\treturn 0;\n\n\t\t}\n\n\t\tif ( this.running ) {\n\n\t\t\tconst newTime = now();\n\n\t\t\tdiff = ( newTime - this.oldTime ) / 1000;\n\t\t\tthis.oldTime = newTime;\n\n\t\t\tthis.elapsedTime += diff;\n\n\t\t}\n\n\t\treturn diff;\n\n\t}\n\n}\n\nfunction now() {\n\n\treturn ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732\n\n}\n\nconst _position$1 = /*@__PURE__*/ new Vector3();\nconst _quaternion$1 = /*@__PURE__*/ new Quaternion();\nconst _scale$1 = /*@__PURE__*/ new Vector3();\nconst _orientation$1 = /*@__PURE__*/ new Vector3();\n\nclass AudioListener extends Object3D {\n\n\tconstructor() {\n\n\t\tsuper();\n\n\t\tthis.type = 'AudioListener';\n\n\t\tthis.context = AudioContext.getContext();\n\n\t\tthis.gain = this.context.createGain();\n\t\tthis.gain.connect( this.context.destination );\n\n\t\tthis.filter = null;\n\n\t\tthis.timeDelta = 0;\n\n\t\t// private\n\n\t\tthis._clock = new Clock();\n\n\t}\n\n\tgetInput() {\n\n\t\treturn this.gain;\n\n\t}\n\n\tremoveFilter() {\n\n\t\tif ( this.filter !== null ) {\n\n\t\t\tthis.gain.disconnect( this.filter );\n\t\t\tthis.filter.disconnect( this.context.destination );\n\t\t\tthis.gain.connect( this.context.destination );\n\t\t\tthis.filter = null;\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tgetFilter() {\n\n\t\treturn this.filter;\n\n\t}\n\n\tsetFilter( value ) {\n\n\t\tif ( this.filter !== null ) {\n\n\t\t\tthis.gain.disconnect( this.filter );\n\t\t\tthis.filter.disconnect( this.context.destination );\n\n\t\t} else {\n\n\t\t\tthis.gain.disconnect( this.context.destination );\n\n\t\t}\n\n\t\tthis.filter = value;\n\t\tthis.gain.connect( this.filter );\n\t\tthis.filter.connect( this.context.destination );\n\n\t\treturn this;\n\n\t}\n\n\tgetMasterVolume() {\n\n\t\treturn this.gain.gain.value;\n\n\t}\n\n\tsetMasterVolume( value ) {\n\n\t\tthis.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );\n\n\t\treturn this;\n\n\t}\n\n\tupdateMatrixWorld( force ) {\n\n\t\tsuper.updateMatrixWorld( force );\n\n\t\tconst listener = this.context.listener;\n\t\tconst up = this.up;\n\n\t\tthis.timeDelta = this._clock.getDelta();\n\n\t\tthis.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );\n\n\t\t_orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );\n\n\t\tif ( listener.positionX ) {\n\n\t\t\t// code path for Chrome (see #14393)\n\n\t\t\tconst endTime = this.context.currentTime + this.timeDelta;\n\n\t\t\tlistener.positionX.linearRampToValueAtTime( _position$1.x, endTime );\n\t\t\tlistener.positionY.linearRampToValueAtTime( _position$1.y, endTime );\n\t\t\tlistener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );\n\t\t\tlistener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );\n\t\t\tlistener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );\n\t\t\tlistener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );\n\t\t\tlistener.upX.linearRampToValueAtTime( up.x, endTime );\n\t\t\tlistener.upY.linearRampToValueAtTime( up.y, endTime );\n\t\t\tlistener.upZ.linearRampToValueAtTime( up.z, endTime );\n\n\t\t} else {\n\n\t\t\tlistener.setPosition( _position$1.x, _position$1.y, _position$1.z );\n\t\t\tlistener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );\n\n\t\t}\n\n\t}\n\n}\n\nclass Audio extends Object3D {\n\n\tconstructor( listener ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'Audio';\n\n\t\tthis.listener = listener;\n\t\tthis.context = listener.context;\n\n\t\tthis.gain = this.context.createGain();\n\t\tthis.gain.connect( listener.getInput() );\n\n\t\tthis.autoplay = false;\n\n\t\tthis.buffer = null;\n\t\tthis.detune = 0;\n\t\tthis.loop = false;\n\t\tthis.loopStart = 0;\n\t\tthis.loopEnd = 0;\n\t\tthis.offset = 0;\n\t\tthis.duration = undefined;\n\t\tthis.playbackRate = 1;\n\t\tthis.isPlaying = false;\n\t\tthis.hasPlaybackControl = true;\n\t\tthis.source = null;\n\t\tthis.sourceType = 'empty';\n\n\t\tthis._startedAt = 0;\n\t\tthis._progress = 0;\n\t\tthis._connected = false;\n\n\t\tthis.filters = [];\n\n\t}\n\n\tgetOutput() {\n\n\t\treturn this.gain;\n\n\t}\n\n\tsetNodeSource( audioNode ) {\n\n\t\tthis.hasPlaybackControl = false;\n\t\tthis.sourceType = 'audioNode';\n\t\tthis.source = audioNode;\n\t\tthis.connect();\n\n\t\treturn this;\n\n\t}\n\n\tsetMediaElementSource( mediaElement ) {\n\n\t\tthis.hasPlaybackControl = false;\n\t\tthis.sourceType = 'mediaNode';\n\t\tthis.source = this.context.createMediaElementSource( mediaElement );\n\t\tthis.connect();\n\n\t\treturn this;\n\n\t}\n\n\tsetMediaStreamSource( mediaStream ) {\n\n\t\tthis.hasPlaybackControl = false;\n\t\tthis.sourceType = 'mediaStreamNode';\n\t\tthis.source = this.context.createMediaStreamSource( mediaStream );\n\t\tthis.connect();\n\n\t\treturn this;\n\n\t}\n\n\tsetBuffer( audioBuffer ) {\n\n\t\tthis.buffer = audioBuffer;\n\t\tthis.sourceType = 'buffer';\n\n\t\tif ( this.autoplay ) this.play();\n\n\t\treturn this;\n\n\t}\n\n\tplay( delay = 0 ) {\n\n\t\tif ( this.isPlaying === true ) {\n\n\t\t\tconsole.warn( 'THREE.Audio: Audio is already playing.' );\n\t\t\treturn;\n\n\t\t}\n\n\t\tif ( this.hasPlaybackControl === false ) {\n\n\t\t\tconsole.warn( 'THREE.Audio: this Audio has no playback control.' );\n\t\t\treturn;\n\n\t\t}\n\n\t\tthis._startedAt = this.context.currentTime + delay;\n\n\t\tconst source = this.context.createBufferSource();\n\t\tsource.buffer = this.buffer;\n\t\tsource.loop = this.loop;\n\t\tsource.loopStart = this.loopStart;\n\t\tsource.loopEnd = this.loopEnd;\n\t\tsource.onended = this.onEnded.bind( this );\n\t\tsource.start( this._startedAt, this._progress + this.offset, this.duration );\n\n\t\tthis.isPlaying = true;\n\n\t\tthis.source = source;\n\n\t\tthis.setDetune( this.detune );\n\t\tthis.setPlaybackRate( this.playbackRate );\n\n\t\treturn this.connect();\n\n\t}\n\n\tpause() {\n\n\t\tif ( this.hasPlaybackControl === false ) {\n\n\t\t\tconsole.warn( 'THREE.Audio: this Audio has no playback control.' );\n\t\t\treturn;\n\n\t\t}\n\n\t\tif ( this.isPlaying === true ) {\n\n\t\t\t// update current progress\n\n\t\t\tthis._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;\n\n\t\t\tif ( this.loop === true ) {\n\n\t\t\t\t// ensure _progress does not exceed duration with looped audios\n\n\t\t\t\tthis._progress = this._progress % ( this.duration || this.buffer.duration );\n\n\t\t\t}\n\n\t\t\tthis.source.stop();\n\t\t\tthis.source.onended = null;\n\n\t\t\tthis.isPlaying = false;\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tstop() {\n\n\t\tif ( this.hasPlaybackControl === false ) {\n\n\t\t\tconsole.warn( 'THREE.Audio: this Audio has no playback control.' );\n\t\t\treturn;\n\n\t\t}\n\n\t\tthis._progress = 0;\n\n\t\tif ( this.source !== null ) {\n\n\t\t\tthis.source.stop();\n\t\t\tthis.source.onended = null;\n\n\t\t}\n\n\t\tthis.isPlaying = false;\n\n\t\treturn this;\n\n\t}\n\n\tconnect() {\n\n\t\tif ( this.filters.length > 0 ) {\n\n\t\t\tthis.source.connect( this.filters[ 0 ] );\n\n\t\t\tfor ( let i = 1, l = this.filters.length; i < l; i ++ ) {\n\n\t\t\t\tthis.filters[ i - 1 ].connect( this.filters[ i ] );\n\n\t\t\t}\n\n\t\t\tthis.filters[ this.filters.length - 1 ].connect( this.getOutput() );\n\n\t\t} else {\n\n\t\t\tthis.source.connect( this.getOutput() );\n\n\t\t}\n\n\t\tthis._connected = true;\n\n\t\treturn this;\n\n\t}\n\n\tdisconnect() {\n\n\t\tif ( this.filters.length > 0 ) {\n\n\t\t\tthis.source.disconnect( this.filters[ 0 ] );\n\n\t\t\tfor ( let i = 1, l = this.filters.length; i < l; i ++ ) {\n\n\t\t\t\tthis.filters[ i - 1 ].disconnect( this.filters[ i ] );\n\n\t\t\t}\n\n\t\t\tthis.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );\n\n\t\t} else {\n\n\t\t\tthis.source.disconnect( this.getOutput() );\n\n\t\t}\n\n\t\tthis._connected = false;\n\n\t\treturn this;\n\n\t}\n\n\tgetFilters() {\n\n\t\treturn this.filters;\n\n\t}\n\n\tsetFilters( value ) {\n\n\t\tif ( ! value ) value = [];\n\n\t\tif ( this._connected === true ) {\n\n\t\t\tthis.disconnect();\n\t\t\tthis.filters = value.slice();\n\t\t\tthis.connect();\n\n\t\t} else {\n\n\t\t\tthis.filters = value.slice();\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tsetDetune( value ) {\n\n\t\tthis.detune = value;\n\n\t\tif ( this.source.detune === undefined ) return; // only set detune when available\n\n\t\tif ( this.isPlaying === true ) {\n\n\t\t\tthis.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tgetDetune() {\n\n\t\treturn this.detune;\n\n\t}\n\n\tgetFilter() {\n\n\t\treturn this.getFilters()[ 0 ];\n\n\t}\n\n\tsetFilter( filter ) {\n\n\t\treturn this.setFilters( filter ? [ filter ] : [] );\n\n\t}\n\n\tsetPlaybackRate( value ) {\n\n\t\tif ( this.hasPlaybackControl === false ) {\n\n\t\t\tconsole.warn( 'THREE.Audio: this Audio has no playback control.' );\n\t\t\treturn;\n\n\t\t}\n\n\t\tthis.playbackRate = value;\n\n\t\tif ( this.isPlaying === true ) {\n\n\t\t\tthis.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tgetPlaybackRate() {\n\n\t\treturn this.playbackRate;\n\n\t}\n\n\tonEnded() {\n\n\t\tthis.isPlaying = false;\n\n\t}\n\n\tgetLoop() {\n\n\t\tif ( this.hasPlaybackControl === false ) {\n\n\t\t\tconsole.warn( 'THREE.Audio: this Audio has no playback control.' );\n\t\t\treturn false;\n\n\t\t}\n\n\t\treturn this.loop;\n\n\t}\n\n\tsetLoop( value ) {\n\n\t\tif ( this.hasPlaybackControl === false ) {\n\n\t\t\tconsole.warn( 'THREE.Audio: this Audio has no playback control.' );\n\t\t\treturn;\n\n\t\t}\n\n\t\tthis.loop = value;\n\n\t\tif ( this.isPlaying === true ) {\n\n\t\t\tthis.source.loop = this.loop;\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tsetLoopStart( value ) {\n\n\t\tthis.loopStart = value;\n\n\t\treturn this;\n\n\t}\n\n\tsetLoopEnd( value ) {\n\n\t\tthis.loopEnd = value;\n\n\t\treturn this;\n\n\t}\n\n\tgetVolume() {\n\n\t\treturn this.gain.gain.value;\n\n\t}\n\n\tsetVolume( value ) {\n\n\t\tthis.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );\n\n\t\treturn this;\n\n\t}\n\n}\n\nconst _position = /*@__PURE__*/ new Vector3();\nconst _quaternion = /*@__PURE__*/ new Quaternion();\nconst _scale = /*@__PURE__*/ new Vector3();\nconst _orientation = /*@__PURE__*/ new Vector3();\n\nclass PositionalAudio extends Audio {\n\n\tconstructor( listener ) {\n\n\t\tsuper( listener );\n\n\t\tthis.panner = this.context.createPanner();\n\t\tthis.panner.panningModel = 'HRTF';\n\t\tthis.panner.connect( this.gain );\n\n\t}\n\n\tdisconnect() {\n\n\t\tsuper.disconnect();\n\n\t\tthis.panner.disconnect( this.gain );\n\n\t}\n\n\tgetOutput() {\n\n\t\treturn this.panner;\n\n\t}\n\n\tgetRefDistance() {\n\n\t\treturn this.panner.refDistance;\n\n\t}\n\n\tsetRefDistance( value ) {\n\n\t\tthis.panner.refDistance = value;\n\n\t\treturn this;\n\n\t}\n\n\tgetRolloffFactor() {\n\n\t\treturn this.panner.rolloffFactor;\n\n\t}\n\n\tsetRolloffFactor( value ) {\n\n\t\tthis.panner.rolloffFactor = value;\n\n\t\treturn this;\n\n\t}\n\n\tgetDistanceModel() {\n\n\t\treturn this.panner.distanceModel;\n\n\t}\n\n\tsetDistanceModel( value ) {\n\n\t\tthis.panner.distanceModel = value;\n\n\t\treturn this;\n\n\t}\n\n\tgetMaxDistance() {\n\n\t\treturn this.panner.maxDistance;\n\n\t}\n\n\tsetMaxDistance( value ) {\n\n\t\tthis.panner.maxDistance = value;\n\n\t\treturn this;\n\n\t}\n\n\tsetDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {\n\n\t\tthis.panner.coneInnerAngle = coneInnerAngle;\n\t\tthis.panner.coneOuterAngle = coneOuterAngle;\n\t\tthis.panner.coneOuterGain = coneOuterGain;\n\n\t\treturn this;\n\n\t}\n\n\tupdateMatrixWorld( force ) {\n\n\t\tsuper.updateMatrixWorld( force );\n\n\t\tif ( this.hasPlaybackControl === true && this.isPlaying === false ) return;\n\n\t\tthis.matrixWorld.decompose( _position, _quaternion, _scale );\n\n\t\t_orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );\n\n\t\tconst panner = this.panner;\n\n\t\tif ( panner.positionX ) {\n\n\t\t\t// code path for Chrome and Firefox (see #14393)\n\n\t\t\tconst endTime = this.context.currentTime + this.listener.timeDelta;\n\n\t\t\tpanner.positionX.linearRampToValueAtTime( _position.x, endTime );\n\t\t\tpanner.positionY.linearRampToValueAtTime( _position.y, endTime );\n\t\t\tpanner.positionZ.linearRampToValueAtTime( _position.z, endTime );\n\t\t\tpanner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );\n\t\t\tpanner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );\n\t\t\tpanner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );\n\n\t\t} else {\n\n\t\t\tpanner.setPosition( _position.x, _position.y, _position.z );\n\t\t\tpanner.setOrientation( _orientation.x, _orientation.y, _orientation.z );\n\n\t\t}\n\n\t}\n\n}\n\nclass AudioAnalyser {\n\n\tconstructor( audio, fftSize = 2048 ) {\n\n\t\tthis.analyser = audio.context.createAnalyser();\n\t\tthis.analyser.fftSize = fftSize;\n\n\t\tthis.data = new Uint8Array( this.analyser.frequencyBinCount );\n\n\t\taudio.getOutput().connect( this.analyser );\n\n\t}\n\n\n\tgetFrequencyData() {\n\n\t\tthis.analyser.getByteFrequencyData( this.data );\n\n\t\treturn this.data;\n\n\t}\n\n\tgetAverageFrequency() {\n\n\t\tlet value = 0;\n\t\tconst data = this.getFrequencyData();\n\n\t\tfor ( let i = 0; i < data.length; i ++ ) {\n\n\t\t\tvalue += data[ i ];\n\n\t\t}\n\n\t\treturn value / data.length;\n\n\t}\n\n}\n\nclass PropertyMixer {\n\n\tconstructor( binding, typeName, valueSize ) {\n\n\t\tthis.binding = binding;\n\t\tthis.valueSize = valueSize;\n\n\t\tlet mixFunction,\n\t\t\tmixFunctionAdditive,\n\t\t\tsetIdentity;\n\n\t\t// buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]\n\t\t//\n\t\t// interpolators can use .buffer as their .result\n\t\t// the data then goes to 'incoming'\n\t\t//\n\t\t// 'accu0' and 'accu1' are used frame-interleaved for\n\t\t// the cumulative result and are compared to detect\n\t\t// changes\n\t\t//\n\t\t// 'orig' stores the original state of the property\n\t\t//\n\t\t// 'add' is used for additive cumulative results\n\t\t//\n\t\t// 'work' is optional and is only present for quaternion types. It is used\n\t\t// to store intermediate quaternion multiplication results\n\n\t\tswitch ( typeName ) {\n\n\t\t\tcase 'quaternion':\n\t\t\t\tmixFunction = this._slerp;\n\t\t\t\tmixFunctionAdditive = this._slerpAdditive;\n\t\t\t\tsetIdentity = this._setAdditiveIdentityQuaternion;\n\n\t\t\t\tthis.buffer = new Float64Array( valueSize * 6 );\n\t\t\t\tthis._workIndex = 5;\n\t\t\t\tbreak;\n\n\t\t\tcase 'string':\n\t\t\tcase 'bool':\n\t\t\t\tmixFunction = this._select;\n\n\t\t\t\t// Use the regular mix function and for additive on these types,\n\t\t\t\t// additive is not relevant for non-numeric types\n\t\t\t\tmixFunctionAdditive = this._select;\n\n\t\t\t\tsetIdentity = this._setAdditiveIdentityOther;\n\n\t\t\t\tthis.buffer = new Array( valueSize * 5 );\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tmixFunction = this._lerp;\n\t\t\t\tmixFunctionAdditive = this._lerpAdditive;\n\t\t\t\tsetIdentity = this._setAdditiveIdentityNumeric;\n\n\t\t\t\tthis.buffer = new Float64Array( valueSize * 5 );\n\n\t\t}\n\n\t\tthis._mixBufferRegion = mixFunction;\n\t\tthis._mixBufferRegionAdditive = mixFunctionAdditive;\n\t\tthis._setIdentity = setIdentity;\n\t\tthis._origIndex = 3;\n\t\tthis._addIndex = 4;\n\n\t\tthis.cumulativeWeight = 0;\n\t\tthis.cumulativeWeightAdditive = 0;\n\n\t\tthis.useCount = 0;\n\t\tthis.referenceCount = 0;\n\n\t}\n\n\t// accumulate data in the 'incoming' region into 'accu'\n\taccumulate( accuIndex, weight ) {\n\n\t\t// note: happily accumulating nothing when weight = 0, the caller knows\n\t\t// the weight and shouldn't have made the call in the first place\n\n\t\tconst buffer = this.buffer,\n\t\t\tstride = this.valueSize,\n\t\t\toffset = accuIndex * stride + stride;\n\n\t\tlet currentWeight = this.cumulativeWeight;\n\n\t\tif ( currentWeight === 0 ) {\n\n\t\t\t// accuN := incoming * weight\n\n\t\t\tfor ( let i = 0; i !== stride; ++ i ) {\n\n\t\t\t\tbuffer[ offset + i ] = buffer[ i ];\n\n\t\t\t}\n\n\t\t\tcurrentWeight = weight;\n\n\t\t} else {\n\n\t\t\t// accuN := accuN + incoming * weight\n\n\t\t\tcurrentWeight += weight;\n\t\t\tconst mix = weight / currentWeight;\n\t\t\tthis._mixBufferRegion( buffer, offset, 0, mix, stride );\n\n\t\t}\n\n\t\tthis.cumulativeWeight = currentWeight;\n\n\t}\n\n\t// accumulate data in the 'incoming' region into 'add'\n\taccumulateAdditive( weight ) {\n\n\t\tconst buffer = this.buffer,\n\t\t\tstride = this.valueSize,\n\t\t\toffset = stride * this._addIndex;\n\n\t\tif ( this.cumulativeWeightAdditive === 0 ) {\n\n\t\t\t// add = identity\n\n\t\t\tthis._setIdentity();\n\n\t\t}\n\n\t\t// add := add + incoming * weight\n\n\t\tthis._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );\n\t\tthis.cumulativeWeightAdditive += weight;\n\n\t}\n\n\t// apply the state of 'accu' to the binding when accus differ\n\tapply( accuIndex ) {\n\n\t\tconst stride = this.valueSize,\n\t\t\tbuffer = this.buffer,\n\t\t\toffset = accuIndex * stride + stride,\n\n\t\t\tweight = this.cumulativeWeight,\n\t\t\tweightAdditive = this.cumulativeWeightAdditive,\n\n\t\t\tbinding = this.binding;\n\n\t\tthis.cumulativeWeight = 0;\n\t\tthis.cumulativeWeightAdditive = 0;\n\n\t\tif ( weight < 1 ) {\n\n\t\t\t// accuN := accuN + original * ( 1 - cumulativeWeight )\n\n\t\t\tconst originalValueOffset = stride * this._origIndex;\n\n\t\t\tthis._mixBufferRegion(\n\t\t\t\tbuffer, offset, originalValueOffset, 1 - weight, stride );\n\n\t\t}\n\n\t\tif ( weightAdditive > 0 ) {\n\n\t\t\t// accuN := accuN + additive accuN\n\n\t\t\tthis._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );\n\n\t\t}\n\n\t\tfor ( let i = stride, e = stride + stride; i !== e; ++ i ) {\n\n\t\t\tif ( buffer[ i ] !== buffer[ i + stride ] ) {\n\n\t\t\t\t// value has changed -> update scene graph\n\n\t\t\t\tbinding.setValue( buffer, offset );\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t// remember the state of the bound property and copy it to both accus\n\tsaveOriginalState() {\n\n\t\tconst binding = this.binding;\n\n\t\tconst buffer = this.buffer,\n\t\t\tstride = this.valueSize,\n\n\t\t\toriginalValueOffset = stride * this._origIndex;\n\n\t\tbinding.getValue( buffer, originalValueOffset );\n\n\t\t// accu[0..1] := orig -- initially detect changes against the original\n\t\tfor ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {\n\n\t\t\tbuffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];\n\n\t\t}\n\n\t\t// Add to identity for additive\n\t\tthis._setIdentity();\n\n\t\tthis.cumulativeWeight = 0;\n\t\tthis.cumulativeWeightAdditive = 0;\n\n\t}\n\n\t// apply the state previously taken via 'saveOriginalState' to the binding\n\trestoreOriginalState() {\n\n\t\tconst originalValueOffset = this.valueSize * 3;\n\t\tthis.binding.setValue( this.buffer, originalValueOffset );\n\n\t}\n\n\t_setAdditiveIdentityNumeric() {\n\n\t\tconst startIndex = this._addIndex * this.valueSize;\n\t\tconst endIndex = startIndex + this.valueSize;\n\n\t\tfor ( let i = startIndex; i < endIndex; i ++ ) {\n\n\t\t\tthis.buffer[ i ] = 0;\n\n\t\t}\n\n\t}\n\n\t_setAdditiveIdentityQuaternion() {\n\n\t\tthis._setAdditiveIdentityNumeric();\n\t\tthis.buffer[ this._addIndex * this.valueSize + 3 ] = 1;\n\n\t}\n\n\t_setAdditiveIdentityOther() {\n\n\t\tconst startIndex = this._origIndex * this.valueSize;\n\t\tconst targetIndex = this._addIndex * this.valueSize;\n\n\t\tfor ( let i = 0; i < this.valueSize; i ++ ) {\n\n\t\t\tthis.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];\n\n\t\t}\n\n\t}\n\n\n\t// mix functions\n\n\t_select( buffer, dstOffset, srcOffset, t, stride ) {\n\n\t\tif ( t >= 0.5 ) {\n\n\t\t\tfor ( let i = 0; i !== stride; ++ i ) {\n\n\t\t\t\tbuffer[ dstOffset + i ] = buffer[ srcOffset + i ];\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t_slerp( buffer, dstOffset, srcOffset, t ) {\n\n\t\tQuaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );\n\n\t}\n\n\t_slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {\n\n\t\tconst workOffset = this._workIndex * stride;\n\n\t\t// Store result in intermediate buffer offset\n\t\tQuaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );\n\n\t\t// Slerp to the intermediate result\n\t\tQuaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );\n\n\t}\n\n\t_lerp( buffer, dstOffset, srcOffset, t, stride ) {\n\n\t\tconst s = 1 - t;\n\n\t\tfor ( let i = 0; i !== stride; ++ i ) {\n\n\t\t\tconst j = dstOffset + i;\n\n\t\t\tbuffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;\n\n\t\t}\n\n\t}\n\n\t_lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {\n\n\t\tfor ( let i = 0; i !== stride; ++ i ) {\n\n\t\t\tconst j = dstOffset + i;\n\n\t\t\tbuffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;\n\n\t\t}\n\n\t}\n\n}\n\n// Characters [].:/ are reserved for track binding syntax.\nconst _RESERVED_CHARS_RE = '\\\\[\\\\]\\\\.:\\\\/';\nconst _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );\n\n// Attempts to allow node names from any language. ES5's `\\w` regexp matches\n// only latin characters, and the unicode \\p{L} is not yet supported. So\n// instead, we exclude reserved characters and match everything else.\nconst _wordChar = '[^' + _RESERVED_CHARS_RE + ']';\nconst _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\\\.', '' ) + ']';\n\n// Parent directories, delimited by '/' or ':'. Currently unused, but must\n// be matched to parse the rest of the track name.\nconst _directoryRe = /*@__PURE__*/ /((?:WC+[\\/:])*)/.source.replace( 'WC', _wordChar );\n\n// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.\nconst _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );\n\n// Object on target node, and accessor. May not contain reserved\n// characters. Accessor may contain any character except closing bracket.\nconst _objectRe = /*@__PURE__*/ /(?:\\.(WC+)(?:\\[(.+)\\])?)?/.source.replace( 'WC', _wordChar );\n\n// Property and accessor. May not contain reserved characters. Accessor may\n// contain any non-bracket characters.\nconst _propertyRe = /*@__PURE__*/ /\\.(WC+)(?:\\[(.+)\\])?/.source.replace( 'WC', _wordChar );\n\nconst _trackRe = new RegExp( ''\n\t+ '^'\n\t+ _directoryRe\n\t+ _nodeRe\n\t+ _objectRe\n\t+ _propertyRe\n\t+ '$'\n);\n\nconst _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];\n\nclass Composite {\n\n\tconstructor( targetGroup, path, optionalParsedPath ) {\n\n\t\tconst parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );\n\n\t\tthis._targetGroup = targetGroup;\n\t\tthis._bindings = targetGroup.subscribe_( path, parsedPath );\n\n\t}\n\n\tgetValue( array, offset ) {\n\n\t\tthis.bind(); // bind all binding\n\n\t\tconst firstValidIndex = this._targetGroup.nCachedObjects_,\n\t\t\tbinding = this._bindings[ firstValidIndex ];\n\n\t\t// and only call .getValue on the first\n\t\tif ( binding !== undefined ) binding.getValue( array, offset );\n\n\t}\n\n\tsetValue( array, offset ) {\n\n\t\tconst bindings = this._bindings;\n\n\t\tfor ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {\n\n\t\t\tbindings[ i ].setValue( array, offset );\n\n\t\t}\n\n\t}\n\n\tbind() {\n\n\t\tconst bindings = this._bindings;\n\n\t\tfor ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {\n\n\t\t\tbindings[ i ].bind();\n\n\t\t}\n\n\t}\n\n\tunbind() {\n\n\t\tconst bindings = this._bindings;\n\n\t\tfor ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {\n\n\t\t\tbindings[ i ].unbind();\n\n\t\t}\n\n\t}\n\n}\n\n// Note: This class uses a State pattern on a per-method basis:\n// 'bind' sets 'this.getValue' / 'setValue' and shadows the\n// prototype version of these methods with one that represents\n// the bound state. When the property is not found, the methods\n// become no-ops.\nclass PropertyBinding {\n\n\tconstructor( rootNode, path, parsedPath ) {\n\n\t\tthis.path = path;\n\t\tthis.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );\n\n\t\tthis.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );\n\n\t\tthis.rootNode = rootNode;\n\n\t\t// initial state of these methods that calls 'bind'\n\t\tthis.getValue = this._getValue_unbound;\n\t\tthis.setValue = this._setValue_unbound;\n\n\t}\n\n\n\tstatic create( root, path, parsedPath ) {\n\n\t\tif ( ! ( root && root.isAnimationObjectGroup ) ) {\n\n\t\t\treturn new PropertyBinding( root, path, parsedPath );\n\n\t\t} else {\n\n\t\t\treturn new PropertyBinding.Composite( root, path, parsedPath );\n\n\t\t}\n\n\t}\n\n\t/**\n\t * Replaces spaces with underscores and removes unsupported characters from\n\t * node names, to ensure compatibility with parseTrackName().\n\t *\n\t * @param {string} name Node name to be sanitized.\n\t * @return {string}\n\t */\n\tstatic sanitizeNodeName( name ) {\n\n\t\treturn name.replace( /\\s/g, '_' ).replace( _reservedRe, '' );\n\n\t}\n\n\tstatic parseTrackName( trackName ) {\n\n\t\tconst matches = _trackRe.exec( trackName );\n\n\t\tif ( matches === null ) {\n\n\t\t\tthrow new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );\n\n\t\t}\n\n\t\tconst results = {\n\t\t\t// directoryName: matches[ 1 ], // (tschw) currently unused\n\t\t\tnodeName: matches[ 2 ],\n\t\t\tobjectName: matches[ 3 ],\n\t\t\tobjectIndex: matches[ 4 ],\n\t\t\tpropertyName: matches[ 5 ], // required\n\t\t\tpropertyIndex: matches[ 6 ]\n\t\t};\n\n\t\tconst lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );\n\n\t\tif ( lastDot !== undefined && lastDot !== - 1 ) {\n\n\t\t\tconst objectName = results.nodeName.substring( lastDot + 1 );\n\n\t\t\t// Object names must be checked against an allowlist. Otherwise, there\n\t\t\t// is no way to parse 'foo.bar.baz': 'baz' must be a property, but\n\t\t\t// 'bar' could be the objectName, or part of a nodeName (which can\n\t\t\t// include '.' characters).\n\t\t\tif ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {\n\n\t\t\t\tresults.nodeName = results.nodeName.substring( 0, lastDot );\n\t\t\t\tresults.objectName = objectName;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( results.propertyName === null || results.propertyName.length === 0 ) {\n\n\t\t\tthrow new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );\n\n\t\t}\n\n\t\treturn results;\n\n\t}\n\n\tstatic findNode( root, nodeName ) {\n\n\t\tif ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {\n\n\t\t\treturn root;\n\n\t\t}\n\n\t\t// search into skeleton bones.\n\t\tif ( root.skeleton ) {\n\n\t\t\tconst bone = root.skeleton.getBoneByName( nodeName );\n\n\t\t\tif ( bone !== undefined ) {\n\n\t\t\t\treturn bone;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// search into node subtree.\n\t\tif ( root.children ) {\n\n\t\t\tconst searchNodeSubtree = function ( children ) {\n\n\t\t\t\tfor ( let i = 0; i < children.length; i ++ ) {\n\n\t\t\t\t\tconst childNode = children[ i ];\n\n\t\t\t\t\tif ( childNode.name === nodeName || childNode.uuid === nodeName ) {\n\n\t\t\t\t\t\treturn childNode;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tconst result = searchNodeSubtree( childNode.children );\n\n\t\t\t\t\tif ( result ) return result;\n\n\t\t\t\t}\n\n\t\t\t\treturn null;\n\n\t\t\t};\n\n\t\t\tconst subTreeNode = searchNodeSubtree( root.children );\n\n\t\t\tif ( subTreeNode ) {\n\n\t\t\t\treturn subTreeNode;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn null;\n\n\t}\n\n\t// these are used to \"bind\" a nonexistent property\n\t_getValue_unavailable() {}\n\t_setValue_unavailable() {}\n\n\t// Getters\n\n\t_getValue_direct( buffer, offset ) {\n\n\t\tbuffer[ offset ] = this.targetObject[ this.propertyName ];\n\n\t}\n\n\t_getValue_array( buffer, offset ) {\n\n\t\tconst source = this.resolvedProperty;\n\n\t\tfor ( let i = 0, n = source.length; i !== n; ++ i ) {\n\n\t\t\tbuffer[ offset ++ ] = source[ i ];\n\n\t\t}\n\n\t}\n\n\t_getValue_arrayElement( buffer, offset ) {\n\n\t\tbuffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];\n\n\t}\n\n\t_getValue_toArray( buffer, offset ) {\n\n\t\tthis.resolvedProperty.toArray( buffer, offset );\n\n\t}\n\n\t// Direct\n\n\t_setValue_direct( buffer, offset ) {\n\n\t\tthis.targetObject[ this.propertyName ] = buffer[ offset ];\n\n\t}\n\n\t_setValue_direct_setNeedsUpdate( buffer, offset ) {\n\n\t\tthis.targetObject[ this.propertyName ] = buffer[ offset ];\n\t\tthis.targetObject.needsUpdate = true;\n\n\t}\n\n\t_setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {\n\n\t\tthis.targetObject[ this.propertyName ] = buffer[ offset ];\n\t\tthis.targetObject.matrixWorldNeedsUpdate = true;\n\n\t}\n\n\t// EntireArray\n\n\t_setValue_array( buffer, offset ) {\n\n\t\tconst dest = this.resolvedProperty;\n\n\t\tfor ( let i = 0, n = dest.length; i !== n; ++ i ) {\n\n\t\t\tdest[ i ] = buffer[ offset ++ ];\n\n\t\t}\n\n\t}\n\n\t_setValue_array_setNeedsUpdate( buffer, offset ) {\n\n\t\tconst dest = this.resolvedProperty;\n\n\t\tfor ( let i = 0, n = dest.length; i !== n; ++ i ) {\n\n\t\t\tdest[ i ] = buffer[ offset ++ ];\n\n\t\t}\n\n\t\tthis.targetObject.needsUpdate = true;\n\n\t}\n\n\t_setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {\n\n\t\tconst dest = this.resolvedProperty;\n\n\t\tfor ( let i = 0, n = dest.length; i !== n; ++ i ) {\n\n\t\t\tdest[ i ] = buffer[ offset ++ ];\n\n\t\t}\n\n\t\tthis.targetObject.matrixWorldNeedsUpdate = true;\n\n\t}\n\n\t// ArrayElement\n\n\t_setValue_arrayElement( buffer, offset ) {\n\n\t\tthis.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];\n\n\t}\n\n\t_setValue_arrayElement_setNeedsUpdate( buffer, offset ) {\n\n\t\tthis.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];\n\t\tthis.targetObject.needsUpdate = true;\n\n\t}\n\n\t_setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {\n\n\t\tthis.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];\n\t\tthis.targetObject.matrixWorldNeedsUpdate = true;\n\n\t}\n\n\t// HasToFromArray\n\n\t_setValue_fromArray( buffer, offset ) {\n\n\t\tthis.resolvedProperty.fromArray( buffer, offset );\n\n\t}\n\n\t_setValue_fromArray_setNeedsUpdate( buffer, offset ) {\n\n\t\tthis.resolvedProperty.fromArray( buffer, offset );\n\t\tthis.targetObject.needsUpdate = true;\n\n\t}\n\n\t_setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {\n\n\t\tthis.resolvedProperty.fromArray( buffer, offset );\n\t\tthis.targetObject.matrixWorldNeedsUpdate = true;\n\n\t}\n\n\t_getValue_unbound( targetArray, offset ) {\n\n\t\tthis.bind();\n\t\tthis.getValue( targetArray, offset );\n\n\t}\n\n\t_setValue_unbound( sourceArray, offset ) {\n\n\t\tthis.bind();\n\t\tthis.setValue( sourceArray, offset );\n\n\t}\n\n\t// create getter / setter pair for a property in the scene graph\n\tbind() {\n\n\t\tlet targetObject = this.node;\n\t\tconst parsedPath = this.parsedPath;\n\n\t\tconst objectName = parsedPath.objectName;\n\t\tconst propertyName = parsedPath.propertyName;\n\t\tlet propertyIndex = parsedPath.propertyIndex;\n\n\t\tif ( ! targetObject ) {\n\n\t\t\ttargetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );\n\n\t\t\tthis.node = targetObject;\n\n\t\t}\n\n\t\t// set fail state so we can just 'return' on error\n\t\tthis.getValue = this._getValue_unavailable;\n\t\tthis.setValue = this._setValue_unavailable;\n\n\t\t// ensure there is a value node\n\t\tif ( ! targetObject ) {\n\n\t\t\tconsole.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\\'t found.' );\n\t\t\treturn;\n\n\t\t}\n\n\t\tif ( objectName ) {\n\n\t\t\tlet objectIndex = parsedPath.objectIndex;\n\n\t\t\t// special cases were we need to reach deeper into the hierarchy to get the face materials....\n\t\t\tswitch ( objectName ) {\n\n\t\t\t\tcase 'materials':\n\n\t\t\t\t\tif ( ! targetObject.material ) {\n\n\t\t\t\t\t\tconsole.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( ! targetObject.material.materials ) {\n\n\t\t\t\t\t\tconsole.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t}\n\n\t\t\t\t\ttargetObject = targetObject.material.materials;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'bones':\n\n\t\t\t\t\tif ( ! targetObject.skeleton ) {\n\n\t\t\t\t\t\tconsole.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// potential future optimization: skip this if propertyIndex is already an integer\n\t\t\t\t\t// and convert the integer string to a true integer.\n\n\t\t\t\t\ttargetObject = targetObject.skeleton.bones;\n\n\t\t\t\t\t// support resolving morphTarget names into indices.\n\t\t\t\t\tfor ( let i = 0; i < targetObject.length; i ++ ) {\n\n\t\t\t\t\t\tif ( targetObject[ i ].name === objectIndex ) {\n\n\t\t\t\t\t\t\tobjectIndex = i;\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'map':\n\n\t\t\t\t\tif ( 'map' in targetObject ) {\n\n\t\t\t\t\t\ttargetObject = targetObject.map;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( ! targetObject.material ) {\n\n\t\t\t\t\t\tconsole.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( ! targetObject.material.map ) {\n\n\t\t\t\t\t\tconsole.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t}\n\n\t\t\t\t\ttargetObject = targetObject.material.map;\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\n\t\t\t\t\tif ( targetObject[ objectName ] === undefined ) {\n\n\t\t\t\t\t\tconsole.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t}\n\n\t\t\t\t\ttargetObject = targetObject[ objectName ];\n\n\t\t\t}\n\n\n\t\t\tif ( objectIndex !== undefined ) {\n\n\t\t\t\tif ( targetObject[ objectIndex ] === undefined ) {\n\n\t\t\t\t\tconsole.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );\n\t\t\t\t\treturn;\n\n\t\t\t\t}\n\n\t\t\t\ttargetObject = targetObject[ objectIndex ];\n\n\t\t\t}\n\n\t\t}\n\n\t\t// resolve property\n\t\tconst nodeProperty = targetObject[ propertyName ];\n\n\t\tif ( nodeProperty === undefined ) {\n\n\t\t\tconst nodeName = parsedPath.nodeName;\n\n\t\t\tconsole.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +\n\t\t\t\t'.' + propertyName + ' but it wasn\\'t found.', targetObject );\n\t\t\treturn;\n\n\t\t}\n\n\t\t// determine versioning scheme\n\t\tlet versioning = this.Versioning.None;\n\n\t\tthis.targetObject = targetObject;\n\n\t\tif ( targetObject.needsUpdate !== undefined ) { // material\n\n\t\t\tversioning = this.Versioning.NeedsUpdate;\n\n\t\t} else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform\n\n\t\t\tversioning = this.Versioning.MatrixWorldNeedsUpdate;\n\n\t\t}\n\n\t\t// determine how the property gets bound\n\t\tlet bindingType = this.BindingType.Direct;\n\n\t\tif ( propertyIndex !== undefined ) {\n\n\t\t\t// access a sub element of the property array (only primitives are supported right now)\n\n\t\t\tif ( propertyName === 'morphTargetInfluences' ) {\n\n\t\t\t\t// potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.\n\n\t\t\t\t// support resolving morphTarget names into indices.\n\t\t\t\tif ( ! targetObject.geometry ) {\n\n\t\t\t\t\tconsole.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );\n\t\t\t\t\treturn;\n\n\t\t\t\t}\n\n\t\t\t\tif ( ! targetObject.geometry.morphAttributes ) {\n\n\t\t\t\t\tconsole.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );\n\t\t\t\t\treturn;\n\n\t\t\t\t}\n\n\t\t\t\tif ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {\n\n\t\t\t\t\tpropertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tbindingType = this.BindingType.ArrayElement;\n\n\t\t\tthis.resolvedProperty = nodeProperty;\n\t\t\tthis.propertyIndex = propertyIndex;\n\n\t\t} else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {\n\n\t\t\t// must use copy for Object3D.Euler/Quaternion\n\n\t\t\tbindingType = this.BindingType.HasFromToArray;\n\n\t\t\tthis.resolvedProperty = nodeProperty;\n\n\t\t} else if ( Array.isArray( nodeProperty ) ) {\n\n\t\t\tbindingType = this.BindingType.EntireArray;\n\n\t\t\tthis.resolvedProperty = nodeProperty;\n\n\t\t} else {\n\n\t\t\tthis.propertyName = propertyName;\n\n\t\t}\n\n\t\t// select getter / setter\n\t\tthis.getValue = this.GetterByBindingType[ bindingType ];\n\t\tthis.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];\n\n\t}\n\n\tunbind() {\n\n\t\tthis.node = null;\n\n\t\t// back to the prototype version of getValue / setValue\n\t\t// note: avoiding to mutate the shape of 'this' via 'delete'\n\t\tthis.getValue = this._getValue_unbound;\n\t\tthis.setValue = this._setValue_unbound;\n\n\t}\n\n}\n\nPropertyBinding.Composite = Composite;\n\nPropertyBinding.prototype.BindingType = {\n\tDirect: 0,\n\tEntireArray: 1,\n\tArrayElement: 2,\n\tHasFromToArray: 3\n};\n\nPropertyBinding.prototype.Versioning = {\n\tNone: 0,\n\tNeedsUpdate: 1,\n\tMatrixWorldNeedsUpdate: 2\n};\n\nPropertyBinding.prototype.GetterByBindingType = [\n\n\tPropertyBinding.prototype._getValue_direct,\n\tPropertyBinding.prototype._getValue_array,\n\tPropertyBinding.prototype._getValue_arrayElement,\n\tPropertyBinding.prototype._getValue_toArray,\n\n];\n\nPropertyBinding.prototype.SetterByBindingTypeAndVersioning = [\n\n\t[\n\t\t// Direct\n\t\tPropertyBinding.prototype._setValue_direct,\n\t\tPropertyBinding.prototype._setValue_direct_setNeedsUpdate,\n\t\tPropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,\n\n\t], [\n\n\t\t// EntireArray\n\n\t\tPropertyBinding.prototype._setValue_array,\n\t\tPropertyBinding.prototype._setValue_array_setNeedsUpdate,\n\t\tPropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,\n\n\t], [\n\n\t\t// ArrayElement\n\t\tPropertyBinding.prototype._setValue_arrayElement,\n\t\tPropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,\n\t\tPropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,\n\n\t], [\n\n\t\t// HasToFromArray\n\t\tPropertyBinding.prototype._setValue_fromArray,\n\t\tPropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,\n\t\tPropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,\n\n\t]\n\n];\n\n/**\n *\n * A group of objects that receives a shared animation state.\n *\n * Usage:\n *\n * - Add objects you would otherwise pass as 'root' to the\n * constructor or the .clipAction method of AnimationMixer.\n *\n * - Instead pass this object as 'root'.\n *\n * - You can also add and remove objects later when the mixer\n * is running.\n *\n * Note:\n *\n * Objects of this class appear as one object to the mixer,\n * so cache control of the individual objects must be done\n * on the group.\n *\n * Limitation:\n *\n * - The animated properties must be compatible among the\n * all objects in the group.\n *\n * - A single property can either be controlled through a\n * target group or directly, but not both.\n */\n\nclass AnimationObjectGroup {\n\n\tconstructor() {\n\n\t\tthis.isAnimationObjectGroup = true;\n\n\t\tthis.uuid = generateUUID();\n\n\t\t// cached objects followed by the active ones\n\t\tthis._objects = Array.prototype.slice.call( arguments );\n\n\t\tthis.nCachedObjects_ = 0; // threshold\n\t\t// note: read by PropertyBinding.Composite\n\n\t\tconst indices = {};\n\t\tthis._indicesByUUID = indices; // for bookkeeping\n\n\t\tfor ( let i = 0, n = arguments.length; i !== n; ++ i ) {\n\n\t\t\tindices[ arguments[ i ].uuid ] = i;\n\n\t\t}\n\n\t\tthis._paths = []; // inside: string\n\t\tthis._parsedPaths = []; // inside: { we don't care, here }\n\t\tthis._bindings = []; // inside: Array< PropertyBinding >\n\t\tthis._bindingsIndicesByPath = {}; // inside: indices in these arrays\n\n\t\tconst scope = this;\n\n\t\tthis.stats = {\n\n\t\t\tobjects: {\n\t\t\t\tget total() {\n\n\t\t\t\t\treturn scope._objects.length;\n\n\t\t\t\t},\n\t\t\t\tget inUse() {\n\n\t\t\t\t\treturn this.total - scope.nCachedObjects_;\n\n\t\t\t\t}\n\t\t\t},\n\t\t\tget bindingsPerObject() {\n\n\t\t\t\treturn scope._bindings.length;\n\n\t\t\t}\n\n\t\t};\n\n\t}\n\n\tadd() {\n\n\t\tconst objects = this._objects,\n\t\t\tindicesByUUID = this._indicesByUUID,\n\t\t\tpaths = this._paths,\n\t\t\tparsedPaths = this._parsedPaths,\n\t\t\tbindings = this._bindings,\n\t\t\tnBindings = bindings.length;\n\n\t\tlet knownObject = undefined,\n\t\t\tnObjects = objects.length,\n\t\t\tnCachedObjects = this.nCachedObjects_;\n\n\t\tfor ( let i = 0, n = arguments.length; i !== n; ++ i ) {\n\n\t\t\tconst object = arguments[ i ],\n\t\t\t\tuuid = object.uuid;\n\t\t\tlet index = indicesByUUID[ uuid ];\n\n\t\t\tif ( index === undefined ) {\n\n\t\t\t\t// unknown object -> add it to the ACTIVE region\n\n\t\t\t\tindex = nObjects ++;\n\t\t\t\tindicesByUUID[ uuid ] = index;\n\t\t\t\tobjects.push( object );\n\n\t\t\t\t// accounting is done, now do the same for all bindings\n\n\t\t\t\tfor ( let j = 0, m = nBindings; j !== m; ++ j ) {\n\n\t\t\t\t\tbindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );\n\n\t\t\t\t}\n\n\t\t\t} else if ( index < nCachedObjects ) {\n\n\t\t\t\tknownObject = objects[ index ];\n\n\t\t\t\t// move existing object to the ACTIVE region\n\n\t\t\t\tconst firstActiveIndex = -- nCachedObjects,\n\t\t\t\t\tlastCachedObject = objects[ firstActiveIndex ];\n\n\t\t\t\tindicesByUUID[ lastCachedObject.uuid ] = index;\n\t\t\t\tobjects[ index ] = lastCachedObject;\n\n\t\t\t\tindicesByUUID[ uuid ] = firstActiveIndex;\n\t\t\t\tobjects[ firstActiveIndex ] = object;\n\n\t\t\t\t// accounting is done, now do the same for all bindings\n\n\t\t\t\tfor ( let j = 0, m = nBindings; j !== m; ++ j ) {\n\n\t\t\t\t\tconst bindingsForPath = bindings[ j ],\n\t\t\t\t\t\tlastCached = bindingsForPath[ firstActiveIndex ];\n\n\t\t\t\t\tlet binding = bindingsForPath[ index ];\n\n\t\t\t\t\tbindingsForPath[ index ] = lastCached;\n\n\t\t\t\t\tif ( binding === undefined ) {\n\n\t\t\t\t\t\t// since we do not bother to create new bindings\n\t\t\t\t\t\t// for objects that are cached, the binding may\n\t\t\t\t\t\t// or may not exist\n\n\t\t\t\t\t\tbinding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbindingsForPath[ firstActiveIndex ] = binding;\n\n\t\t\t\t}\n\n\t\t\t} else if ( objects[ index ] !== knownObject ) {\n\n\t\t\t\tconsole.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +\n\t\t\t\t\t'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );\n\n\t\t\t} // else the object is already where we want it to be\n\n\t\t} // for arguments\n\n\t\tthis.nCachedObjects_ = nCachedObjects;\n\n\t}\n\n\tremove() {\n\n\t\tconst objects = this._objects,\n\t\t\tindicesByUUID = this._indicesByUUID,\n\t\t\tbindings = this._bindings,\n\t\t\tnBindings = bindings.length;\n\n\t\tlet nCachedObjects = this.nCachedObjects_;\n\n\t\tfor ( let i = 0, n = arguments.length; i !== n; ++ i ) {\n\n\t\t\tconst object = arguments[ i ],\n\t\t\t\tuuid = object.uuid,\n\t\t\t\tindex = indicesByUUID[ uuid ];\n\n\t\t\tif ( index !== undefined && index >= nCachedObjects ) {\n\n\t\t\t\t// move existing object into the CACHED region\n\n\t\t\t\tconst lastCachedIndex = nCachedObjects ++,\n\t\t\t\t\tfirstActiveObject = objects[ lastCachedIndex ];\n\n\t\t\t\tindicesByUUID[ firstActiveObject.uuid ] = index;\n\t\t\t\tobjects[ index ] = firstActiveObject;\n\n\t\t\t\tindicesByUUID[ uuid ] = lastCachedIndex;\n\t\t\t\tobjects[ lastCachedIndex ] = object;\n\n\t\t\t\t// accounting is done, now do the same for all bindings\n\n\t\t\t\tfor ( let j = 0, m = nBindings; j !== m; ++ j ) {\n\n\t\t\t\t\tconst bindingsForPath = bindings[ j ],\n\t\t\t\t\t\tfirstActive = bindingsForPath[ lastCachedIndex ],\n\t\t\t\t\t\tbinding = bindingsForPath[ index ];\n\n\t\t\t\t\tbindingsForPath[ index ] = firstActive;\n\t\t\t\t\tbindingsForPath[ lastCachedIndex ] = binding;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} // for arguments\n\n\t\tthis.nCachedObjects_ = nCachedObjects;\n\n\t}\n\n\t// remove & forget\n\tuncache() {\n\n\t\tconst objects = this._objects,\n\t\t\tindicesByUUID = this._indicesByUUID,\n\t\t\tbindings = this._bindings,\n\t\t\tnBindings = bindings.length;\n\n\t\tlet nCachedObjects = this.nCachedObjects_,\n\t\t\tnObjects = objects.length;\n\n\t\tfor ( let i = 0, n = arguments.length; i !== n; ++ i ) {\n\n\t\t\tconst object = arguments[ i ],\n\t\t\t\tuuid = object.uuid,\n\t\t\t\tindex = indicesByUUID[ uuid ];\n\n\t\t\tif ( index !== undefined ) {\n\n\t\t\t\tdelete indicesByUUID[ uuid ];\n\n\t\t\t\tif ( index < nCachedObjects ) {\n\n\t\t\t\t\t// object is cached, shrink the CACHED region\n\n\t\t\t\t\tconst firstActiveIndex = -- nCachedObjects,\n\t\t\t\t\t\tlastCachedObject = objects[ firstActiveIndex ],\n\t\t\t\t\t\tlastIndex = -- nObjects,\n\t\t\t\t\t\tlastObject = objects[ lastIndex ];\n\n\t\t\t\t\t// last cached object takes this object's place\n\t\t\t\t\tindicesByUUID[ lastCachedObject.uuid ] = index;\n\t\t\t\t\tobjects[ index ] = lastCachedObject;\n\n\t\t\t\t\t// last object goes to the activated slot and pop\n\t\t\t\t\tindicesByUUID[ lastObject.uuid ] = firstActiveIndex;\n\t\t\t\t\tobjects[ firstActiveIndex ] = lastObject;\n\t\t\t\t\tobjects.pop();\n\n\t\t\t\t\t// accounting is done, now do the same for all bindings\n\n\t\t\t\t\tfor ( let j = 0, m = nBindings; j !== m; ++ j ) {\n\n\t\t\t\t\t\tconst bindingsForPath = bindings[ j ],\n\t\t\t\t\t\t\tlastCached = bindingsForPath[ firstActiveIndex ],\n\t\t\t\t\t\t\tlast = bindingsForPath[ lastIndex ];\n\n\t\t\t\t\t\tbindingsForPath[ index ] = lastCached;\n\t\t\t\t\t\tbindingsForPath[ firstActiveIndex ] = last;\n\t\t\t\t\t\tbindingsForPath.pop();\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// object is active, just swap with the last and pop\n\n\t\t\t\t\tconst lastIndex = -- nObjects,\n\t\t\t\t\t\tlastObject = objects[ lastIndex ];\n\n\t\t\t\t\tif ( lastIndex > 0 ) {\n\n\t\t\t\t\t\tindicesByUUID[ lastObject.uuid ] = index;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tobjects[ index ] = lastObject;\n\t\t\t\t\tobjects.pop();\n\n\t\t\t\t\t// accounting is done, now do the same for all bindings\n\n\t\t\t\t\tfor ( let j = 0, m = nBindings; j !== m; ++ j ) {\n\n\t\t\t\t\t\tconst bindingsForPath = bindings[ j ];\n\n\t\t\t\t\t\tbindingsForPath[ index ] = bindingsForPath[ lastIndex ];\n\t\t\t\t\t\tbindingsForPath.pop();\n\n\t\t\t\t\t}\n\n\t\t\t\t} // cached or active\n\n\t\t\t} // if object is known\n\n\t\t} // for arguments\n\n\t\tthis.nCachedObjects_ = nCachedObjects;\n\n\t}\n\n\t// Internal interface used by befriended PropertyBinding.Composite:\n\n\tsubscribe_( path, parsedPath ) {\n\n\t\t// returns an array of bindings for the given path that is changed\n\t\t// according to the contained objects in the group\n\n\t\tconst indicesByPath = this._bindingsIndicesByPath;\n\t\tlet index = indicesByPath[ path ];\n\t\tconst bindings = this._bindings;\n\n\t\tif ( index !== undefined ) return bindings[ index ];\n\n\t\tconst paths = this._paths,\n\t\t\tparsedPaths = this._parsedPaths,\n\t\t\tobjects = this._objects,\n\t\t\tnObjects = objects.length,\n\t\t\tnCachedObjects = this.nCachedObjects_,\n\t\t\tbindingsForPath = new Array( nObjects );\n\n\t\tindex = bindings.length;\n\n\t\tindicesByPath[ path ] = index;\n\n\t\tpaths.push( path );\n\t\tparsedPaths.push( parsedPath );\n\t\tbindings.push( bindingsForPath );\n\n\t\tfor ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {\n\n\t\t\tconst object = objects[ i ];\n\t\t\tbindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );\n\n\t\t}\n\n\t\treturn bindingsForPath;\n\n\t}\n\n\tunsubscribe_( path ) {\n\n\t\t// tells the group to forget about a property path and no longer\n\t\t// update the array previously obtained with 'subscribe_'\n\n\t\tconst indicesByPath = this._bindingsIndicesByPath,\n\t\t\tindex = indicesByPath[ path ];\n\n\t\tif ( index !== undefined ) {\n\n\t\t\tconst paths = this._paths,\n\t\t\t\tparsedPaths = this._parsedPaths,\n\t\t\t\tbindings = this._bindings,\n\t\t\t\tlastBindingsIndex = bindings.length - 1,\n\t\t\t\tlastBindings = bindings[ lastBindingsIndex ],\n\t\t\t\tlastBindingsPath = path[ lastBindingsIndex ];\n\n\t\t\tindicesByPath[ lastBindingsPath ] = index;\n\n\t\t\tbindings[ index ] = lastBindings;\n\t\t\tbindings.pop();\n\n\t\t\tparsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];\n\t\t\tparsedPaths.pop();\n\n\t\t\tpaths[ index ] = paths[ lastBindingsIndex ];\n\t\t\tpaths.pop();\n\n\t\t}\n\n\t}\n\n}\n\nclass AnimationAction {\n\n\tconstructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {\n\n\t\tthis._mixer = mixer;\n\t\tthis._clip = clip;\n\t\tthis._localRoot = localRoot;\n\t\tthis.blendMode = blendMode;\n\n\t\tconst tracks = clip.tracks,\n\t\t\tnTracks = tracks.length,\n\t\t\tinterpolants = new Array( nTracks );\n\n\t\tconst interpolantSettings = {\n\t\t\tendingStart: ZeroCurvatureEnding,\n\t\t\tendingEnd: ZeroCurvatureEnding\n\t\t};\n\n\t\tfor ( let i = 0; i !== nTracks; ++ i ) {\n\n\t\t\tconst interpolant = tracks[ i ].createInterpolant( null );\n\t\t\tinterpolants[ i ] = interpolant;\n\t\t\tinterpolant.settings = interpolantSettings;\n\n\t\t}\n\n\t\tthis._interpolantSettings = interpolantSettings;\n\n\t\tthis._interpolants = interpolants; // bound by the mixer\n\n\t\t// inside: PropertyMixer (managed by the mixer)\n\t\tthis._propertyBindings = new Array( nTracks );\n\n\t\tthis._cacheIndex = null; // for the memory manager\n\t\tthis._byClipCacheIndex = null; // for the memory manager\n\n\t\tthis._timeScaleInterpolant = null;\n\t\tthis._weightInterpolant = null;\n\n\t\tthis.loop = LoopRepeat;\n\t\tthis._loopCount = - 1;\n\n\t\t// global mixer time when the action is to be started\n\t\t// it's set back to 'null' upon start of the action\n\t\tthis._startTime = null;\n\n\t\t// scaled local time of the action\n\t\t// gets clamped or wrapped to 0..clip.duration according to loop\n\t\tthis.time = 0;\n\n\t\tthis.timeScale = 1;\n\t\tthis._effectiveTimeScale = 1;\n\n\t\tthis.weight = 1;\n\t\tthis._effectiveWeight = 1;\n\n\t\tthis.repetitions = Infinity; // no. of repetitions when looping\n\n\t\tthis.paused = false; // true -> zero effective time scale\n\t\tthis.enabled = true; // false -> zero effective weight\n\n\t\tthis.clampWhenFinished = false;// keep feeding the last frame?\n\n\t\tthis.zeroSlopeAtStart = true;// for smooth interpolation w/o separate\n\t\tthis.zeroSlopeAtEnd = true;// clips for start, loop and end\n\n\t}\n\n\t// State & Scheduling\n\n\tplay() {\n\n\t\tthis._mixer._activateAction( this );\n\n\t\treturn this;\n\n\t}\n\n\tstop() {\n\n\t\tthis._mixer._deactivateAction( this );\n\n\t\treturn this.reset();\n\n\t}\n\n\treset() {\n\n\t\tthis.paused = false;\n\t\tthis.enabled = true;\n\n\t\tthis.time = 0; // restart clip\n\t\tthis._loopCount = - 1;// forget previous loops\n\t\tthis._startTime = null;// forget scheduling\n\n\t\treturn this.stopFading().stopWarping();\n\n\t}\n\n\tisRunning() {\n\n\t\treturn this.enabled && ! this.paused && this.timeScale !== 0 &&\n\t\t\tthis._startTime === null && this._mixer._isActiveAction( this );\n\n\t}\n\n\t// return true when play has been called\n\tisScheduled() {\n\n\t\treturn this._mixer._isActiveAction( this );\n\n\t}\n\n\tstartAt( time ) {\n\n\t\tthis._startTime = time;\n\n\t\treturn this;\n\n\t}\n\n\tsetLoop( mode, repetitions ) {\n\n\t\tthis.loop = mode;\n\t\tthis.repetitions = repetitions;\n\n\t\treturn this;\n\n\t}\n\n\t// Weight\n\n\t// set the weight stopping any scheduled fading\n\t// although .enabled = false yields an effective weight of zero, this\n\t// method does *not* change .enabled, because it would be confusing\n\tsetEffectiveWeight( weight ) {\n\n\t\tthis.weight = weight;\n\n\t\t// note: same logic as when updated at runtime\n\t\tthis._effectiveWeight = this.enabled ? weight : 0;\n\n\t\treturn this.stopFading();\n\n\t}\n\n\t// return the weight considering fading and .enabled\n\tgetEffectiveWeight() {\n\n\t\treturn this._effectiveWeight;\n\n\t}\n\n\tfadeIn( duration ) {\n\n\t\treturn this._scheduleFading( duration, 0, 1 );\n\n\t}\n\n\tfadeOut( duration ) {\n\n\t\treturn this._scheduleFading( duration, 1, 0 );\n\n\t}\n\n\tcrossFadeFrom( fadeOutAction, duration, warp ) {\n\n\t\tfadeOutAction.fadeOut( duration );\n\t\tthis.fadeIn( duration );\n\n\t\tif ( warp ) {\n\n\t\t\tconst fadeInDuration = this._clip.duration,\n\t\t\t\tfadeOutDuration = fadeOutAction._clip.duration,\n\n\t\t\t\tstartEndRatio = fadeOutDuration / fadeInDuration,\n\t\t\t\tendStartRatio = fadeInDuration / fadeOutDuration;\n\n\t\t\tfadeOutAction.warp( 1.0, startEndRatio, duration );\n\t\t\tthis.warp( endStartRatio, 1.0, duration );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tcrossFadeTo( fadeInAction, duration, warp ) {\n\n\t\treturn fadeInAction.crossFadeFrom( this, duration, warp );\n\n\t}\n\n\tstopFading() {\n\n\t\tconst weightInterpolant = this._weightInterpolant;\n\n\t\tif ( weightInterpolant !== null ) {\n\n\t\t\tthis._weightInterpolant = null;\n\t\t\tthis._mixer._takeBackControlInterpolant( weightInterpolant );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t// Time Scale Control\n\n\t// set the time scale stopping any scheduled warping\n\t// although .paused = true yields an effective time scale of zero, this\n\t// method does *not* change .paused, because it would be confusing\n\tsetEffectiveTimeScale( timeScale ) {\n\n\t\tthis.timeScale = timeScale;\n\t\tthis._effectiveTimeScale = this.paused ? 0 : timeScale;\n\n\t\treturn this.stopWarping();\n\n\t}\n\n\t// return the time scale considering warping and .paused\n\tgetEffectiveTimeScale() {\n\n\t\treturn this._effectiveTimeScale;\n\n\t}\n\n\tsetDuration( duration ) {\n\n\t\tthis.timeScale = this._clip.duration / duration;\n\n\t\treturn this.stopWarping();\n\n\t}\n\n\tsyncWith( action ) {\n\n\t\tthis.time = action.time;\n\t\tthis.timeScale = action.timeScale;\n\n\t\treturn this.stopWarping();\n\n\t}\n\n\thalt( duration ) {\n\n\t\treturn this.warp( this._effectiveTimeScale, 0, duration );\n\n\t}\n\n\twarp( startTimeScale, endTimeScale, duration ) {\n\n\t\tconst mixer = this._mixer,\n\t\t\tnow = mixer.time,\n\t\t\ttimeScale = this.timeScale;\n\n\t\tlet interpolant = this._timeScaleInterpolant;\n\n\t\tif ( interpolant === null ) {\n\n\t\t\tinterpolant = mixer._lendControlInterpolant();\n\t\t\tthis._timeScaleInterpolant = interpolant;\n\n\t\t}\n\n\t\tconst times = interpolant.parameterPositions,\n\t\t\tvalues = interpolant.sampleValues;\n\n\t\ttimes[ 0 ] = now;\n\t\ttimes[ 1 ] = now + duration;\n\n\t\tvalues[ 0 ] = startTimeScale / timeScale;\n\t\tvalues[ 1 ] = endTimeScale / timeScale;\n\n\t\treturn this;\n\n\t}\n\n\tstopWarping() {\n\n\t\tconst timeScaleInterpolant = this._timeScaleInterpolant;\n\n\t\tif ( timeScaleInterpolant !== null ) {\n\n\t\t\tthis._timeScaleInterpolant = null;\n\t\t\tthis._mixer._takeBackControlInterpolant( timeScaleInterpolant );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t// Object Accessors\n\n\tgetMixer() {\n\n\t\treturn this._mixer;\n\n\t}\n\n\tgetClip() {\n\n\t\treturn this._clip;\n\n\t}\n\n\tgetRoot() {\n\n\t\treturn this._localRoot || this._mixer._root;\n\n\t}\n\n\t// Interna\n\n\t_update( time, deltaTime, timeDirection, accuIndex ) {\n\n\t\t// called by the mixer\n\n\t\tif ( ! this.enabled ) {\n\n\t\t\t// call ._updateWeight() to update ._effectiveWeight\n\n\t\t\tthis._updateWeight( time );\n\t\t\treturn;\n\n\t\t}\n\n\t\tconst startTime = this._startTime;\n\n\t\tif ( startTime !== null ) {\n\n\t\t\t// check for scheduled start of action\n\n\t\t\tconst timeRunning = ( time - startTime ) * timeDirection;\n\t\t\tif ( timeRunning < 0 || timeDirection === 0 ) {\n\n\t\t\t\tdeltaTime = 0;\n\n\t\t\t} else {\n\n\n\t\t\t\tthis._startTime = null; // unschedule\n\t\t\t\tdeltaTime = timeDirection * timeRunning;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// apply time scale and advance time\n\n\t\tdeltaTime *= this._updateTimeScale( time );\n\t\tconst clipTime = this._updateTime( deltaTime );\n\n\t\t// note: _updateTime may disable the action resulting in\n\t\t// an effective weight of 0\n\n\t\tconst weight = this._updateWeight( time );\n\n\t\tif ( weight > 0 ) {\n\n\t\t\tconst interpolants = this._interpolants;\n\t\t\tconst propertyMixers = this._propertyBindings;\n\n\t\t\tswitch ( this.blendMode ) {\n\n\t\t\t\tcase AdditiveAnimationBlendMode:\n\n\t\t\t\t\tfor ( let j = 0, m = interpolants.length; j !== m; ++ j ) {\n\n\t\t\t\t\t\tinterpolants[ j ].evaluate( clipTime );\n\t\t\t\t\t\tpropertyMixers[ j ].accumulateAdditive( weight );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase NormalAnimationBlendMode:\n\t\t\t\tdefault:\n\n\t\t\t\t\tfor ( let j = 0, m = interpolants.length; j !== m; ++ j ) {\n\n\t\t\t\t\t\tinterpolants[ j ].evaluate( clipTime );\n\t\t\t\t\t\tpropertyMixers[ j ].accumulate( accuIndex, weight );\n\n\t\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t_updateWeight( time ) {\n\n\t\tlet weight = 0;\n\n\t\tif ( this.enabled ) {\n\n\t\t\tweight = this.weight;\n\t\t\tconst interpolant = this._weightInterpolant;\n\n\t\t\tif ( interpolant !== null ) {\n\n\t\t\t\tconst interpolantValue = interpolant.evaluate( time )[ 0 ];\n\n\t\t\t\tweight *= interpolantValue;\n\n\t\t\t\tif ( time > interpolant.parameterPositions[ 1 ] ) {\n\n\t\t\t\t\tthis.stopFading();\n\n\t\t\t\t\tif ( interpolantValue === 0 ) {\n\n\t\t\t\t\t\t// faded out, disable\n\t\t\t\t\t\tthis.enabled = false;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tthis._effectiveWeight = weight;\n\t\treturn weight;\n\n\t}\n\n\t_updateTimeScale( time ) {\n\n\t\tlet timeScale = 0;\n\n\t\tif ( ! this.paused ) {\n\n\t\t\ttimeScale = this.timeScale;\n\n\t\t\tconst interpolant = this._timeScaleInterpolant;\n\n\t\t\tif ( interpolant !== null ) {\n\n\t\t\t\tconst interpolantValue = interpolant.evaluate( time )[ 0 ];\n\n\t\t\t\ttimeScale *= interpolantValue;\n\n\t\t\t\tif ( time > interpolant.parameterPositions[ 1 ] ) {\n\n\t\t\t\t\tthis.stopWarping();\n\n\t\t\t\t\tif ( timeScale === 0 ) {\n\n\t\t\t\t\t\t// motion has halted, pause\n\t\t\t\t\t\tthis.paused = true;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t// warp done - apply final time scale\n\t\t\t\t\t\tthis.timeScale = timeScale;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tthis._effectiveTimeScale = timeScale;\n\t\treturn timeScale;\n\n\t}\n\n\t_updateTime( deltaTime ) {\n\n\t\tconst duration = this._clip.duration;\n\t\tconst loop = this.loop;\n\n\t\tlet time = this.time + deltaTime;\n\t\tlet loopCount = this._loopCount;\n\n\t\tconst pingPong = ( loop === LoopPingPong );\n\n\t\tif ( deltaTime === 0 ) {\n\n\t\t\tif ( loopCount === - 1 ) return time;\n\n\t\t\treturn ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;\n\n\t\t}\n\n\t\tif ( loop === LoopOnce ) {\n\n\t\t\tif ( loopCount === - 1 ) {\n\n\t\t\t\t// just started\n\n\t\t\t\tthis._loopCount = 0;\n\t\t\t\tthis._setEndings( true, true, false );\n\n\t\t\t}\n\n\t\t\thandle_stop: {\n\n\t\t\t\tif ( time >= duration ) {\n\n\t\t\t\t\ttime = duration;\n\n\t\t\t\t} else if ( time < 0 ) {\n\n\t\t\t\t\ttime = 0;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tthis.time = time;\n\n\t\t\t\t\tbreak handle_stop;\n\n\t\t\t\t}\n\n\t\t\t\tif ( this.clampWhenFinished ) this.paused = true;\n\t\t\t\telse this.enabled = false;\n\n\t\t\t\tthis.time = time;\n\n\t\t\t\tthis._mixer.dispatchEvent( {\n\t\t\t\t\ttype: 'finished', action: this,\n\t\t\t\t\tdirection: deltaTime < 0 ? - 1 : 1\n\t\t\t\t} );\n\n\t\t\t}\n\n\t\t} else { // repetitive Repeat or PingPong\n\n\t\t\tif ( loopCount === - 1 ) {\n\n\t\t\t\t// just started\n\n\t\t\t\tif ( deltaTime >= 0 ) {\n\n\t\t\t\t\tloopCount = 0;\n\n\t\t\t\t\tthis._setEndings( true, this.repetitions === 0, pingPong );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// when looping in reverse direction, the initial\n\t\t\t\t\t// transition through zero counts as a repetition,\n\t\t\t\t\t// so leave loopCount at -1\n\n\t\t\t\t\tthis._setEndings( this.repetitions === 0, true, pingPong );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( time >= duration || time < 0 ) {\n\n\t\t\t\t// wrap around\n\n\t\t\t\tconst loopDelta = Math.floor( time / duration ); // signed\n\t\t\t\ttime -= duration * loopDelta;\n\n\t\t\t\tloopCount += Math.abs( loopDelta );\n\n\t\t\t\tconst pending = this.repetitions - loopCount;\n\n\t\t\t\tif ( pending <= 0 ) {\n\n\t\t\t\t\t// have to stop (switch state, clamp time, fire event)\n\n\t\t\t\t\tif ( this.clampWhenFinished ) this.paused = true;\n\t\t\t\t\telse this.enabled = false;\n\n\t\t\t\t\ttime = deltaTime > 0 ? duration : 0;\n\n\t\t\t\t\tthis.time = time;\n\n\t\t\t\t\tthis._mixer.dispatchEvent( {\n\t\t\t\t\t\ttype: 'finished', action: this,\n\t\t\t\t\t\tdirection: deltaTime > 0 ? 1 : - 1\n\t\t\t\t\t} );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// keep running\n\n\t\t\t\t\tif ( pending === 1 ) {\n\n\t\t\t\t\t\t// entering the last round\n\n\t\t\t\t\t\tconst atStart = deltaTime < 0;\n\t\t\t\t\t\tthis._setEndings( atStart, ! atStart, pingPong );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tthis._setEndings( false, false, pingPong );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tthis._loopCount = loopCount;\n\n\t\t\t\t\tthis.time = time;\n\n\t\t\t\t\tthis._mixer.dispatchEvent( {\n\t\t\t\t\t\ttype: 'loop', action: this, loopDelta: loopDelta\n\t\t\t\t\t} );\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tthis.time = time;\n\n\t\t\t}\n\n\t\t\tif ( pingPong && ( loopCount & 1 ) === 1 ) {\n\n\t\t\t\t// invert time for the \"pong round\"\n\n\t\t\t\treturn duration - time;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn time;\n\n\t}\n\n\t_setEndings( atStart, atEnd, pingPong ) {\n\n\t\tconst settings = this._interpolantSettings;\n\n\t\tif ( pingPong ) {\n\n\t\t\tsettings.endingStart = ZeroSlopeEnding;\n\t\t\tsettings.endingEnd = ZeroSlopeEnding;\n\n\t\t} else {\n\n\t\t\t// assuming for LoopOnce atStart == atEnd == true\n\n\t\t\tif ( atStart ) {\n\n\t\t\t\tsettings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;\n\n\t\t\t} else {\n\n\t\t\t\tsettings.endingStart = WrapAroundEnding;\n\n\t\t\t}\n\n\t\t\tif ( atEnd ) {\n\n\t\t\t\tsettings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;\n\n\t\t\t} else {\n\n\t\t\t\tsettings.endingEnd \t = WrapAroundEnding;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t_scheduleFading( duration, weightNow, weightThen ) {\n\n\t\tconst mixer = this._mixer, now = mixer.time;\n\t\tlet interpolant = this._weightInterpolant;\n\n\t\tif ( interpolant === null ) {\n\n\t\t\tinterpolant = mixer._lendControlInterpolant();\n\t\t\tthis._weightInterpolant = interpolant;\n\n\t\t}\n\n\t\tconst times = interpolant.parameterPositions,\n\t\t\tvalues = interpolant.sampleValues;\n\n\t\ttimes[ 0 ] = now;\n\t\tvalues[ 0 ] = weightNow;\n\t\ttimes[ 1 ] = now + duration;\n\t\tvalues[ 1 ] = weightThen;\n\n\t\treturn this;\n\n\t}\n\n}\n\nconst _controlInterpolantsResultBuffer = new Float32Array( 1 );\n\n\nclass AnimationMixer extends EventDispatcher {\n\n\tconstructor( root ) {\n\n\t\tsuper();\n\n\t\tthis._root = root;\n\t\tthis._initMemoryManager();\n\t\tthis._accuIndex = 0;\n\t\tthis.time = 0;\n\t\tthis.timeScale = 1.0;\n\n\t}\n\n\t_bindAction( action, prototypeAction ) {\n\n\t\tconst root = action._localRoot || this._root,\n\t\t\ttracks = action._clip.tracks,\n\t\t\tnTracks = tracks.length,\n\t\t\tbindings = action._propertyBindings,\n\t\t\tinterpolants = action._interpolants,\n\t\t\trootUuid = root.uuid,\n\t\t\tbindingsByRoot = this._bindingsByRootAndName;\n\n\t\tlet bindingsByName = bindingsByRoot[ rootUuid ];\n\n\t\tif ( bindingsByName === undefined ) {\n\n\t\t\tbindingsByName = {};\n\t\t\tbindingsByRoot[ rootUuid ] = bindingsByName;\n\n\t\t}\n\n\t\tfor ( let i = 0; i !== nTracks; ++ i ) {\n\n\t\t\tconst track = tracks[ i ],\n\t\t\t\ttrackName = track.name;\n\n\t\t\tlet binding = bindingsByName[ trackName ];\n\n\t\t\tif ( binding !== undefined ) {\n\n\t\t\t\t++ binding.referenceCount;\n\t\t\t\tbindings[ i ] = binding;\n\n\t\t\t} else {\n\n\t\t\t\tbinding = bindings[ i ];\n\n\t\t\t\tif ( binding !== undefined ) {\n\n\t\t\t\t\t// existing binding, make sure the cache knows\n\n\t\t\t\t\tif ( binding._cacheIndex === null ) {\n\n\t\t\t\t\t\t++ binding.referenceCount;\n\t\t\t\t\t\tthis._addInactiveBinding( binding, rootUuid, trackName );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\t}\n\n\t\t\t\tconst path = prototypeAction && prototypeAction.\n\t\t\t\t\t_propertyBindings[ i ].binding.parsedPath;\n\n\t\t\t\tbinding = new PropertyMixer(\n\t\t\t\t\tPropertyBinding.create( root, trackName, path ),\n\t\t\t\t\ttrack.ValueTypeName, track.getValueSize() );\n\n\t\t\t\t++ binding.referenceCount;\n\t\t\t\tthis._addInactiveBinding( binding, rootUuid, trackName );\n\n\t\t\t\tbindings[ i ] = binding;\n\n\t\t\t}\n\n\t\t\tinterpolants[ i ].resultBuffer = binding.buffer;\n\n\t\t}\n\n\t}\n\n\t_activateAction( action ) {\n\n\t\tif ( ! this._isActiveAction( action ) ) {\n\n\t\t\tif ( action._cacheIndex === null ) {\n\n\t\t\t\t// this action has been forgotten by the cache, but the user\n\t\t\t\t// appears to be still using it -> rebind\n\n\t\t\t\tconst rootUuid = ( action._localRoot || this._root ).uuid,\n\t\t\t\t\tclipUuid = action._clip.uuid,\n\t\t\t\t\tactionsForClip = this._actionsByClip[ clipUuid ];\n\n\t\t\t\tthis._bindAction( action,\n\t\t\t\t\tactionsForClip && actionsForClip.knownActions[ 0 ] );\n\n\t\t\t\tthis._addInactiveAction( action, clipUuid, rootUuid );\n\n\t\t\t}\n\n\t\t\tconst bindings = action._propertyBindings;\n\n\t\t\t// increment reference counts / sort out state\n\t\t\tfor ( let i = 0, n = bindings.length; i !== n; ++ i ) {\n\n\t\t\t\tconst binding = bindings[ i ];\n\n\t\t\t\tif ( binding.useCount ++ === 0 ) {\n\n\t\t\t\t\tthis._lendBinding( binding );\n\t\t\t\t\tbinding.saveOriginalState();\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tthis._lendAction( action );\n\n\t\t}\n\n\t}\n\n\t_deactivateAction( action ) {\n\n\t\tif ( this._isActiveAction( action ) ) {\n\n\t\t\tconst bindings = action._propertyBindings;\n\n\t\t\t// decrement reference counts / sort out state\n\t\t\tfor ( let i = 0, n = bindings.length; i !== n; ++ i ) {\n\n\t\t\t\tconst binding = bindings[ i ];\n\n\t\t\t\tif ( -- binding.useCount === 0 ) {\n\n\t\t\t\t\tbinding.restoreOriginalState();\n\t\t\t\t\tthis._takeBackBinding( binding );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tthis._takeBackAction( action );\n\n\t\t}\n\n\t}\n\n\t// Memory manager\n\n\t_initMemoryManager() {\n\n\t\tthis._actions = []; // 'nActiveActions' followed by inactive ones\n\t\tthis._nActiveActions = 0;\n\n\t\tthis._actionsByClip = {};\n\t\t// inside:\n\t\t// {\n\t\t// \tknownActions: Array< AnimationAction > - used as prototypes\n\t\t// \tactionByRoot: AnimationAction - lookup\n\t\t// }\n\n\n\t\tthis._bindings = []; // 'nActiveBindings' followed by inactive ones\n\t\tthis._nActiveBindings = 0;\n\n\t\tthis._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >\n\n\n\t\tthis._controlInterpolants = []; // same game as above\n\t\tthis._nActiveControlInterpolants = 0;\n\n\t\tconst scope = this;\n\n\t\tthis.stats = {\n\n\t\t\tactions: {\n\t\t\t\tget total() {\n\n\t\t\t\t\treturn scope._actions.length;\n\n\t\t\t\t},\n\t\t\t\tget inUse() {\n\n\t\t\t\t\treturn scope._nActiveActions;\n\n\t\t\t\t}\n\t\t\t},\n\t\t\tbindings: {\n\t\t\t\tget total() {\n\n\t\t\t\t\treturn scope._bindings.length;\n\n\t\t\t\t},\n\t\t\t\tget inUse() {\n\n\t\t\t\t\treturn scope._nActiveBindings;\n\n\t\t\t\t}\n\t\t\t},\n\t\t\tcontrolInterpolants: {\n\t\t\t\tget total() {\n\n\t\t\t\t\treturn scope._controlInterpolants.length;\n\n\t\t\t\t},\n\t\t\t\tget inUse() {\n\n\t\t\t\t\treturn scope._nActiveControlInterpolants;\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t};\n\n\t}\n\n\t// Memory management for AnimationAction objects\n\n\t_isActiveAction( action ) {\n\n\t\tconst index = action._cacheIndex;\n\t\treturn index !== null && index < this._nActiveActions;\n\n\t}\n\n\t_addInactiveAction( action, clipUuid, rootUuid ) {\n\n\t\tconst actions = this._actions,\n\t\t\tactionsByClip = this._actionsByClip;\n\n\t\tlet actionsForClip = actionsByClip[ clipUuid ];\n\n\t\tif ( actionsForClip === undefined ) {\n\n\t\t\tactionsForClip = {\n\n\t\t\t\tknownActions: [ action ],\n\t\t\t\tactionByRoot: {}\n\n\t\t\t};\n\n\t\t\taction._byClipCacheIndex = 0;\n\n\t\t\tactionsByClip[ clipUuid ] = actionsForClip;\n\n\t\t} else {\n\n\t\t\tconst knownActions = actionsForClip.knownActions;\n\n\t\t\taction._byClipCacheIndex = knownActions.length;\n\t\t\tknownActions.push( action );\n\n\t\t}\n\n\t\taction._cacheIndex = actions.length;\n\t\tactions.push( action );\n\n\t\tactionsForClip.actionByRoot[ rootUuid ] = action;\n\n\t}\n\n\t_removeInactiveAction( action ) {\n\n\t\tconst actions = this._actions,\n\t\t\tlastInactiveAction = actions[ actions.length - 1 ],\n\t\t\tcacheIndex = action._cacheIndex;\n\n\t\tlastInactiveAction._cacheIndex = cacheIndex;\n\t\tactions[ cacheIndex ] = lastInactiveAction;\n\t\tactions.pop();\n\n\t\taction._cacheIndex = null;\n\n\n\t\tconst clipUuid = action._clip.uuid,\n\t\t\tactionsByClip = this._actionsByClip,\n\t\t\tactionsForClip = actionsByClip[ clipUuid ],\n\t\t\tknownActionsForClip = actionsForClip.knownActions,\n\n\t\t\tlastKnownAction =\n\t\t\t\tknownActionsForClip[ knownActionsForClip.length - 1 ],\n\n\t\t\tbyClipCacheIndex = action._byClipCacheIndex;\n\n\t\tlastKnownAction._byClipCacheIndex = byClipCacheIndex;\n\t\tknownActionsForClip[ byClipCacheIndex ] = lastKnownAction;\n\t\tknownActionsForClip.pop();\n\n\t\taction._byClipCacheIndex = null;\n\n\n\t\tconst actionByRoot = actionsForClip.actionByRoot,\n\t\t\trootUuid = ( action._localRoot || this._root ).uuid;\n\n\t\tdelete actionByRoot[ rootUuid ];\n\n\t\tif ( knownActionsForClip.length === 0 ) {\n\n\t\t\tdelete actionsByClip[ clipUuid ];\n\n\t\t}\n\n\t\tthis._removeInactiveBindingsForAction( action );\n\n\t}\n\n\t_removeInactiveBindingsForAction( action ) {\n\n\t\tconst bindings = action._propertyBindings;\n\n\t\tfor ( let i = 0, n = bindings.length; i !== n; ++ i ) {\n\n\t\t\tconst binding = bindings[ i ];\n\n\t\t\tif ( -- binding.referenceCount === 0 ) {\n\n\t\t\t\tthis._removeInactiveBinding( binding );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t_lendAction( action ) {\n\n\t\t// [ active actions | inactive actions ]\n\t\t// [ active actions >| inactive actions ]\n\t\t// s a\n\t\t// <-swap->\n\t\t// a s\n\n\t\tconst actions = this._actions,\n\t\t\tprevIndex = action._cacheIndex,\n\n\t\t\tlastActiveIndex = this._nActiveActions ++,\n\n\t\t\tfirstInactiveAction = actions[ lastActiveIndex ];\n\n\t\taction._cacheIndex = lastActiveIndex;\n\t\tactions[ lastActiveIndex ] = action;\n\n\t\tfirstInactiveAction._cacheIndex = prevIndex;\n\t\tactions[ prevIndex ] = firstInactiveAction;\n\n\t}\n\n\t_takeBackAction( action ) {\n\n\t\t// [ active actions | inactive actions ]\n\t\t// [ active actions |< inactive actions ]\n\t\t// a s\n\t\t// <-swap->\n\t\t// s a\n\n\t\tconst actions = this._actions,\n\t\t\tprevIndex = action._cacheIndex,\n\n\t\t\tfirstInactiveIndex = -- this._nActiveActions,\n\n\t\t\tlastActiveAction = actions[ firstInactiveIndex ];\n\n\t\taction._cacheIndex = firstInactiveIndex;\n\t\tactions[ firstInactiveIndex ] = action;\n\n\t\tlastActiveAction._cacheIndex = prevIndex;\n\t\tactions[ prevIndex ] = lastActiveAction;\n\n\t}\n\n\t// Memory management for PropertyMixer objects\n\n\t_addInactiveBinding( binding, rootUuid, trackName ) {\n\n\t\tconst bindingsByRoot = this._bindingsByRootAndName,\n\t\t\tbindings = this._bindings;\n\n\t\tlet bindingByName = bindingsByRoot[ rootUuid ];\n\n\t\tif ( bindingByName === undefined ) {\n\n\t\t\tbindingByName = {};\n\t\t\tbindingsByRoot[ rootUuid ] = bindingByName;\n\n\t\t}\n\n\t\tbindingByName[ trackName ] = binding;\n\n\t\tbinding._cacheIndex = bindings.length;\n\t\tbindings.push( binding );\n\n\t}\n\n\t_removeInactiveBinding( binding ) {\n\n\t\tconst bindings = this._bindings,\n\t\t\tpropBinding = binding.binding,\n\t\t\trootUuid = propBinding.rootNode.uuid,\n\t\t\ttrackName = propBinding.path,\n\t\t\tbindingsByRoot = this._bindingsByRootAndName,\n\t\t\tbindingByName = bindingsByRoot[ rootUuid ],\n\n\t\t\tlastInactiveBinding = bindings[ bindings.length - 1 ],\n\t\t\tcacheIndex = binding._cacheIndex;\n\n\t\tlastInactiveBinding._cacheIndex = cacheIndex;\n\t\tbindings[ cacheIndex ] = lastInactiveBinding;\n\t\tbindings.pop();\n\n\t\tdelete bindingByName[ trackName ];\n\n\t\tif ( Object.keys( bindingByName ).length === 0 ) {\n\n\t\t\tdelete bindingsByRoot[ rootUuid ];\n\n\t\t}\n\n\t}\n\n\t_lendBinding( binding ) {\n\n\t\tconst bindings = this._bindings,\n\t\t\tprevIndex = binding._cacheIndex,\n\n\t\t\tlastActiveIndex = this._nActiveBindings ++,\n\n\t\t\tfirstInactiveBinding = bindings[ lastActiveIndex ];\n\n\t\tbinding._cacheIndex = lastActiveIndex;\n\t\tbindings[ lastActiveIndex ] = binding;\n\n\t\tfirstInactiveBinding._cacheIndex = prevIndex;\n\t\tbindings[ prevIndex ] = firstInactiveBinding;\n\n\t}\n\n\t_takeBackBinding( binding ) {\n\n\t\tconst bindings = this._bindings,\n\t\t\tprevIndex = binding._cacheIndex,\n\n\t\t\tfirstInactiveIndex = -- this._nActiveBindings,\n\n\t\t\tlastActiveBinding = bindings[ firstInactiveIndex ];\n\n\t\tbinding._cacheIndex = firstInactiveIndex;\n\t\tbindings[ firstInactiveIndex ] = binding;\n\n\t\tlastActiveBinding._cacheIndex = prevIndex;\n\t\tbindings[ prevIndex ] = lastActiveBinding;\n\n\t}\n\n\n\t// Memory management of Interpolants for weight and time scale\n\n\t_lendControlInterpolant() {\n\n\t\tconst interpolants = this._controlInterpolants,\n\t\t\tlastActiveIndex = this._nActiveControlInterpolants ++;\n\n\t\tlet interpolant = interpolants[ lastActiveIndex ];\n\n\t\tif ( interpolant === undefined ) {\n\n\t\t\tinterpolant = new LinearInterpolant(\n\t\t\t\tnew Float32Array( 2 ), new Float32Array( 2 ),\n\t\t\t\t1, _controlInterpolantsResultBuffer );\n\n\t\t\tinterpolant.__cacheIndex = lastActiveIndex;\n\t\t\tinterpolants[ lastActiveIndex ] = interpolant;\n\n\t\t}\n\n\t\treturn interpolant;\n\n\t}\n\n\t_takeBackControlInterpolant( interpolant ) {\n\n\t\tconst interpolants = this._controlInterpolants,\n\t\t\tprevIndex = interpolant.__cacheIndex,\n\n\t\t\tfirstInactiveIndex = -- this._nActiveControlInterpolants,\n\n\t\t\tlastActiveInterpolant = interpolants[ firstInactiveIndex ];\n\n\t\tinterpolant.__cacheIndex = firstInactiveIndex;\n\t\tinterpolants[ firstInactiveIndex ] = interpolant;\n\n\t\tlastActiveInterpolant.__cacheIndex = prevIndex;\n\t\tinterpolants[ prevIndex ] = lastActiveInterpolant;\n\n\t}\n\n\t// return an action for a clip optionally using a custom root target\n\t// object (this method allocates a lot of dynamic memory in case a\n\t// previously unknown clip/root combination is specified)\n\tclipAction( clip, optionalRoot, blendMode ) {\n\n\t\tconst root = optionalRoot || this._root,\n\t\t\trootUuid = root.uuid;\n\n\t\tlet clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;\n\n\t\tconst clipUuid = clipObject !== null ? clipObject.uuid : clip;\n\n\t\tconst actionsForClip = this._actionsByClip[ clipUuid ];\n\t\tlet prototypeAction = null;\n\n\t\tif ( blendMode === undefined ) {\n\n\t\t\tif ( clipObject !== null ) {\n\n\t\t\t\tblendMode = clipObject.blendMode;\n\n\t\t\t} else {\n\n\t\t\t\tblendMode = NormalAnimationBlendMode;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( actionsForClip !== undefined ) {\n\n\t\t\tconst existingAction = actionsForClip.actionByRoot[ rootUuid ];\n\n\t\t\tif ( existingAction !== undefined && existingAction.blendMode === blendMode ) {\n\n\t\t\t\treturn existingAction;\n\n\t\t\t}\n\n\t\t\t// we know the clip, so we don't have to parse all\n\t\t\t// the bindings again but can just copy\n\t\t\tprototypeAction = actionsForClip.knownActions[ 0 ];\n\n\t\t\t// also, take the clip from the prototype action\n\t\t\tif ( clipObject === null )\n\t\t\t\tclipObject = prototypeAction._clip;\n\n\t\t}\n\n\t\t// clip must be known when specified via string\n\t\tif ( clipObject === null ) return null;\n\n\t\t// allocate all resources required to run it\n\t\tconst newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );\n\n\t\tthis._bindAction( newAction, prototypeAction );\n\n\t\t// and make the action known to the memory manager\n\t\tthis._addInactiveAction( newAction, clipUuid, rootUuid );\n\n\t\treturn newAction;\n\n\t}\n\n\t// get an existing action\n\texistingAction( clip, optionalRoot ) {\n\n\t\tconst root = optionalRoot || this._root,\n\t\t\trootUuid = root.uuid,\n\n\t\t\tclipObject = typeof clip === 'string' ?\n\t\t\t\tAnimationClip.findByName( root, clip ) : clip,\n\n\t\t\tclipUuid = clipObject ? clipObject.uuid : clip,\n\n\t\t\tactionsForClip = this._actionsByClip[ clipUuid ];\n\n\t\tif ( actionsForClip !== undefined ) {\n\n\t\t\treturn actionsForClip.actionByRoot[ rootUuid ] || null;\n\n\t\t}\n\n\t\treturn null;\n\n\t}\n\n\t// deactivates all previously scheduled actions\n\tstopAllAction() {\n\n\t\tconst actions = this._actions,\n\t\t\tnActions = this._nActiveActions;\n\n\t\tfor ( let i = nActions - 1; i >= 0; -- i ) {\n\n\t\t\tactions[ i ].stop();\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t// advance the time and update apply the animation\n\tupdate( deltaTime ) {\n\n\t\tdeltaTime *= this.timeScale;\n\n\t\tconst actions = this._actions,\n\t\t\tnActions = this._nActiveActions,\n\n\t\t\ttime = this.time += deltaTime,\n\t\t\ttimeDirection = Math.sign( deltaTime ),\n\n\t\t\taccuIndex = this._accuIndex ^= 1;\n\n\t\t// run active actions\n\n\t\tfor ( let i = 0; i !== nActions; ++ i ) {\n\n\t\t\tconst action = actions[ i ];\n\n\t\t\taction._update( time, deltaTime, timeDirection, accuIndex );\n\n\t\t}\n\n\t\t// update scene graph\n\n\t\tconst bindings = this._bindings,\n\t\t\tnBindings = this._nActiveBindings;\n\n\t\tfor ( let i = 0; i !== nBindings; ++ i ) {\n\n\t\t\tbindings[ i ].apply( accuIndex );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\t// Allows you to seek to a specific time in an animation.\n\tsetTime( timeInSeconds ) {\n\n\t\tthis.time = 0; // Zero out time attribute for AnimationMixer object;\n\t\tfor ( let i = 0; i < this._actions.length; i ++ ) {\n\n\t\t\tthis._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.\n\n\t\t}\n\n\t\treturn this.update( timeInSeconds ); // Update used to set exact time. Returns \"this\" AnimationMixer object.\n\n\t}\n\n\t// return this mixer's root target object\n\tgetRoot() {\n\n\t\treturn this._root;\n\n\t}\n\n\t// free all resources specific to a particular clip\n\tuncacheClip( clip ) {\n\n\t\tconst actions = this._actions,\n\t\t\tclipUuid = clip.uuid,\n\t\t\tactionsByClip = this._actionsByClip,\n\t\t\tactionsForClip = actionsByClip[ clipUuid ];\n\n\t\tif ( actionsForClip !== undefined ) {\n\n\t\t\t// note: just calling _removeInactiveAction would mess up the\n\t\t\t// iteration state and also require updating the state we can\n\t\t\t// just throw away\n\n\t\t\tconst actionsToRemove = actionsForClip.knownActions;\n\n\t\t\tfor ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {\n\n\t\t\t\tconst action = actionsToRemove[ i ];\n\n\t\t\t\tthis._deactivateAction( action );\n\n\t\t\t\tconst cacheIndex = action._cacheIndex,\n\t\t\t\t\tlastInactiveAction = actions[ actions.length - 1 ];\n\n\t\t\t\taction._cacheIndex = null;\n\t\t\t\taction._byClipCacheIndex = null;\n\n\t\t\t\tlastInactiveAction._cacheIndex = cacheIndex;\n\t\t\t\tactions[ cacheIndex ] = lastInactiveAction;\n\t\t\t\tactions.pop();\n\n\t\t\t\tthis._removeInactiveBindingsForAction( action );\n\n\t\t\t}\n\n\t\t\tdelete actionsByClip[ clipUuid ];\n\n\t\t}\n\n\t}\n\n\t// free all resources specific to a particular root target object\n\tuncacheRoot( root ) {\n\n\t\tconst rootUuid = root.uuid,\n\t\t\tactionsByClip = this._actionsByClip;\n\n\t\tfor ( const clipUuid in actionsByClip ) {\n\n\t\t\tconst actionByRoot = actionsByClip[ clipUuid ].actionByRoot,\n\t\t\t\taction = actionByRoot[ rootUuid ];\n\n\t\t\tif ( action !== undefined ) {\n\n\t\t\t\tthis._deactivateAction( action );\n\t\t\t\tthis._removeInactiveAction( action );\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst bindingsByRoot = this._bindingsByRootAndName,\n\t\t\tbindingByName = bindingsByRoot[ rootUuid ];\n\n\t\tif ( bindingByName !== undefined ) {\n\n\t\t\tfor ( const trackName in bindingByName ) {\n\n\t\t\t\tconst binding = bindingByName[ trackName ];\n\t\t\t\tbinding.restoreOriginalState();\n\t\t\t\tthis._removeInactiveBinding( binding );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t// remove a targeted clip from the cache\n\tuncacheAction( clip, optionalRoot ) {\n\n\t\tconst action = this.existingAction( clip, optionalRoot );\n\n\t\tif ( action !== null ) {\n\n\t\t\tthis._deactivateAction( action );\n\t\t\tthis._removeInactiveAction( action );\n\n\t\t}\n\n\t}\n\n}\n\nclass Uniform {\n\n\tconstructor( value ) {\n\n\t\tthis.value = value;\n\n\t}\n\n\tclone() {\n\n\t\treturn new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );\n\n\t}\n\n}\n\nlet id = 0;\n\nclass UniformsGroup extends EventDispatcher {\n\n\tconstructor() {\n\n\t\tsuper();\n\n\t\tthis.isUniformsGroup = true;\n\n\t\tObject.defineProperty( this, 'id', { value: id ++ } );\n\n\t\tthis.name = '';\n\n\t\tthis.usage = StaticDrawUsage;\n\t\tthis.uniforms = [];\n\n\t}\n\n\tadd( uniform ) {\n\n\t\tthis.uniforms.push( uniform );\n\n\t\treturn this;\n\n\t}\n\n\tremove( uniform ) {\n\n\t\tconst index = this.uniforms.indexOf( uniform );\n\n\t\tif ( index !== - 1 ) this.uniforms.splice( index, 1 );\n\n\t\treturn this;\n\n\t}\n\n\tsetName( name ) {\n\n\t\tthis.name = name;\n\n\t\treturn this;\n\n\t}\n\n\tsetUsage( value ) {\n\n\t\tthis.usage = value;\n\n\t\treturn this;\n\n\t}\n\n\tdispose() {\n\n\t\tthis.dispatchEvent( { type: 'dispose' } );\n\n\t\treturn this;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tthis.name = source.name;\n\t\tthis.usage = source.usage;\n\n\t\tconst uniformsSource = source.uniforms;\n\n\t\tthis.uniforms.length = 0;\n\n\t\tfor ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {\n\n\t\t\tthis.uniforms.push( uniformsSource[ i ].clone() );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n}\n\nclass InstancedInterleavedBuffer extends InterleavedBuffer {\n\n\tconstructor( array, stride, meshPerAttribute = 1 ) {\n\n\t\tsuper( array, stride );\n\n\t\tthis.isInstancedInterleavedBuffer = true;\n\n\t\tthis.meshPerAttribute = meshPerAttribute;\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source );\n\n\t\tthis.meshPerAttribute = source.meshPerAttribute;\n\n\t\treturn this;\n\n\t}\n\n\tclone( data ) {\n\n\t\tconst ib = super.clone( data );\n\n\t\tib.meshPerAttribute = this.meshPerAttribute;\n\n\t\treturn ib;\n\n\t}\n\n\ttoJSON( data ) {\n\n\t\tconst json = super.toJSON( data );\n\n\t\tjson.isInstancedInterleavedBuffer = true;\n\t\tjson.meshPerAttribute = this.meshPerAttribute;\n\n\t\treturn json;\n\n\t}\n\n}\n\nclass GLBufferAttribute {\n\n\tconstructor( buffer, type, itemSize, elementSize, count ) {\n\n\t\tthis.isGLBufferAttribute = true;\n\n\t\tthis.name = '';\n\n\t\tthis.buffer = buffer;\n\t\tthis.type = type;\n\t\tthis.itemSize = itemSize;\n\t\tthis.elementSize = elementSize;\n\t\tthis.count = count;\n\n\t\tthis.version = 0;\n\n\t}\n\n\tset needsUpdate( value ) {\n\n\t\tif ( value === true ) this.version ++;\n\n\t}\n\n\tsetBuffer( buffer ) {\n\n\t\tthis.buffer = buffer;\n\n\t\treturn this;\n\n\t}\n\n\tsetType( type, elementSize ) {\n\n\t\tthis.type = type;\n\t\tthis.elementSize = elementSize;\n\n\t\treturn this;\n\n\t}\n\n\tsetItemSize( itemSize ) {\n\n\t\tthis.itemSize = itemSize;\n\n\t\treturn this;\n\n\t}\n\n\tsetCount( count ) {\n\n\t\tthis.count = count;\n\n\t\treturn this;\n\n\t}\n\n}\n\nclass Raycaster {\n\n\tconstructor( origin, direction, near = 0, far = Infinity ) {\n\n\t\tthis.ray = new Ray( origin, direction );\n\t\t// direction is assumed to be normalized (for accurate distance calculations)\n\n\t\tthis.near = near;\n\t\tthis.far = far;\n\t\tthis.camera = null;\n\t\tthis.layers = new Layers();\n\n\t\tthis.params = {\n\t\t\tMesh: {},\n\t\t\tLine: { threshold: 1 },\n\t\t\tLOD: {},\n\t\t\tPoints: { threshold: 1 },\n\t\t\tSprite: {}\n\t\t};\n\n\t}\n\n\tset( origin, direction ) {\n\n\t\t// direction is assumed to be normalized (for accurate distance calculations)\n\n\t\tthis.ray.set( origin, direction );\n\n\t}\n\n\tsetFromCamera( coords, camera ) {\n\n\t\tif ( camera.isPerspectiveCamera ) {\n\n\t\t\tthis.ray.origin.setFromMatrixPosition( camera.matrixWorld );\n\t\t\tthis.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();\n\t\t\tthis.camera = camera;\n\n\t\t} else if ( camera.isOrthographicCamera ) {\n\n\t\t\tthis.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera\n\t\t\tthis.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );\n\t\t\tthis.camera = camera;\n\n\t\t} else {\n\n\t\t\tconsole.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );\n\n\t\t}\n\n\t}\n\n\tintersectObject( object, recursive = true, intersects = [] ) {\n\n\t\tintersectObject( object, this, intersects, recursive );\n\n\t\tintersects.sort( ascSort );\n\n\t\treturn intersects;\n\n\t}\n\n\tintersectObjects( objects, recursive = true, intersects = [] ) {\n\n\t\tfor ( let i = 0, l = objects.length; i < l; i ++ ) {\n\n\t\t\tintersectObject( objects[ i ], this, intersects, recursive );\n\n\t\t}\n\n\t\tintersects.sort( ascSort );\n\n\t\treturn intersects;\n\n\t}\n\n}\n\nfunction ascSort( a, b ) {\n\n\treturn a.distance - b.distance;\n\n}\n\nfunction intersectObject( object, raycaster, intersects, recursive ) {\n\n\tif ( object.layers.test( raycaster.layers ) ) {\n\n\t\tobject.raycast( raycaster, intersects );\n\n\t}\n\n\tif ( recursive === true ) {\n\n\t\tconst children = object.children;\n\n\t\tfor ( let i = 0, l = children.length; i < l; i ++ ) {\n\n\t\t\tintersectObject( children[ i ], raycaster, intersects, true );\n\n\t\t}\n\n\t}\n\n}\n\n/**\n * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system\n *\n * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.\n * The azimuthal angle (theta) is measured from the positive z-axis.\n */\n\nclass Spherical {\n\n\tconstructor( radius = 1, phi = 0, theta = 0 ) {\n\n\t\tthis.radius = radius;\n\t\tthis.phi = phi; // polar angle\n\t\tthis.theta = theta; // azimuthal angle\n\n\t\treturn this;\n\n\t}\n\n\tset( radius, phi, theta ) {\n\n\t\tthis.radius = radius;\n\t\tthis.phi = phi;\n\t\tthis.theta = theta;\n\n\t\treturn this;\n\n\t}\n\n\tcopy( other ) {\n\n\t\tthis.radius = other.radius;\n\t\tthis.phi = other.phi;\n\t\tthis.theta = other.theta;\n\n\t\treturn this;\n\n\t}\n\n\t// restrict phi to be between EPS and PI-EPS\n\tmakeSafe() {\n\n\t\tconst EPS = 0.000001;\n\t\tthis.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );\n\n\t\treturn this;\n\n\t}\n\n\tsetFromVector3( v ) {\n\n\t\treturn this.setFromCartesianCoords( v.x, v.y, v.z );\n\n\t}\n\n\tsetFromCartesianCoords( x, y, z ) {\n\n\t\tthis.radius = Math.sqrt( x * x + y * y + z * z );\n\n\t\tif ( this.radius === 0 ) {\n\n\t\t\tthis.theta = 0;\n\t\t\tthis.phi = 0;\n\n\t\t} else {\n\n\t\t\tthis.theta = Math.atan2( x, z );\n\t\t\tthis.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n}\n\n/**\n * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system\n */\n\nclass Cylindrical {\n\n\tconstructor( radius = 1, theta = 0, y = 0 ) {\n\n\t\tthis.radius = radius; // distance from the origin to a point in the x-z plane\n\t\tthis.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis\n\t\tthis.y = y; // height above the x-z plane\n\n\t\treturn this;\n\n\t}\n\n\tset( radius, theta, y ) {\n\n\t\tthis.radius = radius;\n\t\tthis.theta = theta;\n\t\tthis.y = y;\n\n\t\treturn this;\n\n\t}\n\n\tcopy( other ) {\n\n\t\tthis.radius = other.radius;\n\t\tthis.theta = other.theta;\n\t\tthis.y = other.y;\n\n\t\treturn this;\n\n\t}\n\n\tsetFromVector3( v ) {\n\n\t\treturn this.setFromCartesianCoords( v.x, v.y, v.z );\n\n\t}\n\n\tsetFromCartesianCoords( x, y, z ) {\n\n\t\tthis.radius = Math.sqrt( x * x + z * z );\n\t\tthis.theta = Math.atan2( x, z );\n\t\tthis.y = y;\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n}\n\nconst _vector$4 = /*@__PURE__*/ new Vector2();\n\nclass Box2 {\n\n\tconstructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {\n\n\t\tthis.isBox2 = true;\n\n\t\tthis.min = min;\n\t\tthis.max = max;\n\n\t}\n\n\tset( min, max ) {\n\n\t\tthis.min.copy( min );\n\t\tthis.max.copy( max );\n\n\t\treturn this;\n\n\t}\n\n\tsetFromPoints( points ) {\n\n\t\tthis.makeEmpty();\n\n\t\tfor ( let i = 0, il = points.length; i < il; i ++ ) {\n\n\t\t\tthis.expandByPoint( points[ i ] );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tsetFromCenterAndSize( center, size ) {\n\n\t\tconst halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );\n\t\tthis.min.copy( center ).sub( halfSize );\n\t\tthis.max.copy( center ).add( halfSize );\n\n\t\treturn this;\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n\tcopy( box ) {\n\n\t\tthis.min.copy( box.min );\n\t\tthis.max.copy( box.max );\n\n\t\treturn this;\n\n\t}\n\n\tmakeEmpty() {\n\n\t\tthis.min.x = this.min.y = + Infinity;\n\t\tthis.max.x = this.max.y = - Infinity;\n\n\t\treturn this;\n\n\t}\n\n\tisEmpty() {\n\n\t\t// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes\n\n\t\treturn ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );\n\n\t}\n\n\tgetCenter( target ) {\n\n\t\treturn this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );\n\n\t}\n\n\tgetSize( target ) {\n\n\t\treturn this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );\n\n\t}\n\n\texpandByPoint( point ) {\n\n\t\tthis.min.min( point );\n\t\tthis.max.max( point );\n\n\t\treturn this;\n\n\t}\n\n\texpandByVector( vector ) {\n\n\t\tthis.min.sub( vector );\n\t\tthis.max.add( vector );\n\n\t\treturn this;\n\n\t}\n\n\texpandByScalar( scalar ) {\n\n\t\tthis.min.addScalar( - scalar );\n\t\tthis.max.addScalar( scalar );\n\n\t\treturn this;\n\n\t}\n\n\tcontainsPoint( point ) {\n\n\t\treturn point.x < this.min.x || point.x > this.max.x ||\n\t\t\tpoint.y < this.min.y || point.y > this.max.y ? false : true;\n\n\t}\n\n\tcontainsBox( box ) {\n\n\t\treturn this.min.x <= box.min.x && box.max.x <= this.max.x &&\n\t\t\tthis.min.y <= box.min.y && box.max.y <= this.max.y;\n\n\t}\n\n\tgetParameter( point, target ) {\n\n\t\t// This can potentially have a divide by zero if the box\n\t\t// has a size dimension of 0.\n\n\t\treturn target.set(\n\t\t\t( point.x - this.min.x ) / ( this.max.x - this.min.x ),\n\t\t\t( point.y - this.min.y ) / ( this.max.y - this.min.y )\n\t\t);\n\n\t}\n\n\tintersectsBox( box ) {\n\n\t\t// using 4 splitting planes to rule out intersections\n\n\t\treturn box.max.x < this.min.x || box.min.x > this.max.x ||\n\t\t\tbox.max.y < this.min.y || box.min.y > this.max.y ? false : true;\n\n\t}\n\n\tclampPoint( point, target ) {\n\n\t\treturn target.copy( point ).clamp( this.min, this.max );\n\n\t}\n\n\tdistanceToPoint( point ) {\n\n\t\treturn this.clampPoint( point, _vector$4 ).distanceTo( point );\n\n\t}\n\n\tintersect( box ) {\n\n\t\tthis.min.max( box.min );\n\t\tthis.max.min( box.max );\n\n\t\tif ( this.isEmpty() ) this.makeEmpty();\n\n\t\treturn this;\n\n\t}\n\n\tunion( box ) {\n\n\t\tthis.min.min( box.min );\n\t\tthis.max.max( box.max );\n\n\t\treturn this;\n\n\t}\n\n\ttranslate( offset ) {\n\n\t\tthis.min.add( offset );\n\t\tthis.max.add( offset );\n\n\t\treturn this;\n\n\t}\n\n\tequals( box ) {\n\n\t\treturn box.min.equals( this.min ) && box.max.equals( this.max );\n\n\t}\n\n}\n\nconst _startP = /*@__PURE__*/ new Vector3();\nconst _startEnd = /*@__PURE__*/ new Vector3();\n\nclass Line3 {\n\n\tconstructor( start = new Vector3(), end = new Vector3() ) {\n\n\t\tthis.start = start;\n\t\tthis.end = end;\n\n\t}\n\n\tset( start, end ) {\n\n\t\tthis.start.copy( start );\n\t\tthis.end.copy( end );\n\n\t\treturn this;\n\n\t}\n\n\tcopy( line ) {\n\n\t\tthis.start.copy( line.start );\n\t\tthis.end.copy( line.end );\n\n\t\treturn this;\n\n\t}\n\n\tgetCenter( target ) {\n\n\t\treturn target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );\n\n\t}\n\n\tdelta( target ) {\n\n\t\treturn target.subVectors( this.end, this.start );\n\n\t}\n\n\tdistanceSq() {\n\n\t\treturn this.start.distanceToSquared( this.end );\n\n\t}\n\n\tdistance() {\n\n\t\treturn this.start.distanceTo( this.end );\n\n\t}\n\n\tat( t, target ) {\n\n\t\treturn this.delta( target ).multiplyScalar( t ).add( this.start );\n\n\t}\n\n\tclosestPointToPointParameter( point, clampToLine ) {\n\n\t\t_startP.subVectors( point, this.start );\n\t\t_startEnd.subVectors( this.end, this.start );\n\n\t\tconst startEnd2 = _startEnd.dot( _startEnd );\n\t\tconst startEnd_startP = _startEnd.dot( _startP );\n\n\t\tlet t = startEnd_startP / startEnd2;\n\n\t\tif ( clampToLine ) {\n\n\t\t\tt = clamp( t, 0, 1 );\n\n\t\t}\n\n\t\treturn t;\n\n\t}\n\n\tclosestPointToPoint( point, clampToLine, target ) {\n\n\t\tconst t = this.closestPointToPointParameter( point, clampToLine );\n\n\t\treturn this.delta( target ).multiplyScalar( t ).add( this.start );\n\n\t}\n\n\tapplyMatrix4( matrix ) {\n\n\t\tthis.start.applyMatrix4( matrix );\n\t\tthis.end.applyMatrix4( matrix );\n\n\t\treturn this;\n\n\t}\n\n\tequals( line ) {\n\n\t\treturn line.start.equals( this.start ) && line.end.equals( this.end );\n\n\t}\n\n\tclone() {\n\n\t\treturn new this.constructor().copy( this );\n\n\t}\n\n}\n\nconst _vector$3 = /*@__PURE__*/ new Vector3();\n\nclass SpotLightHelper extends Object3D {\n\n\tconstructor( light, color ) {\n\n\t\tsuper();\n\n\t\tthis.light = light;\n\n\t\tthis.matrix = light.matrixWorld;\n\t\tthis.matrixAutoUpdate = false;\n\n\t\tthis.color = color;\n\n\t\tthis.type = 'SpotLightHelper';\n\n\t\tconst geometry = new BufferGeometry();\n\n\t\tconst positions = [\n\t\t\t0, 0, 0, \t0, 0, 1,\n\t\t\t0, 0, 0, \t1, 0, 1,\n\t\t\t0, 0, 0,\t- 1, 0, 1,\n\t\t\t0, 0, 0, \t0, 1, 1,\n\t\t\t0, 0, 0, \t0, - 1, 1\n\t\t];\n\n\t\tfor ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {\n\n\t\t\tconst p1 = ( i / l ) * Math.PI * 2;\n\t\t\tconst p2 = ( j / l ) * Math.PI * 2;\n\n\t\t\tpositions.push(\n\t\t\t\tMath.cos( p1 ), Math.sin( p1 ), 1,\n\t\t\t\tMath.cos( p2 ), Math.sin( p2 ), 1\n\t\t\t);\n\n\t\t}\n\n\t\tgeometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );\n\n\t\tconst material = new LineBasicMaterial( { fog: false, toneMapped: false } );\n\n\t\tthis.cone = new LineSegments( geometry, material );\n\t\tthis.add( this.cone );\n\n\t\tthis.update();\n\n\t}\n\n\tdispose() {\n\n\t\tthis.cone.geometry.dispose();\n\t\tthis.cone.material.dispose();\n\n\t}\n\n\tupdate() {\n\n\t\tthis.light.updateWorldMatrix( true, false );\n\t\tthis.light.target.updateWorldMatrix( true, false );\n\n\t\tconst coneLength = this.light.distance ? this.light.distance : 1000;\n\t\tconst coneWidth = coneLength * Math.tan( this.light.angle );\n\n\t\tthis.cone.scale.set( coneWidth, coneWidth, coneLength );\n\n\t\t_vector$3.setFromMatrixPosition( this.light.target.matrixWorld );\n\n\t\tthis.cone.lookAt( _vector$3 );\n\n\t\tif ( this.color !== undefined ) {\n\n\t\t\tthis.cone.material.color.set( this.color );\n\n\t\t} else {\n\n\t\t\tthis.cone.material.color.copy( this.light.color );\n\n\t\t}\n\n\t}\n\n}\n\nconst _vector$2 = /*@__PURE__*/ new Vector3();\nconst _boneMatrix = /*@__PURE__*/ new Matrix4();\nconst _matrixWorldInv = /*@__PURE__*/ new Matrix4();\n\n\nclass SkeletonHelper extends LineSegments {\n\n\tconstructor( object ) {\n\n\t\tconst bones = getBoneList( object );\n\n\t\tconst geometry = new BufferGeometry();\n\n\t\tconst vertices = [];\n\t\tconst colors = [];\n\n\t\tconst color1 = new Color( 0, 0, 1 );\n\t\tconst color2 = new Color( 0, 1, 0 );\n\n\t\tfor ( let i = 0; i < bones.length; i ++ ) {\n\n\t\t\tconst bone = bones[ i ];\n\n\t\t\tif ( bone.parent && bone.parent.isBone ) {\n\n\t\t\t\tvertices.push( 0, 0, 0 );\n\t\t\t\tvertices.push( 0, 0, 0 );\n\t\t\t\tcolors.push( color1.r, color1.g, color1.b );\n\t\t\t\tcolors.push( color2.r, color2.g, color2.b );\n\n\t\t\t}\n\n\t\t}\n\n\t\tgeometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tgeometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );\n\n\t\tconst material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );\n\n\t\tsuper( geometry, material );\n\n\t\tthis.isSkeletonHelper = true;\n\n\t\tthis.type = 'SkeletonHelper';\n\n\t\tthis.root = object;\n\t\tthis.bones = bones;\n\n\t\tthis.matrix = object.matrixWorld;\n\t\tthis.matrixAutoUpdate = false;\n\n\t}\n\n\tupdateMatrixWorld( force ) {\n\n\t\tconst bones = this.bones;\n\n\t\tconst geometry = this.geometry;\n\t\tconst position = geometry.getAttribute( 'position' );\n\n\t\t_matrixWorldInv.copy( this.root.matrixWorld ).invert();\n\n\t\tfor ( let i = 0, j = 0; i < bones.length; i ++ ) {\n\n\t\t\tconst bone = bones[ i ];\n\n\t\t\tif ( bone.parent && bone.parent.isBone ) {\n\n\t\t\t\t_boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );\n\t\t\t\t_vector$2.setFromMatrixPosition( _boneMatrix );\n\t\t\t\tposition.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );\n\n\t\t\t\t_boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );\n\t\t\t\t_vector$2.setFromMatrixPosition( _boneMatrix );\n\t\t\t\tposition.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );\n\n\t\t\t\tj += 2;\n\n\t\t\t}\n\n\t\t}\n\n\t\tgeometry.getAttribute( 'position' ).needsUpdate = true;\n\n\t\tsuper.updateMatrixWorld( force );\n\n\t}\n\n\tdispose() {\n\n\t\tthis.geometry.dispose();\n\t\tthis.material.dispose();\n\n\t}\n\n}\n\n\nfunction getBoneList( object ) {\n\n\tconst boneList = [];\n\n\tif ( object.isBone === true ) {\n\n\t\tboneList.push( object );\n\n\t}\n\n\tfor ( let i = 0; i < object.children.length; i ++ ) {\n\n\t\tboneList.push.apply( boneList, getBoneList( object.children[ i ] ) );\n\n\t}\n\n\treturn boneList;\n\n}\n\nclass PointLightHelper extends Mesh {\n\n\tconstructor( light, sphereSize, color ) {\n\n\t\tconst geometry = new SphereGeometry( sphereSize, 4, 2 );\n\t\tconst material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );\n\n\t\tsuper( geometry, material );\n\n\t\tthis.light = light;\n\n\t\tthis.color = color;\n\n\t\tthis.type = 'PointLightHelper';\n\n\t\tthis.matrix = this.light.matrixWorld;\n\t\tthis.matrixAutoUpdate = false;\n\n\t\tthis.update();\n\n\n\t\t/*\n\t// TODO: delete this comment?\n\tconst distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );\n\tconst distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );\n\n\tthis.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );\n\tthis.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );\n\n\tconst d = light.distance;\n\n\tif ( d === 0.0 ) {\n\n\t\tthis.lightDistance.visible = false;\n\n\t} else {\n\n\t\tthis.lightDistance.scale.set( d, d, d );\n\n\t}\n\n\tthis.add( this.lightDistance );\n\t*/\n\n\t}\n\n\tdispose() {\n\n\t\tthis.geometry.dispose();\n\t\tthis.material.dispose();\n\n\t}\n\n\tupdate() {\n\n\t\tthis.light.updateWorldMatrix( true, false );\n\n\t\tif ( this.color !== undefined ) {\n\n\t\t\tthis.material.color.set( this.color );\n\n\t\t} else {\n\n\t\t\tthis.material.color.copy( this.light.color );\n\n\t\t}\n\n\t\t/*\n\t\tconst d = this.light.distance;\n\n\t\tif ( d === 0.0 ) {\n\n\t\t\tthis.lightDistance.visible = false;\n\n\t\t} else {\n\n\t\t\tthis.lightDistance.visible = true;\n\t\t\tthis.lightDistance.scale.set( d, d, d );\n\n\t\t}\n\t\t*/\n\n\t}\n\n}\n\nconst _vector$1 = /*@__PURE__*/ new Vector3();\nconst _color1 = /*@__PURE__*/ new Color();\nconst _color2 = /*@__PURE__*/ new Color();\n\nclass HemisphereLightHelper extends Object3D {\n\n\tconstructor( light, size, color ) {\n\n\t\tsuper();\n\n\t\tthis.light = light;\n\n\t\tthis.matrix = light.matrixWorld;\n\t\tthis.matrixAutoUpdate = false;\n\n\t\tthis.color = color;\n\n\t\tthis.type = 'HemisphereLightHelper';\n\n\t\tconst geometry = new OctahedronGeometry( size );\n\t\tgeometry.rotateY( Math.PI * 0.5 );\n\n\t\tthis.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );\n\t\tif ( this.color === undefined ) this.material.vertexColors = true;\n\n\t\tconst position = geometry.getAttribute( 'position' );\n\t\tconst colors = new Float32Array( position.count * 3 );\n\n\t\tgeometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );\n\n\t\tthis.add( new Mesh( geometry, this.material ) );\n\n\t\tthis.update();\n\n\t}\n\n\tdispose() {\n\n\t\tthis.children[ 0 ].geometry.dispose();\n\t\tthis.children[ 0 ].material.dispose();\n\n\t}\n\n\tupdate() {\n\n\t\tconst mesh = this.children[ 0 ];\n\n\t\tif ( this.color !== undefined ) {\n\n\t\t\tthis.material.color.set( this.color );\n\n\t\t} else {\n\n\t\t\tconst colors = mesh.geometry.getAttribute( 'color' );\n\n\t\t\t_color1.copy( this.light.color );\n\t\t\t_color2.copy( this.light.groundColor );\n\n\t\t\tfor ( let i = 0, l = colors.count; i < l; i ++ ) {\n\n\t\t\t\tconst color = ( i < ( l / 2 ) ) ? _color1 : _color2;\n\n\t\t\t\tcolors.setXYZ( i, color.r, color.g, color.b );\n\n\t\t\t}\n\n\t\t\tcolors.needsUpdate = true;\n\n\t\t}\n\n\t\tthis.light.updateWorldMatrix( true, false );\n\n\t\tmesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );\n\n\t}\n\n}\n\nclass GridHelper extends LineSegments {\n\n\tconstructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {\n\n\t\tcolor1 = new Color( color1 );\n\t\tcolor2 = new Color( color2 );\n\n\t\tconst center = divisions / 2;\n\t\tconst step = size / divisions;\n\t\tconst halfSize = size / 2;\n\n\t\tconst vertices = [], colors = [];\n\n\t\tfor ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {\n\n\t\t\tvertices.push( - halfSize, 0, k, halfSize, 0, k );\n\t\t\tvertices.push( k, 0, - halfSize, k, 0, halfSize );\n\n\t\t\tconst color = i === center ? color1 : color2;\n\n\t\t\tcolor.toArray( colors, j ); j += 3;\n\t\t\tcolor.toArray( colors, j ); j += 3;\n\t\t\tcolor.toArray( colors, j ); j += 3;\n\t\t\tcolor.toArray( colors, j ); j += 3;\n\n\t\t}\n\n\t\tconst geometry = new BufferGeometry();\n\t\tgeometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tgeometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );\n\n\t\tconst material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );\n\n\t\tsuper( geometry, material );\n\n\t\tthis.type = 'GridHelper';\n\n\t}\n\n\tdispose() {\n\n\t\tthis.geometry.dispose();\n\t\tthis.material.dispose();\n\n\t}\n\n}\n\nclass PolarGridHelper extends LineSegments {\n\n\tconstructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {\n\n\t\tcolor1 = new Color( color1 );\n\t\tcolor2 = new Color( color2 );\n\n\t\tconst vertices = [];\n\t\tconst colors = [];\n\n\t\t// create the sectors\n\n\t\tif ( sectors > 1 ) {\n\n\t\t\tfor ( let i = 0; i < sectors; i ++ ) {\n\n\t\t\t\tconst v = ( i / sectors ) * ( Math.PI * 2 );\n\n\t\t\t\tconst x = Math.sin( v ) * radius;\n\t\t\t\tconst z = Math.cos( v ) * radius;\n\n\t\t\t\tvertices.push( 0, 0, 0 );\n\t\t\t\tvertices.push( x, 0, z );\n\n\t\t\t\tconst color = ( i & 1 ) ? color1 : color2;\n\n\t\t\t\tcolors.push( color.r, color.g, color.b );\n\t\t\t\tcolors.push( color.r, color.g, color.b );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// create the rings\n\n\t\tfor ( let i = 0; i < rings; i ++ ) {\n\n\t\t\tconst color = ( i & 1 ) ? color1 : color2;\n\n\t\t\tconst r = radius - ( radius / rings * i );\n\n\t\t\tfor ( let j = 0; j < divisions; j ++ ) {\n\n\t\t\t\t// first vertex\n\n\t\t\t\tlet v = ( j / divisions ) * ( Math.PI * 2 );\n\n\t\t\t\tlet x = Math.sin( v ) * r;\n\t\t\t\tlet z = Math.cos( v ) * r;\n\n\t\t\t\tvertices.push( x, 0, z );\n\t\t\t\tcolors.push( color.r, color.g, color.b );\n\n\t\t\t\t// second vertex\n\n\t\t\t\tv = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );\n\n\t\t\t\tx = Math.sin( v ) * r;\n\t\t\t\tz = Math.cos( v ) * r;\n\n\t\t\t\tvertices.push( x, 0, z );\n\t\t\t\tcolors.push( color.r, color.g, color.b );\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst geometry = new BufferGeometry();\n\t\tgeometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tgeometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );\n\n\t\tconst material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );\n\n\t\tsuper( geometry, material );\n\n\t\tthis.type = 'PolarGridHelper';\n\n\t}\n\n\tdispose() {\n\n\t\tthis.geometry.dispose();\n\t\tthis.material.dispose();\n\n\t}\n\n}\n\nconst _v1 = /*@__PURE__*/ new Vector3();\nconst _v2 = /*@__PURE__*/ new Vector3();\nconst _v3 = /*@__PURE__*/ new Vector3();\n\nclass DirectionalLightHelper extends Object3D {\n\n\tconstructor( light, size, color ) {\n\n\t\tsuper();\n\n\t\tthis.light = light;\n\n\t\tthis.matrix = light.matrixWorld;\n\t\tthis.matrixAutoUpdate = false;\n\n\t\tthis.color = color;\n\n\t\tthis.type = 'DirectionalLightHelper';\n\n\t\tif ( size === undefined ) size = 1;\n\n\t\tlet geometry = new BufferGeometry();\n\t\tgeometry.setAttribute( 'position', new Float32BufferAttribute( [\n\t\t\t- size, size, 0,\n\t\t\tsize, size, 0,\n\t\t\tsize, - size, 0,\n\t\t\t- size, - size, 0,\n\t\t\t- size, size, 0\n\t\t], 3 ) );\n\n\t\tconst material = new LineBasicMaterial( { fog: false, toneMapped: false } );\n\n\t\tthis.lightPlane = new Line( geometry, material );\n\t\tthis.add( this.lightPlane );\n\n\t\tgeometry = new BufferGeometry();\n\t\tgeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );\n\n\t\tthis.targetLine = new Line( geometry, material );\n\t\tthis.add( this.targetLine );\n\n\t\tthis.update();\n\n\t}\n\n\tdispose() {\n\n\t\tthis.lightPlane.geometry.dispose();\n\t\tthis.lightPlane.material.dispose();\n\t\tthis.targetLine.geometry.dispose();\n\t\tthis.targetLine.material.dispose();\n\n\t}\n\n\tupdate() {\n\n\t\tthis.light.updateWorldMatrix( true, false );\n\t\tthis.light.target.updateWorldMatrix( true, false );\n\n\t\t_v1.setFromMatrixPosition( this.light.matrixWorld );\n\t\t_v2.setFromMatrixPosition( this.light.target.matrixWorld );\n\t\t_v3.subVectors( _v2, _v1 );\n\n\t\tthis.lightPlane.lookAt( _v2 );\n\n\t\tif ( this.color !== undefined ) {\n\n\t\t\tthis.lightPlane.material.color.set( this.color );\n\t\t\tthis.targetLine.material.color.set( this.color );\n\n\t\t} else {\n\n\t\t\tthis.lightPlane.material.color.copy( this.light.color );\n\t\t\tthis.targetLine.material.color.copy( this.light.color );\n\n\t\t}\n\n\t\tthis.targetLine.lookAt( _v2 );\n\t\tthis.targetLine.scale.z = _v3.length();\n\n\t}\n\n}\n\nconst _vector = /*@__PURE__*/ new Vector3();\nconst _camera = /*@__PURE__*/ new Camera();\n\n/**\n *\t- shows frustum, line of sight and up of the camera\n *\t- suitable for fast updates\n * \t- based on frustum visualization in lightgl.js shadowmap example\n *\t\thttps://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html\n */\n\nclass CameraHelper extends LineSegments {\n\n\tconstructor( camera ) {\n\n\t\tconst geometry = new BufferGeometry();\n\t\tconst material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );\n\n\t\tconst vertices = [];\n\t\tconst colors = [];\n\n\t\tconst pointMap = {};\n\n\t\t// near\n\n\t\taddLine( 'n1', 'n2' );\n\t\taddLine( 'n2', 'n4' );\n\t\taddLine( 'n4', 'n3' );\n\t\taddLine( 'n3', 'n1' );\n\n\t\t// far\n\n\t\taddLine( 'f1', 'f2' );\n\t\taddLine( 'f2', 'f4' );\n\t\taddLine( 'f4', 'f3' );\n\t\taddLine( 'f3', 'f1' );\n\n\t\t// sides\n\n\t\taddLine( 'n1', 'f1' );\n\t\taddLine( 'n2', 'f2' );\n\t\taddLine( 'n3', 'f3' );\n\t\taddLine( 'n4', 'f4' );\n\n\t\t// cone\n\n\t\taddLine( 'p', 'n1' );\n\t\taddLine( 'p', 'n2' );\n\t\taddLine( 'p', 'n3' );\n\t\taddLine( 'p', 'n4' );\n\n\t\t// up\n\n\t\taddLine( 'u1', 'u2' );\n\t\taddLine( 'u2', 'u3' );\n\t\taddLine( 'u3', 'u1' );\n\n\t\t// target\n\n\t\taddLine( 'c', 't' );\n\t\taddLine( 'p', 'c' );\n\n\t\t// cross\n\n\t\taddLine( 'cn1', 'cn2' );\n\t\taddLine( 'cn3', 'cn4' );\n\n\t\taddLine( 'cf1', 'cf2' );\n\t\taddLine( 'cf3', 'cf4' );\n\n\t\tfunction addLine( a, b ) {\n\n\t\t\taddPoint( a );\n\t\t\taddPoint( b );\n\n\t\t}\n\n\t\tfunction addPoint( id ) {\n\n\t\t\tvertices.push( 0, 0, 0 );\n\t\t\tcolors.push( 0, 0, 0 );\n\n\t\t\tif ( pointMap[ id ] === undefined ) {\n\n\t\t\t\tpointMap[ id ] = [];\n\n\t\t\t}\n\n\t\t\tpointMap[ id ].push( ( vertices.length / 3 ) - 1 );\n\n\t\t}\n\n\t\tgeometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tgeometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );\n\n\t\tsuper( geometry, material );\n\n\t\tthis.type = 'CameraHelper';\n\n\t\tthis.camera = camera;\n\t\tif ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();\n\n\t\tthis.matrix = camera.matrixWorld;\n\t\tthis.matrixAutoUpdate = false;\n\n\t\tthis.pointMap = pointMap;\n\n\t\tthis.update();\n\n\t\t// colors\n\n\t\tconst colorFrustum = new Color( 0xffaa00 );\n\t\tconst colorCone = new Color( 0xff0000 );\n\t\tconst colorUp = new Color( 0x00aaff );\n\t\tconst colorTarget = new Color( 0xffffff );\n\t\tconst colorCross = new Color( 0x333333 );\n\n\t\tthis.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );\n\n\t}\n\n\tsetColors( frustum, cone, up, target, cross ) {\n\n\t\tconst geometry = this.geometry;\n\n\t\tconst colorAttribute = geometry.getAttribute( 'color' );\n\n\t\t// near\n\n\t\tcolorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2\n\t\tcolorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4\n\t\tcolorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3\n\t\tcolorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1\n\n\t\t// far\n\n\t\tcolorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2\n\t\tcolorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4\n\t\tcolorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3\n\t\tcolorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1\n\n\t\t// sides\n\n\t\tcolorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1\n\t\tcolorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2\n\t\tcolorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3\n\t\tcolorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4\n\n\t\t// cone\n\n\t\tcolorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1\n\t\tcolorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2\n\t\tcolorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3\n\t\tcolorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4\n\n\t\t// up\n\n\t\tcolorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2\n\t\tcolorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3\n\t\tcolorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1\n\n\t\t// target\n\n\t\tcolorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t\n\t\tcolorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c\n\n\t\t// cross\n\n\t\tcolorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2\n\t\tcolorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4\n\n\t\tcolorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2\n\t\tcolorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4\n\n\t\tcolorAttribute.needsUpdate = true;\n\n\t}\n\n\tupdate() {\n\n\t\tconst geometry = this.geometry;\n\t\tconst pointMap = this.pointMap;\n\n\t\tconst w = 1, h = 1;\n\n\t\t// we need just camera projection matrix inverse\n\t\t// world matrix must be identity\n\n\t\t_camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );\n\n\t\t// center / target\n\n\t\tsetPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );\n\t\tsetPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );\n\n\t\t// near\n\n\t\tsetPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );\n\t\tsetPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );\n\t\tsetPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );\n\t\tsetPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );\n\n\t\t// far\n\n\t\tsetPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );\n\t\tsetPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );\n\t\tsetPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );\n\t\tsetPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );\n\n\t\t// up\n\n\t\tsetPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );\n\t\tsetPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );\n\t\tsetPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );\n\n\t\t// cross\n\n\t\tsetPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );\n\t\tsetPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );\n\t\tsetPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );\n\t\tsetPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );\n\n\t\tsetPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );\n\t\tsetPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );\n\t\tsetPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );\n\t\tsetPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );\n\n\t\tgeometry.getAttribute( 'position' ).needsUpdate = true;\n\n\t}\n\n\tdispose() {\n\n\t\tthis.geometry.dispose();\n\t\tthis.material.dispose();\n\n\t}\n\n}\n\n\nfunction setPoint( point, pointMap, geometry, camera, x, y, z ) {\n\n\t_vector.set( x, y, z ).unproject( camera );\n\n\tconst points = pointMap[ point ];\n\n\tif ( points !== undefined ) {\n\n\t\tconst position = geometry.getAttribute( 'position' );\n\n\t\tfor ( let i = 0, l = points.length; i < l; i ++ ) {\n\n\t\t\tposition.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );\n\n\t\t}\n\n\t}\n\n}\n\nconst _box = /*@__PURE__*/ new Box3();\n\nclass BoxHelper extends LineSegments {\n\n\tconstructor( object, color = 0xffff00 ) {\n\n\t\tconst indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );\n\t\tconst positions = new Float32Array( 8 * 3 );\n\n\t\tconst geometry = new BufferGeometry();\n\t\tgeometry.setIndex( new BufferAttribute( indices, 1 ) );\n\t\tgeometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );\n\n\t\tsuper( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );\n\n\t\tthis.object = object;\n\t\tthis.type = 'BoxHelper';\n\n\t\tthis.matrixAutoUpdate = false;\n\n\t\tthis.update();\n\n\t}\n\n\tupdate( object ) {\n\n\t\tif ( object !== undefined ) {\n\n\t\t\tconsole.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );\n\n\t\t}\n\n\t\tif ( this.object !== undefined ) {\n\n\t\t\t_box.setFromObject( this.object );\n\n\t\t}\n\n\t\tif ( _box.isEmpty() ) return;\n\n\t\tconst min = _box.min;\n\t\tconst max = _box.max;\n\n\t\t/*\n\t\t\t5____4\n\t\t1/___0/|\n\t\t| 6__|_7\n\t\t2/___3/\n\n\t\t0: max.x, max.y, max.z\n\t\t1: min.x, max.y, max.z\n\t\t2: min.x, min.y, max.z\n\t\t3: max.x, min.y, max.z\n\t\t4: max.x, max.y, min.z\n\t\t5: min.x, max.y, min.z\n\t\t6: min.x, min.y, min.z\n\t\t7: max.x, min.y, min.z\n\t\t*/\n\n\t\tconst position = this.geometry.attributes.position;\n\t\tconst array = position.array;\n\n\t\tarray[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;\n\t\tarray[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;\n\t\tarray[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;\n\t\tarray[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;\n\t\tarray[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;\n\t\tarray[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;\n\t\tarray[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;\n\t\tarray[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;\n\n\t\tposition.needsUpdate = true;\n\n\t\tthis.geometry.computeBoundingSphere();\n\n\t}\n\n\tsetFromObject( object ) {\n\n\t\tthis.object = object;\n\t\tthis.update();\n\n\t\treturn this;\n\n\t}\n\n\tcopy( source, recursive ) {\n\n\t\tsuper.copy( source, recursive );\n\n\t\tthis.object = source.object;\n\n\t\treturn this;\n\n\t}\n\n\tdispose() {\n\n\t\tthis.geometry.dispose();\n\t\tthis.material.dispose();\n\n\t}\n\n}\n\nclass Box3Helper extends LineSegments {\n\n\tconstructor( box, color = 0xffff00 ) {\n\n\t\tconst indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );\n\n\t\tconst positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];\n\n\t\tconst geometry = new BufferGeometry();\n\n\t\tgeometry.setIndex( new BufferAttribute( indices, 1 ) );\n\n\t\tgeometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );\n\n\t\tsuper( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );\n\n\t\tthis.box = box;\n\n\t\tthis.type = 'Box3Helper';\n\n\t\tthis.geometry.computeBoundingSphere();\n\n\t}\n\n\tupdateMatrixWorld( force ) {\n\n\t\tconst box = this.box;\n\n\t\tif ( box.isEmpty() ) return;\n\n\t\tbox.getCenter( this.position );\n\n\t\tbox.getSize( this.scale );\n\n\t\tthis.scale.multiplyScalar( 0.5 );\n\n\t\tsuper.updateMatrixWorld( force );\n\n\t}\n\n\tdispose() {\n\n\t\tthis.geometry.dispose();\n\t\tthis.material.dispose();\n\n\t}\n\n}\n\nclass PlaneHelper extends Line {\n\n\tconstructor( plane, size = 1, hex = 0xffff00 ) {\n\n\t\tconst color = hex;\n\n\t\tconst positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ];\n\n\t\tconst geometry = new BufferGeometry();\n\t\tgeometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );\n\t\tgeometry.computeBoundingSphere();\n\n\t\tsuper( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );\n\n\t\tthis.type = 'PlaneHelper';\n\n\t\tthis.plane = plane;\n\n\t\tthis.size = size;\n\n\t\tconst positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];\n\n\t\tconst geometry2 = new BufferGeometry();\n\t\tgeometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );\n\t\tgeometry2.computeBoundingSphere();\n\n\t\tthis.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );\n\n\t}\n\n\tupdateMatrixWorld( force ) {\n\n\t\tthis.position.set( 0, 0, 0 );\n\n\t\tthis.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );\n\n\t\tthis.lookAt( this.plane.normal );\n\n\t\tthis.translateZ( - this.plane.constant );\n\n\t\tsuper.updateMatrixWorld( force );\n\n\t}\n\n\tdispose() {\n\n\t\tthis.geometry.dispose();\n\t\tthis.material.dispose();\n\t\tthis.children[ 0 ].geometry.dispose();\n\t\tthis.children[ 0 ].material.dispose();\n\n\t}\n\n}\n\nconst _axis = /*@__PURE__*/ new Vector3();\nlet _lineGeometry, _coneGeometry;\n\nclass ArrowHelper extends Object3D {\n\n\t// dir is assumed to be normalized\n\n\tconstructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) {\n\n\t\tsuper();\n\n\t\tthis.type = 'ArrowHelper';\n\n\t\tif ( _lineGeometry === undefined ) {\n\n\t\t\t_lineGeometry = new BufferGeometry();\n\t\t\t_lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );\n\n\t\t\t_coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );\n\t\t\t_coneGeometry.translate( 0, - 0.5, 0 );\n\n\t\t}\n\n\t\tthis.position.copy( origin );\n\n\t\tthis.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );\n\t\tthis.line.matrixAutoUpdate = false;\n\t\tthis.add( this.line );\n\n\t\tthis.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );\n\t\tthis.cone.matrixAutoUpdate = false;\n\t\tthis.add( this.cone );\n\n\t\tthis.setDirection( dir );\n\t\tthis.setLength( length, headLength, headWidth );\n\n\t}\n\n\tsetDirection( dir ) {\n\n\t\t// dir is assumed to be normalized\n\n\t\tif ( dir.y > 0.99999 ) {\n\n\t\t\tthis.quaternion.set( 0, 0, 0, 1 );\n\n\t\t} else if ( dir.y < - 0.99999 ) {\n\n\t\t\tthis.quaternion.set( 1, 0, 0, 0 );\n\n\t\t} else {\n\n\t\t\t_axis.set( dir.z, 0, - dir.x ).normalize();\n\n\t\t\tconst radians = Math.acos( dir.y );\n\n\t\t\tthis.quaternion.setFromAxisAngle( _axis, radians );\n\n\t\t}\n\n\t}\n\n\tsetLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {\n\n\t\tthis.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458\n\t\tthis.line.updateMatrix();\n\n\t\tthis.cone.scale.set( headWidth, headLength, headWidth );\n\t\tthis.cone.position.y = length;\n\t\tthis.cone.updateMatrix();\n\n\t}\n\n\tsetColor( color ) {\n\n\t\tthis.line.material.color.set( color );\n\t\tthis.cone.material.color.set( color );\n\n\t}\n\n\tcopy( source ) {\n\n\t\tsuper.copy( source, false );\n\n\t\tthis.line.copy( source.line );\n\t\tthis.cone.copy( source.cone );\n\n\t\treturn this;\n\n\t}\n\n\tdispose() {\n\n\t\tthis.line.geometry.dispose();\n\t\tthis.line.material.dispose();\n\t\tthis.cone.geometry.dispose();\n\t\tthis.cone.material.dispose();\n\n\t}\n\n}\n\nclass AxesHelper extends LineSegments {\n\n\tconstructor( size = 1 ) {\n\n\t\tconst vertices = [\n\t\t\t0, 0, 0,\tsize, 0, 0,\n\t\t\t0, 0, 0,\t0, size, 0,\n\t\t\t0, 0, 0,\t0, 0, size\n\t\t];\n\n\t\tconst colors = [\n\t\t\t1, 0, 0,\t1, 0.6, 0,\n\t\t\t0, 1, 0,\t0.6, 1, 0,\n\t\t\t0, 0, 1,\t0, 0.6, 1\n\t\t];\n\n\t\tconst geometry = new BufferGeometry();\n\t\tgeometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );\n\t\tgeometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );\n\n\t\tconst material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );\n\n\t\tsuper( geometry, material );\n\n\t\tthis.type = 'AxesHelper';\n\n\t}\n\n\tsetColors( xAxisColor, yAxisColor, zAxisColor ) {\n\n\t\tconst color = new Color();\n\t\tconst array = this.geometry.attributes.color.array;\n\n\t\tcolor.set( xAxisColor );\n\t\tcolor.toArray( array, 0 );\n\t\tcolor.toArray( array, 3 );\n\n\t\tcolor.set( yAxisColor );\n\t\tcolor.toArray( array, 6 );\n\t\tcolor.toArray( array, 9 );\n\n\t\tcolor.set( zAxisColor );\n\t\tcolor.toArray( array, 12 );\n\t\tcolor.toArray( array, 15 );\n\n\t\tthis.geometry.attributes.color.needsUpdate = true;\n\n\t\treturn this;\n\n\t}\n\n\tdispose() {\n\n\t\tthis.geometry.dispose();\n\t\tthis.material.dispose();\n\n\t}\n\n}\n\nclass ShapePath {\n\n\tconstructor() {\n\n\t\tthis.type = 'ShapePath';\n\n\t\tthis.color = new Color();\n\n\t\tthis.subPaths = [];\n\t\tthis.currentPath = null;\n\n\t}\n\n\tmoveTo( x, y ) {\n\n\t\tthis.currentPath = new Path();\n\t\tthis.subPaths.push( this.currentPath );\n\t\tthis.currentPath.moveTo( x, y );\n\n\t\treturn this;\n\n\t}\n\n\tlineTo( x, y ) {\n\n\t\tthis.currentPath.lineTo( x, y );\n\n\t\treturn this;\n\n\t}\n\n\tquadraticCurveTo( aCPx, aCPy, aX, aY ) {\n\n\t\tthis.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );\n\n\t\treturn this;\n\n\t}\n\n\tbezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {\n\n\t\tthis.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );\n\n\t\treturn this;\n\n\t}\n\n\tsplineThru( pts ) {\n\n\t\tthis.currentPath.splineThru( pts );\n\n\t\treturn this;\n\n\t}\n\n\ttoShapes( isCCW ) {\n\n\t\tfunction toShapesNoHoles( inSubpaths ) {\n\n\t\t\tconst shapes = [];\n\n\t\t\tfor ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {\n\n\t\t\t\tconst tmpPath = inSubpaths[ i ];\n\n\t\t\t\tconst tmpShape = new Shape();\n\t\t\t\ttmpShape.curves = tmpPath.curves;\n\n\t\t\t\tshapes.push( tmpShape );\n\n\t\t\t}\n\n\t\t\treturn shapes;\n\n\t\t}\n\n\t\tfunction isPointInsidePolygon( inPt, inPolygon ) {\n\n\t\t\tconst polyLen = inPolygon.length;\n\n\t\t\t// inPt on polygon contour => immediate success or\n\t\t\t// toggling of inside/outside at every single! intersection point of an edge\n\t\t\t// with the horizontal line through inPt, left of inPt\n\t\t\t// not counting lowerY endpoints of edges and whole edges on that line\n\t\t\tlet inside = false;\n\t\t\tfor ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {\n\n\t\t\t\tlet edgeLowPt = inPolygon[ p ];\n\t\t\t\tlet edgeHighPt = inPolygon[ q ];\n\n\t\t\t\tlet edgeDx = edgeHighPt.x - edgeLowPt.x;\n\t\t\t\tlet edgeDy = edgeHighPt.y - edgeLowPt.y;\n\n\t\t\t\tif ( Math.abs( edgeDy ) > Number.EPSILON ) {\n\n\t\t\t\t\t// not parallel\n\t\t\t\t\tif ( edgeDy < 0 ) {\n\n\t\t\t\t\t\tedgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;\n\t\t\t\t\t\tedgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) \t\tcontinue;\n\n\t\t\t\t\tif ( inPt.y === edgeLowPt.y ) {\n\n\t\t\t\t\t\tif ( inPt.x === edgeLowPt.x )\t\treturn\ttrue;\t\t// inPt is on contour ?\n\t\t\t\t\t\t// continue;\t\t\t\t// no intersection or edgeLowPt => doesn't count !!!\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tconst perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );\n\t\t\t\t\t\tif ( perpEdge === 0 )\t\t\t\treturn\ttrue;\t\t// inPt is on contour ?\n\t\t\t\t\t\tif ( perpEdge < 0 ) \t\t\t\tcontinue;\n\t\t\t\t\t\tinside = ! inside;\t\t// true intersection left of inPt\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// parallel or collinear\n\t\t\t\t\tif ( inPt.y !== edgeLowPt.y ) \t\tcontinue;\t\t\t// parallel\n\t\t\t\t\t// edge lies on the same horizontal line as inPt\n\t\t\t\t\tif ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||\n\t\t\t\t\t\t ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) )\t\treturn\ttrue;\t// inPt: Point on contour !\n\t\t\t\t\t// continue;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn\tinside;\n\n\t\t}\n\n\t\tconst isClockWise = ShapeUtils.isClockWise;\n\n\t\tconst subPaths = this.subPaths;\n\t\tif ( subPaths.length === 0 ) return [];\n\n\t\tlet solid, tmpPath, tmpShape;\n\t\tconst shapes = [];\n\n\t\tif ( subPaths.length === 1 ) {\n\n\t\t\ttmpPath = subPaths[ 0 ];\n\t\t\ttmpShape = new Shape();\n\t\t\ttmpShape.curves = tmpPath.curves;\n\t\t\tshapes.push( tmpShape );\n\t\t\treturn shapes;\n\n\t\t}\n\n\t\tlet holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );\n\t\tholesFirst = isCCW ? ! holesFirst : holesFirst;\n\n\t\t// console.log(\"Holes first\", holesFirst);\n\n\t\tconst betterShapeHoles = [];\n\t\tconst newShapes = [];\n\t\tlet newShapeHoles = [];\n\t\tlet mainIdx = 0;\n\t\tlet tmpPoints;\n\n\t\tnewShapes[ mainIdx ] = undefined;\n\t\tnewShapeHoles[ mainIdx ] = [];\n\n\t\tfor ( let i = 0, l = subPaths.length; i < l; i ++ ) {\n\n\t\t\ttmpPath = subPaths[ i ];\n\t\t\ttmpPoints = tmpPath.getPoints();\n\t\t\tsolid = isClockWise( tmpPoints );\n\t\t\tsolid = isCCW ? ! solid : solid;\n\n\t\t\tif ( solid ) {\n\n\t\t\t\tif ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) )\tmainIdx ++;\n\n\t\t\t\tnewShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };\n\t\t\t\tnewShapes[ mainIdx ].s.curves = tmpPath.curves;\n\n\t\t\t\tif ( holesFirst )\tmainIdx ++;\n\t\t\t\tnewShapeHoles[ mainIdx ] = [];\n\n\t\t\t\t//console.log('cw', i);\n\n\t\t\t} else {\n\n\t\t\t\tnewShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );\n\n\t\t\t\t//console.log('ccw', i);\n\n\t\t\t}\n\n\t\t}\n\n\t\t// only Holes? -> probably all Shapes with wrong orientation\n\t\tif ( ! newShapes[ 0 ] )\treturn\ttoShapesNoHoles( subPaths );\n\n\n\t\tif ( newShapes.length > 1 ) {\n\n\t\t\tlet ambiguous = false;\n\t\t\tlet toChange = 0;\n\n\t\t\tfor ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {\n\n\t\t\t\tbetterShapeHoles[ sIdx ] = [];\n\n\t\t\t}\n\n\t\t\tfor ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {\n\n\t\t\t\tconst sho = newShapeHoles[ sIdx ];\n\n\t\t\t\tfor ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {\n\n\t\t\t\t\tconst ho = sho[ hIdx ];\n\t\t\t\t\tlet hole_unassigned = true;\n\n\t\t\t\t\tfor ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {\n\n\t\t\t\t\t\tif ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {\n\n\t\t\t\t\t\t\tif ( sIdx !== s2Idx )\ttoChange ++;\n\n\t\t\t\t\t\t\tif ( hole_unassigned ) {\n\n\t\t\t\t\t\t\t\thole_unassigned = false;\n\t\t\t\t\t\t\t\tbetterShapeHoles[ s2Idx ].push( ho );\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tambiguous = true;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( hole_unassigned ) {\n\n\t\t\t\t\t\tbetterShapeHoles[ sIdx ].push( ho );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( toChange > 0 && ambiguous === false ) {\n\n\t\t\t\tnewShapeHoles = betterShapeHoles;\n\n\t\t\t}\n\n\t\t}\n\n\t\tlet tmpHoles;\n\n\t\tfor ( let i = 0, il = newShapes.length; i < il; i ++ ) {\n\n\t\t\ttmpShape = newShapes[ i ].s;\n\t\t\tshapes.push( tmpShape );\n\t\t\ttmpHoles = newShapeHoles[ i ];\n\n\t\t\tfor ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {\n\n\t\t\t\ttmpShape.holes.push( tmpHoles[ j ].h );\n\n\t\t\t}\n\n\t\t}\n\n\t\t//console.log(\"shape\", shapes);\n\n\t\treturn shapes;\n\n\t}\n\n}\n\nclass BoxBufferGeometry extends BoxGeometry { // @deprecated, r144\n\n\tconstructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {\n\n\t\tconsole.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );\n\t\tsuper( width, height, depth, widthSegments, heightSegments, depthSegments );\n\n\n\t}\n\n}\n\nclass CapsuleBufferGeometry extends CapsuleGeometry { // @deprecated, r144\n\n\tconstructor( radius, length, capSegments, radialSegments ) {\n\n\t\tconsole.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );\n\t\tsuper( radius, length, capSegments, radialSegments );\n\n\t}\n\n}\n\nclass CircleBufferGeometry extends CircleGeometry { // @deprecated, r144\n\n\tconstructor( radius, segments, thetaStart, thetaLength ) {\n\n\t\tconsole.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );\n\t\tsuper( radius, segments, thetaStart, thetaLength );\n\n\t}\n\n}\n\nclass ConeBufferGeometry extends ConeGeometry { // @deprecated, r144\n\n\tconstructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {\n\n\t\tconsole.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );\n\t\tsuper( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );\n\n\t}\n\n}\n\nclass CylinderBufferGeometry extends CylinderGeometry { // @deprecated, r144\n\n\tconstructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {\n\n\t\tconsole.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );\n\t\tsuper( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );\n\n\t}\n\n}\n\nclass DodecahedronBufferGeometry extends DodecahedronGeometry { // @deprecated, r144\n\n\tconstructor( radius, detail ) {\n\n\t\tconsole.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );\n\t\tsuper( radius, detail );\n\n\t}\n\n}\n\nclass ExtrudeBufferGeometry extends ExtrudeGeometry { // @deprecated, r144\n\n\tconstructor( shapes, options ) {\n\n\t\tconsole.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );\n\t\tsuper( shapes, options );\n\n\t}\n\n}\n\nclass IcosahedronBufferGeometry extends IcosahedronGeometry { // @deprecated, r144\n\n\tconstructor( radius, detail ) {\n\n\t\tconsole.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );\n\t\tsuper( radius, detail );\n\n\t}\n\n}\n\nclass LatheBufferGeometry extends LatheGeometry { // @deprecated, r144\n\n\tconstructor( points, segments, phiStart, phiLength ) {\n\n\t\tconsole.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );\n\t\tsuper( points, segments, phiStart, phiLength );\n\n\t}\n\n}\n\nclass OctahedronBufferGeometry extends OctahedronGeometry { // @deprecated, r144\n\n\tconstructor( radius, detail ) {\n\n\t\tconsole.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );\n\t\tsuper( radius, detail );\n\n\t}\n\n}\n\nclass PlaneBufferGeometry extends PlaneGeometry { // @deprecated, r144\n\n\tconstructor( width, height, widthSegments, heightSegments ) {\n\n\t\tconsole.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );\n\t\tsuper( width, height, widthSegments, heightSegments );\n\n\t}\n\n}\n\nclass PolyhedronBufferGeometry extends PolyhedronGeometry { // @deprecated, r144\n\n\tconstructor( vertices, indices, radius, detail ) {\n\n\t\tconsole.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );\n\t\tsuper( vertices, indices, radius, detail );\n\n\t}\n\n}\n\nclass RingBufferGeometry extends RingGeometry { // @deprecated, r144\n\n\tconstructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {\n\n\t\tconsole.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );\n\t\tsuper( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );\n\n\t}\n\n}\n\nclass ShapeBufferGeometry extends ShapeGeometry { // @deprecated, r144\n\n\tconstructor( shapes, curveSegments ) {\n\n\t\tconsole.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );\n\t\tsuper( shapes, curveSegments );\n\n\t}\n\n}\n\nclass SphereBufferGeometry extends SphereGeometry { // @deprecated, r144\n\n\tconstructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {\n\n\t\tconsole.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );\n\t\tsuper( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );\n\n\t}\n\n}\n\nclass TetrahedronBufferGeometry extends TetrahedronGeometry { // @deprecated, r144\n\n\tconstructor( radius, detail ) {\n\n\t\tconsole.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );\n\t\tsuper( radius, detail );\n\n\t}\n\n}\n\nclass TorusBufferGeometry extends TorusGeometry { // @deprecated, r144\n\n\tconstructor( radius, tube, radialSegments, tubularSegments, arc ) {\n\n\t\tconsole.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );\n\t\tsuper( radius, tube, radialSegments, tubularSegments, arc );\n\n\t}\n\n}\n\nclass TorusKnotBufferGeometry extends TorusKnotGeometry { // @deprecated, r144\n\n\tconstructor( radius, tube, tubularSegments, radialSegments, p, q ) {\n\n\t\tconsole.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );\n\t\tsuper( radius, tube, tubularSegments, radialSegments, p, q );\n\n\t}\n\n}\n\nclass TubeBufferGeometry extends TubeGeometry { // @deprecated, r144\n\n\tconstructor( path, tubularSegments, radius, radialSegments, closed ) {\n\n\t\tconsole.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );\n\t\tsuper( path, tubularSegments, radius, radialSegments, closed );\n\n\t}\n\n}\n\nif ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {\n\n\t__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {\n\t\trevision: REVISION,\n\t} } ) );\n\n}\n\nif ( typeof window !== 'undefined' ) {\n\n\tif ( window.__THREE__ ) {\n\n\t\tconsole.warn( 'WARNING: Multiple instances of Three.js being imported.' );\n\n\t} else {\n\n\t\twindow.__THREE__ = REVISION;\n\n\t}\n\n}\n\n\n\n\n//# sourceURL=webpack://MaterialXView/./node_modules/three/build/three.module.js?"); + +/***/ }), + +/***/ "./node_modules/three/examples/jsm/controls/OrbitControls.js": +/*!*******************************************************************!*\ + !*** ./node_modules/three/examples/jsm/controls/OrbitControls.js ***! + \*******************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ OrbitControls: () => (/* binding */ OrbitControls)\n/* harmony export */ });\n/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! three */ \"./node_modules/three/build/three.module.js\");\n\n\n// OrbitControls performs orbiting, dollying (zooming), and panning.\n// Unlike TrackballControls, it maintains the \"up\" direction object.up (+Y by default).\n//\n// Orbit - left mouse / touch: one-finger move\n// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish\n// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move\n\nconst _changeEvent = { type: 'change' };\nconst _startEvent = { type: 'start' };\nconst _endEvent = { type: 'end' };\n\nclass OrbitControls extends three__WEBPACK_IMPORTED_MODULE_0__.EventDispatcher {\n\n\tconstructor( object, domElement ) {\n\n\t\tsuper();\n\n\t\tthis.object = object;\n\t\tthis.domElement = domElement;\n\t\tthis.domElement.style.touchAction = 'none'; // disable touch scroll\n\n\t\t// Set to false to disable this control\n\t\tthis.enabled = true;\n\n\t\t// \"target\" sets the location of focus, where the object orbits around\n\t\tthis.target = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\n\t\t// How far you can dolly in and out ( PerspectiveCamera only )\n\t\tthis.minDistance = 0;\n\t\tthis.maxDistance = Infinity;\n\n\t\t// How far you can zoom in and out ( OrthographicCamera only )\n\t\tthis.minZoom = 0;\n\t\tthis.maxZoom = Infinity;\n\n\t\t// How far you can orbit vertically, upper and lower limits.\n\t\t// Range is 0 to Math.PI radians.\n\t\tthis.minPolarAngle = 0; // radians\n\t\tthis.maxPolarAngle = Math.PI; // radians\n\n\t\t// How far you can orbit horizontally, upper and lower limits.\n\t\t// If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )\n\t\tthis.minAzimuthAngle = - Infinity; // radians\n\t\tthis.maxAzimuthAngle = Infinity; // radians\n\n\t\t// Set to true to enable damping (inertia)\n\t\t// If damping is enabled, you must call controls.update() in your animation loop\n\t\tthis.enableDamping = false;\n\t\tthis.dampingFactor = 0.05;\n\n\t\t// This option actually enables dollying in and out; left as \"zoom\" for backwards compatibility.\n\t\t// Set to false to disable zooming\n\t\tthis.enableZoom = true;\n\t\tthis.zoomSpeed = 1.0;\n\n\t\t// Set to false to disable rotating\n\t\tthis.enableRotate = true;\n\t\tthis.rotateSpeed = 1.0;\n\n\t\t// Set to false to disable panning\n\t\tthis.enablePan = true;\n\t\tthis.panSpeed = 1.0;\n\t\tthis.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up\n\t\tthis.keyPanSpeed = 7.0;\t// pixels moved per arrow key push\n\n\t\t// Set to true to automatically rotate around the target\n\t\t// If auto-rotate is enabled, you must call controls.update() in your animation loop\n\t\tthis.autoRotate = false;\n\t\tthis.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60\n\n\t\t// The four arrow keys\n\t\tthis.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' };\n\n\t\t// Mouse buttons\n\t\tthis.mouseButtons = { LEFT: three__WEBPACK_IMPORTED_MODULE_0__.MOUSE.ROTATE, MIDDLE: three__WEBPACK_IMPORTED_MODULE_0__.MOUSE.DOLLY, RIGHT: three__WEBPACK_IMPORTED_MODULE_0__.MOUSE.PAN };\n\n\t\t// Touch fingers\n\t\tthis.touches = { ONE: three__WEBPACK_IMPORTED_MODULE_0__.TOUCH.ROTATE, TWO: three__WEBPACK_IMPORTED_MODULE_0__.TOUCH.DOLLY_PAN };\n\n\t\t// for reset\n\t\tthis.target0 = this.target.clone();\n\t\tthis.position0 = this.object.position.clone();\n\t\tthis.zoom0 = this.object.zoom;\n\n\t\t// the target DOM element for key events\n\t\tthis._domElementKeyEvents = null;\n\n\t\t//\n\t\t// public methods\n\t\t//\n\n\t\tthis.getPolarAngle = function () {\n\n\t\t\treturn spherical.phi;\n\n\t\t};\n\n\t\tthis.getAzimuthalAngle = function () {\n\n\t\t\treturn spherical.theta;\n\n\t\t};\n\n\t\tthis.getDistance = function () {\n\n\t\t\treturn this.object.position.distanceTo( this.target );\n\n\t\t};\n\n\t\tthis.listenToKeyEvents = function ( domElement ) {\n\n\t\t\tdomElement.addEventListener( 'keydown', onKeyDown );\n\t\t\tthis._domElementKeyEvents = domElement;\n\n\t\t};\n\n\t\tthis.stopListenToKeyEvents = function () {\n\n\t\t\tthis._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );\n\t\t\tthis._domElementKeyEvents = null;\n\n\t\t};\n\n\t\tthis.saveState = function () {\n\n\t\t\tscope.target0.copy( scope.target );\n\t\t\tscope.position0.copy( scope.object.position );\n\t\t\tscope.zoom0 = scope.object.zoom;\n\n\t\t};\n\n\t\tthis.reset = function () {\n\n\t\t\tscope.target.copy( scope.target0 );\n\t\t\tscope.object.position.copy( scope.position0 );\n\t\t\tscope.object.zoom = scope.zoom0;\n\n\t\t\tscope.object.updateProjectionMatrix();\n\t\t\tscope.dispatchEvent( _changeEvent );\n\n\t\t\tscope.update();\n\n\t\t\tstate = STATE.NONE;\n\n\t\t};\n\n\t\t// this method is exposed, but perhaps it would be better if we can make it private...\n\t\tthis.update = function () {\n\n\t\t\tconst offset = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\n\t\t\t// so camera.up is the orbit axis\n\t\t\tconst quat = new three__WEBPACK_IMPORTED_MODULE_0__.Quaternion().setFromUnitVectors( object.up, new three__WEBPACK_IMPORTED_MODULE_0__.Vector3( 0, 1, 0 ) );\n\t\t\tconst quatInverse = quat.clone().invert();\n\n\t\t\tconst lastPosition = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\t\t\tconst lastQuaternion = new three__WEBPACK_IMPORTED_MODULE_0__.Quaternion();\n\n\t\t\tconst twoPI = 2 * Math.PI;\n\n\t\t\treturn function update() {\n\n\t\t\t\tconst position = scope.object.position;\n\n\t\t\t\toffset.copy( position ).sub( scope.target );\n\n\t\t\t\t// rotate offset to \"y-axis-is-up\" space\n\t\t\t\toffset.applyQuaternion( quat );\n\n\t\t\t\t// angle from z-axis around y-axis\n\t\t\t\tspherical.setFromVector3( offset );\n\n\t\t\t\tif ( scope.autoRotate && state === STATE.NONE ) {\n\n\t\t\t\t\trotateLeft( getAutoRotationAngle() );\n\n\t\t\t\t}\n\n\t\t\t\tif ( scope.enableDamping ) {\n\n\t\t\t\t\tspherical.theta += sphericalDelta.theta * scope.dampingFactor;\n\t\t\t\t\tspherical.phi += sphericalDelta.phi * scope.dampingFactor;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tspherical.theta += sphericalDelta.theta;\n\t\t\t\t\tspherical.phi += sphericalDelta.phi;\n\n\t\t\t\t}\n\n\t\t\t\t// restrict theta to be between desired limits\n\n\t\t\t\tlet min = scope.minAzimuthAngle;\n\t\t\t\tlet max = scope.maxAzimuthAngle;\n\n\t\t\t\tif ( isFinite( min ) && isFinite( max ) ) {\n\n\t\t\t\t\tif ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI;\n\n\t\t\t\t\tif ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI;\n\n\t\t\t\t\tif ( min <= max ) {\n\n\t\t\t\t\t\tspherical.theta = Math.max( min, Math.min( max, spherical.theta ) );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tspherical.theta = ( spherical.theta > ( min + max ) / 2 ) ?\n\t\t\t\t\t\t\tMath.max( min, spherical.theta ) :\n\t\t\t\t\t\t\tMath.min( max, spherical.theta );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\t// restrict phi to be between desired limits\n\t\t\t\tspherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );\n\n\t\t\t\tspherical.makeSafe();\n\n\n\t\t\t\tspherical.radius *= scale;\n\n\t\t\t\t// restrict radius to be between desired limits\n\t\t\t\tspherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) );\n\n\t\t\t\t// move target to panned location\n\n\t\t\t\tif ( scope.enableDamping === true ) {\n\n\t\t\t\t\tscope.target.addScaledVector( panOffset, scope.dampingFactor );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tscope.target.add( panOffset );\n\n\t\t\t\t}\n\n\t\t\t\toffset.setFromSpherical( spherical );\n\n\t\t\t\t// rotate offset back to \"camera-up-vector-is-up\" space\n\t\t\t\toffset.applyQuaternion( quatInverse );\n\n\t\t\t\tposition.copy( scope.target ).add( offset );\n\n\t\t\t\tscope.object.lookAt( scope.target );\n\n\t\t\t\tif ( scope.enableDamping === true ) {\n\n\t\t\t\t\tsphericalDelta.theta *= ( 1 - scope.dampingFactor );\n\t\t\t\t\tsphericalDelta.phi *= ( 1 - scope.dampingFactor );\n\n\t\t\t\t\tpanOffset.multiplyScalar( 1 - scope.dampingFactor );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tsphericalDelta.set( 0, 0, 0 );\n\n\t\t\t\t\tpanOffset.set( 0, 0, 0 );\n\n\t\t\t\t}\n\n\t\t\t\tscale = 1;\n\n\t\t\t\t// update condition is:\n\t\t\t\t// min(camera displacement, camera rotation in radians)^2 > EPS\n\t\t\t\t// using small-angle approximation cos(x/2) = 1 - x^2 / 8\n\n\t\t\t\tif ( zoomChanged ||\n\t\t\t\t\tlastPosition.distanceToSquared( scope.object.position ) > EPS ||\n\t\t\t\t\t8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) {\n\n\t\t\t\t\tscope.dispatchEvent( _changeEvent );\n\n\t\t\t\t\tlastPosition.copy( scope.object.position );\n\t\t\t\t\tlastQuaternion.copy( scope.object.quaternion );\n\t\t\t\t\tzoomChanged = false;\n\n\t\t\t\t\treturn true;\n\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\n\t\t\t};\n\n\t\t}();\n\n\t\tthis.dispose = function () {\n\n\t\t\tscope.domElement.removeEventListener( 'contextmenu', onContextMenu );\n\n\t\t\tscope.domElement.removeEventListener( 'pointerdown', onPointerDown );\n\t\t\tscope.domElement.removeEventListener( 'pointercancel', onPointerUp );\n\t\t\tscope.domElement.removeEventListener( 'wheel', onMouseWheel );\n\n\t\t\tscope.domElement.removeEventListener( 'pointermove', onPointerMove );\n\t\t\tscope.domElement.removeEventListener( 'pointerup', onPointerUp );\n\n\n\t\t\tif ( scope._domElementKeyEvents !== null ) {\n\n\t\t\t\tscope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );\n\t\t\t\tscope._domElementKeyEvents = null;\n\n\t\t\t}\n\n\t\t\t//scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?\n\n\t\t};\n\n\t\t//\n\t\t// internals\n\t\t//\n\n\t\tconst scope = this;\n\n\t\tconst STATE = {\n\t\t\tNONE: - 1,\n\t\t\tROTATE: 0,\n\t\t\tDOLLY: 1,\n\t\t\tPAN: 2,\n\t\t\tTOUCH_ROTATE: 3,\n\t\t\tTOUCH_PAN: 4,\n\t\t\tTOUCH_DOLLY_PAN: 5,\n\t\t\tTOUCH_DOLLY_ROTATE: 6\n\t\t};\n\n\t\tlet state = STATE.NONE;\n\n\t\tconst EPS = 0.000001;\n\n\t\t// current position in spherical coordinates\n\t\tconst spherical = new three__WEBPACK_IMPORTED_MODULE_0__.Spherical();\n\t\tconst sphericalDelta = new three__WEBPACK_IMPORTED_MODULE_0__.Spherical();\n\n\t\tlet scale = 1;\n\t\tconst panOffset = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\t\tlet zoomChanged = false;\n\n\t\tconst rotateStart = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2();\n\t\tconst rotateEnd = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2();\n\t\tconst rotateDelta = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2();\n\n\t\tconst panStart = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2();\n\t\tconst panEnd = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2();\n\t\tconst panDelta = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2();\n\n\t\tconst dollyStart = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2();\n\t\tconst dollyEnd = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2();\n\t\tconst dollyDelta = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2();\n\n\t\tconst pointers = [];\n\t\tconst pointerPositions = {};\n\n\t\tfunction getAutoRotationAngle() {\n\n\t\t\treturn 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;\n\n\t\t}\n\n\t\tfunction getZoomScale() {\n\n\t\t\treturn Math.pow( 0.95, scope.zoomSpeed );\n\n\t\t}\n\n\t\tfunction rotateLeft( angle ) {\n\n\t\t\tsphericalDelta.theta -= angle;\n\n\t\t}\n\n\t\tfunction rotateUp( angle ) {\n\n\t\t\tsphericalDelta.phi -= angle;\n\n\t\t}\n\n\t\tconst panLeft = function () {\n\n\t\t\tconst v = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\n\t\t\treturn function panLeft( distance, objectMatrix ) {\n\n\t\t\t\tv.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix\n\t\t\t\tv.multiplyScalar( - distance );\n\n\t\t\t\tpanOffset.add( v );\n\n\t\t\t};\n\n\t\t}();\n\n\t\tconst panUp = function () {\n\n\t\t\tconst v = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\n\t\t\treturn function panUp( distance, objectMatrix ) {\n\n\t\t\t\tif ( scope.screenSpacePanning === true ) {\n\n\t\t\t\t\tv.setFromMatrixColumn( objectMatrix, 1 );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tv.setFromMatrixColumn( objectMatrix, 0 );\n\t\t\t\t\tv.crossVectors( scope.object.up, v );\n\n\t\t\t\t}\n\n\t\t\t\tv.multiplyScalar( distance );\n\n\t\t\t\tpanOffset.add( v );\n\n\t\t\t};\n\n\t\t}();\n\n\t\t// deltaX and deltaY are in pixels; right and down are positive\n\t\tconst pan = function () {\n\n\t\t\tconst offset = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\n\t\t\treturn function pan( deltaX, deltaY ) {\n\n\t\t\t\tconst element = scope.domElement;\n\n\t\t\t\tif ( scope.object.isPerspectiveCamera ) {\n\n\t\t\t\t\t// perspective\n\t\t\t\t\tconst position = scope.object.position;\n\t\t\t\t\toffset.copy( position ).sub( scope.target );\n\t\t\t\t\tlet targetDistance = offset.length();\n\n\t\t\t\t\t// half of the fov is center to top of screen\n\t\t\t\t\ttargetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );\n\n\t\t\t\t\t// we use only clientHeight here so aspect ratio does not distort speed\n\t\t\t\t\tpanLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );\n\t\t\t\t\tpanUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );\n\n\t\t\t\t} else if ( scope.object.isOrthographicCamera ) {\n\n\t\t\t\t\t// orthographic\n\t\t\t\t\tpanLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );\n\t\t\t\t\tpanUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// camera neither orthographic nor perspective\n\t\t\t\t\tconsole.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );\n\t\t\t\t\tscope.enablePan = false;\n\n\t\t\t\t}\n\n\t\t\t};\n\n\t\t}();\n\n\t\tfunction dollyOut( dollyScale ) {\n\n\t\t\tif ( scope.object.isPerspectiveCamera ) {\n\n\t\t\t\tscale /= dollyScale;\n\n\t\t\t} else if ( scope.object.isOrthographicCamera ) {\n\n\t\t\t\tscope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) );\n\t\t\t\tscope.object.updateProjectionMatrix();\n\t\t\t\tzoomChanged = true;\n\n\t\t\t} else {\n\n\t\t\t\tconsole.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );\n\t\t\t\tscope.enableZoom = false;\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction dollyIn( dollyScale ) {\n\n\t\t\tif ( scope.object.isPerspectiveCamera ) {\n\n\t\t\t\tscale *= dollyScale;\n\n\t\t\t} else if ( scope.object.isOrthographicCamera ) {\n\n\t\t\t\tscope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) );\n\t\t\t\tscope.object.updateProjectionMatrix();\n\t\t\t\tzoomChanged = true;\n\n\t\t\t} else {\n\n\t\t\t\tconsole.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );\n\t\t\t\tscope.enableZoom = false;\n\n\t\t\t}\n\n\t\t}\n\n\t\t//\n\t\t// event callbacks - update the object state\n\t\t//\n\n\t\tfunction handleMouseDownRotate( event ) {\n\n\t\t\trotateStart.set( event.clientX, event.clientY );\n\n\t\t}\n\n\t\tfunction handleMouseDownDolly( event ) {\n\n\t\t\tdollyStart.set( event.clientX, event.clientY );\n\n\t\t}\n\n\t\tfunction handleMouseDownPan( event ) {\n\n\t\t\tpanStart.set( event.clientX, event.clientY );\n\n\t\t}\n\n\t\tfunction handleMouseMoveRotate( event ) {\n\n\t\t\trotateEnd.set( event.clientX, event.clientY );\n\n\t\t\trotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );\n\n\t\t\tconst element = scope.domElement;\n\n\t\t\trotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height\n\n\t\t\trotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );\n\n\t\t\trotateStart.copy( rotateEnd );\n\n\t\t\tscope.update();\n\n\t\t}\n\n\t\tfunction handleMouseMoveDolly( event ) {\n\n\t\t\tdollyEnd.set( event.clientX, event.clientY );\n\n\t\t\tdollyDelta.subVectors( dollyEnd, dollyStart );\n\n\t\t\tif ( dollyDelta.y > 0 ) {\n\n\t\t\t\tdollyOut( getZoomScale() );\n\n\t\t\t} else if ( dollyDelta.y < 0 ) {\n\n\t\t\t\tdollyIn( getZoomScale() );\n\n\t\t\t}\n\n\t\t\tdollyStart.copy( dollyEnd );\n\n\t\t\tscope.update();\n\n\t\t}\n\n\t\tfunction handleMouseMovePan( event ) {\n\n\t\t\tpanEnd.set( event.clientX, event.clientY );\n\n\t\t\tpanDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );\n\n\t\t\tpan( panDelta.x, panDelta.y );\n\n\t\t\tpanStart.copy( panEnd );\n\n\t\t\tscope.update();\n\n\t\t}\n\n\t\tfunction handleMouseWheel( event ) {\n\n\t\t\tif ( event.deltaY < 0 ) {\n\n\t\t\t\tdollyIn( getZoomScale() );\n\n\t\t\t} else if ( event.deltaY > 0 ) {\n\n\t\t\t\tdollyOut( getZoomScale() );\n\n\t\t\t}\n\n\t\t\tscope.update();\n\n\t\t}\n\n\t\tfunction handleKeyDown( event ) {\n\n\t\t\tlet needsUpdate = false;\n\n\t\t\tswitch ( event.code ) {\n\n\t\t\t\tcase scope.keys.UP:\n\n\t\t\t\t\tif ( event.ctrlKey || event.metaKey || event.shiftKey ) {\n\n\t\t\t\t\t\trotateUp( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tpan( 0, scope.keyPanSpeed );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tneedsUpdate = true;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase scope.keys.BOTTOM:\n\n\t\t\t\t\tif ( event.ctrlKey || event.metaKey || event.shiftKey ) {\n\n\t\t\t\t\t\trotateUp( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tpan( 0, - scope.keyPanSpeed );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tneedsUpdate = true;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase scope.keys.LEFT:\n\n\t\t\t\t\tif ( event.ctrlKey || event.metaKey || event.shiftKey ) {\n\n\t\t\t\t\t\trotateLeft( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tpan( scope.keyPanSpeed, 0 );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tneedsUpdate = true;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase scope.keys.RIGHT:\n\n\t\t\t\t\tif ( event.ctrlKey || event.metaKey || event.shiftKey ) {\n\n\t\t\t\t\t\trotateLeft( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tpan( - scope.keyPanSpeed, 0 );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tneedsUpdate = true;\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\tif ( needsUpdate ) {\n\n\t\t\t\t// prevent the browser from scrolling on cursor keys\n\t\t\t\tevent.preventDefault();\n\n\t\t\t\tscope.update();\n\n\t\t\t}\n\n\n\t\t}\n\n\t\tfunction handleTouchStartRotate() {\n\n\t\t\tif ( pointers.length === 1 ) {\n\n\t\t\t\trotateStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY );\n\n\t\t\t} else {\n\n\t\t\t\tconst x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX );\n\t\t\t\tconst y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY );\n\n\t\t\t\trotateStart.set( x, y );\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction handleTouchStartPan() {\n\n\t\t\tif ( pointers.length === 1 ) {\n\n\t\t\t\tpanStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY );\n\n\t\t\t} else {\n\n\t\t\t\tconst x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX );\n\t\t\t\tconst y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY );\n\n\t\t\t\tpanStart.set( x, y );\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction handleTouchStartDolly() {\n\n\t\t\tconst dx = pointers[ 0 ].pageX - pointers[ 1 ].pageX;\n\t\t\tconst dy = pointers[ 0 ].pageY - pointers[ 1 ].pageY;\n\n\t\t\tconst distance = Math.sqrt( dx * dx + dy * dy );\n\n\t\t\tdollyStart.set( 0, distance );\n\n\t\t}\n\n\t\tfunction handleTouchStartDollyPan() {\n\n\t\t\tif ( scope.enableZoom ) handleTouchStartDolly();\n\n\t\t\tif ( scope.enablePan ) handleTouchStartPan();\n\n\t\t}\n\n\t\tfunction handleTouchStartDollyRotate() {\n\n\t\t\tif ( scope.enableZoom ) handleTouchStartDolly();\n\n\t\t\tif ( scope.enableRotate ) handleTouchStartRotate();\n\n\t\t}\n\n\t\tfunction handleTouchMoveRotate( event ) {\n\n\t\t\tif ( pointers.length == 1 ) {\n\n\t\t\t\trotateEnd.set( event.pageX, event.pageY );\n\n\t\t\t} else {\n\n\t\t\t\tconst position = getSecondPointerPosition( event );\n\n\t\t\t\tconst x = 0.5 * ( event.pageX + position.x );\n\t\t\t\tconst y = 0.5 * ( event.pageY + position.y );\n\n\t\t\t\trotateEnd.set( x, y );\n\n\t\t\t}\n\n\t\t\trotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );\n\n\t\t\tconst element = scope.domElement;\n\n\t\t\trotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height\n\n\t\t\trotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );\n\n\t\t\trotateStart.copy( rotateEnd );\n\n\t\t}\n\n\t\tfunction handleTouchMovePan( event ) {\n\n\t\t\tif ( pointers.length === 1 ) {\n\n\t\t\t\tpanEnd.set( event.pageX, event.pageY );\n\n\t\t\t} else {\n\n\t\t\t\tconst position = getSecondPointerPosition( event );\n\n\t\t\t\tconst x = 0.5 * ( event.pageX + position.x );\n\t\t\t\tconst y = 0.5 * ( event.pageY + position.y );\n\n\t\t\t\tpanEnd.set( x, y );\n\n\t\t\t}\n\n\t\t\tpanDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );\n\n\t\t\tpan( panDelta.x, panDelta.y );\n\n\t\t\tpanStart.copy( panEnd );\n\n\t\t}\n\n\t\tfunction handleTouchMoveDolly( event ) {\n\n\t\t\tconst position = getSecondPointerPosition( event );\n\n\t\t\tconst dx = event.pageX - position.x;\n\t\t\tconst dy = event.pageY - position.y;\n\n\t\t\tconst distance = Math.sqrt( dx * dx + dy * dy );\n\n\t\t\tdollyEnd.set( 0, distance );\n\n\t\t\tdollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );\n\n\t\t\tdollyOut( dollyDelta.y );\n\n\t\t\tdollyStart.copy( dollyEnd );\n\n\t\t}\n\n\t\tfunction handleTouchMoveDollyPan( event ) {\n\n\t\t\tif ( scope.enableZoom ) handleTouchMoveDolly( event );\n\n\t\t\tif ( scope.enablePan ) handleTouchMovePan( event );\n\n\t\t}\n\n\t\tfunction handleTouchMoveDollyRotate( event ) {\n\n\t\t\tif ( scope.enableZoom ) handleTouchMoveDolly( event );\n\n\t\t\tif ( scope.enableRotate ) handleTouchMoveRotate( event );\n\n\t\t}\n\n\t\t//\n\t\t// event handlers - FSM: listen for events and reset state\n\t\t//\n\n\t\tfunction onPointerDown( event ) {\n\n\t\t\tif ( scope.enabled === false ) return;\n\n\t\t\tif ( pointers.length === 0 ) {\n\n\t\t\t\tscope.domElement.setPointerCapture( event.pointerId );\n\n\t\t\t\tscope.domElement.addEventListener( 'pointermove', onPointerMove );\n\t\t\t\tscope.domElement.addEventListener( 'pointerup', onPointerUp );\n\n\t\t\t}\n\n\t\t\t//\n\n\t\t\taddPointer( event );\n\n\t\t\tif ( event.pointerType === 'touch' ) {\n\n\t\t\t\tonTouchStart( event );\n\n\t\t\t} else {\n\n\t\t\t\tonMouseDown( event );\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction onPointerMove( event ) {\n\n\t\t\tif ( scope.enabled === false ) return;\n\n\t\t\tif ( event.pointerType === 'touch' ) {\n\n\t\t\t\tonTouchMove( event );\n\n\t\t\t} else {\n\n\t\t\t\tonMouseMove( event );\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction onPointerUp( event ) {\n\n\t\t\tremovePointer( event );\n\n\t\t\tif ( pointers.length === 0 ) {\n\n\t\t\t\tscope.domElement.releasePointerCapture( event.pointerId );\n\n\t\t\t\tscope.domElement.removeEventListener( 'pointermove', onPointerMove );\n\t\t\t\tscope.domElement.removeEventListener( 'pointerup', onPointerUp );\n\n\t\t\t}\n\n\t\t\tscope.dispatchEvent( _endEvent );\n\n\t\t\tstate = STATE.NONE;\n\n\t\t}\n\n\t\tfunction onMouseDown( event ) {\n\n\t\t\tlet mouseAction;\n\n\t\t\tswitch ( event.button ) {\n\n\t\t\t\tcase 0:\n\n\t\t\t\t\tmouseAction = scope.mouseButtons.LEFT;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 1:\n\n\t\t\t\t\tmouseAction = scope.mouseButtons.MIDDLE;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 2:\n\n\t\t\t\t\tmouseAction = scope.mouseButtons.RIGHT;\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\n\t\t\t\t\tmouseAction = - 1;\n\n\t\t\t}\n\n\t\t\tswitch ( mouseAction ) {\n\n\t\t\t\tcase three__WEBPACK_IMPORTED_MODULE_0__.MOUSE.DOLLY:\n\n\t\t\t\t\tif ( scope.enableZoom === false ) return;\n\n\t\t\t\t\thandleMouseDownDolly( event );\n\n\t\t\t\t\tstate = STATE.DOLLY;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase three__WEBPACK_IMPORTED_MODULE_0__.MOUSE.ROTATE:\n\n\t\t\t\t\tif ( event.ctrlKey || event.metaKey || event.shiftKey ) {\n\n\t\t\t\t\t\tif ( scope.enablePan === false ) return;\n\n\t\t\t\t\t\thandleMouseDownPan( event );\n\n\t\t\t\t\t\tstate = STATE.PAN;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tif ( scope.enableRotate === false ) return;\n\n\t\t\t\t\t\thandleMouseDownRotate( event );\n\n\t\t\t\t\t\tstate = STATE.ROTATE;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase three__WEBPACK_IMPORTED_MODULE_0__.MOUSE.PAN:\n\n\t\t\t\t\tif ( event.ctrlKey || event.metaKey || event.shiftKey ) {\n\n\t\t\t\t\t\tif ( scope.enableRotate === false ) return;\n\n\t\t\t\t\t\thandleMouseDownRotate( event );\n\n\t\t\t\t\t\tstate = STATE.ROTATE;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tif ( scope.enablePan === false ) return;\n\n\t\t\t\t\t\thandleMouseDownPan( event );\n\n\t\t\t\t\t\tstate = STATE.PAN;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\n\t\t\t\t\tstate = STATE.NONE;\n\n\t\t\t}\n\n\t\t\tif ( state !== STATE.NONE ) {\n\n\t\t\t\tscope.dispatchEvent( _startEvent );\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction onMouseMove( event ) {\n\n\t\t\tswitch ( state ) {\n\n\t\t\t\tcase STATE.ROTATE:\n\n\t\t\t\t\tif ( scope.enableRotate === false ) return;\n\n\t\t\t\t\thandleMouseMoveRotate( event );\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase STATE.DOLLY:\n\n\t\t\t\t\tif ( scope.enableZoom === false ) return;\n\n\t\t\t\t\thandleMouseMoveDolly( event );\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase STATE.PAN:\n\n\t\t\t\t\tif ( scope.enablePan === false ) return;\n\n\t\t\t\t\thandleMouseMovePan( event );\n\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction onMouseWheel( event ) {\n\n\t\t\tif ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return;\n\n\t\t\tevent.preventDefault();\n\n\t\t\tscope.dispatchEvent( _startEvent );\n\n\t\t\thandleMouseWheel( event );\n\n\t\t\tscope.dispatchEvent( _endEvent );\n\n\t\t}\n\n\t\tfunction onKeyDown( event ) {\n\n\t\t\tif ( scope.enabled === false || scope.enablePan === false ) return;\n\n\t\t\thandleKeyDown( event );\n\n\t\t}\n\n\t\tfunction onTouchStart( event ) {\n\n\t\t\ttrackPointer( event );\n\n\t\t\tswitch ( pointers.length ) {\n\n\t\t\t\tcase 1:\n\n\t\t\t\t\tswitch ( scope.touches.ONE ) {\n\n\t\t\t\t\t\tcase three__WEBPACK_IMPORTED_MODULE_0__.TOUCH.ROTATE:\n\n\t\t\t\t\t\t\tif ( scope.enableRotate === false ) return;\n\n\t\t\t\t\t\t\thandleTouchStartRotate();\n\n\t\t\t\t\t\t\tstate = STATE.TOUCH_ROTATE;\n\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase three__WEBPACK_IMPORTED_MODULE_0__.TOUCH.PAN:\n\n\t\t\t\t\t\t\tif ( scope.enablePan === false ) return;\n\n\t\t\t\t\t\t\thandleTouchStartPan();\n\n\t\t\t\t\t\t\tstate = STATE.TOUCH_PAN;\n\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tdefault:\n\n\t\t\t\t\t\t\tstate = STATE.NONE;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 2:\n\n\t\t\t\t\tswitch ( scope.touches.TWO ) {\n\n\t\t\t\t\t\tcase three__WEBPACK_IMPORTED_MODULE_0__.TOUCH.DOLLY_PAN:\n\n\t\t\t\t\t\t\tif ( scope.enableZoom === false && scope.enablePan === false ) return;\n\n\t\t\t\t\t\t\thandleTouchStartDollyPan();\n\n\t\t\t\t\t\t\tstate = STATE.TOUCH_DOLLY_PAN;\n\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase three__WEBPACK_IMPORTED_MODULE_0__.TOUCH.DOLLY_ROTATE:\n\n\t\t\t\t\t\t\tif ( scope.enableZoom === false && scope.enableRotate === false ) return;\n\n\t\t\t\t\t\t\thandleTouchStartDollyRotate();\n\n\t\t\t\t\t\t\tstate = STATE.TOUCH_DOLLY_ROTATE;\n\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tdefault:\n\n\t\t\t\t\t\t\tstate = STATE.NONE;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\n\t\t\t\t\tstate = STATE.NONE;\n\n\t\t\t}\n\n\t\t\tif ( state !== STATE.NONE ) {\n\n\t\t\t\tscope.dispatchEvent( _startEvent );\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction onTouchMove( event ) {\n\n\t\t\ttrackPointer( event );\n\n\t\t\tswitch ( state ) {\n\n\t\t\t\tcase STATE.TOUCH_ROTATE:\n\n\t\t\t\t\tif ( scope.enableRotate === false ) return;\n\n\t\t\t\t\thandleTouchMoveRotate( event );\n\n\t\t\t\t\tscope.update();\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase STATE.TOUCH_PAN:\n\n\t\t\t\t\tif ( scope.enablePan === false ) return;\n\n\t\t\t\t\thandleTouchMovePan( event );\n\n\t\t\t\t\tscope.update();\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase STATE.TOUCH_DOLLY_PAN:\n\n\t\t\t\t\tif ( scope.enableZoom === false && scope.enablePan === false ) return;\n\n\t\t\t\t\thandleTouchMoveDollyPan( event );\n\n\t\t\t\t\tscope.update();\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase STATE.TOUCH_DOLLY_ROTATE:\n\n\t\t\t\t\tif ( scope.enableZoom === false && scope.enableRotate === false ) return;\n\n\t\t\t\t\thandleTouchMoveDollyRotate( event );\n\n\t\t\t\t\tscope.update();\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\n\t\t\t\t\tstate = STATE.NONE;\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction onContextMenu( event ) {\n\n\t\t\tif ( scope.enabled === false ) return;\n\n\t\t\tevent.preventDefault();\n\n\t\t}\n\n\t\tfunction addPointer( event ) {\n\n\t\t\tpointers.push( event );\n\n\t\t}\n\n\t\tfunction removePointer( event ) {\n\n\t\t\tdelete pointerPositions[ event.pointerId ];\n\n\t\t\tfor ( let i = 0; i < pointers.length; i ++ ) {\n\n\t\t\t\tif ( pointers[ i ].pointerId == event.pointerId ) {\n\n\t\t\t\t\tpointers.splice( i, 1 );\n\t\t\t\t\treturn;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction trackPointer( event ) {\n\n\t\t\tlet position = pointerPositions[ event.pointerId ];\n\n\t\t\tif ( position === undefined ) {\n\n\t\t\t\tposition = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2();\n\t\t\t\tpointerPositions[ event.pointerId ] = position;\n\n\t\t\t}\n\n\t\t\tposition.set( event.pageX, event.pageY );\n\n\t\t}\n\n\t\tfunction getSecondPointerPosition( event ) {\n\n\t\t\tconst pointer = ( event.pointerId === pointers[ 0 ].pointerId ) ? pointers[ 1 ] : pointers[ 0 ];\n\n\t\t\treturn pointerPositions[ pointer.pointerId ];\n\n\t\t}\n\n\t\t//\n\n\t\tscope.domElement.addEventListener( 'contextmenu', onContextMenu );\n\n\t\tscope.domElement.addEventListener( 'pointerdown', onPointerDown );\n\t\tscope.domElement.addEventListener( 'pointercancel', onPointerUp );\n\t\tscope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } );\n\n\t\t// force an update at start\n\n\t\tthis.update();\n\n\t}\n\n}\n\n\n\n\n//# sourceURL=webpack://MaterialXView/./node_modules/three/examples/jsm/controls/OrbitControls.js?"); + +/***/ }), + +/***/ "./node_modules/three/examples/jsm/libs/fflate.module.js": +/*!***************************************************************!*\ + !*** ./node_modules/three/examples/jsm/libs/fflate.module.js ***! + \***************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AsyncCompress: () => (/* binding */ AsyncGzip),\n/* harmony export */ AsyncDecompress: () => (/* binding */ AsyncDecompress),\n/* harmony export */ AsyncDeflate: () => (/* binding */ AsyncDeflate),\n/* harmony export */ AsyncGunzip: () => (/* binding */ AsyncGunzip),\n/* harmony export */ AsyncGzip: () => (/* binding */ AsyncGzip),\n/* harmony export */ AsyncInflate: () => (/* binding */ AsyncInflate),\n/* harmony export */ AsyncUnzipInflate: () => (/* binding */ AsyncUnzipInflate),\n/* harmony export */ AsyncUnzlib: () => (/* binding */ AsyncUnzlib),\n/* harmony export */ AsyncZipDeflate: () => (/* binding */ AsyncZipDeflate),\n/* harmony export */ AsyncZlib: () => (/* binding */ AsyncZlib),\n/* harmony export */ Compress: () => (/* binding */ Gzip),\n/* harmony export */ DecodeUTF8: () => (/* binding */ DecodeUTF8),\n/* harmony export */ Decompress: () => (/* binding */ Decompress),\n/* harmony export */ Deflate: () => (/* binding */ Deflate),\n/* harmony export */ EncodeUTF8: () => (/* binding */ EncodeUTF8),\n/* harmony export */ Gunzip: () => (/* binding */ Gunzip),\n/* harmony export */ Gzip: () => (/* binding */ Gzip),\n/* harmony export */ Inflate: () => (/* binding */ Inflate),\n/* harmony export */ Unzip: () => (/* binding */ Unzip),\n/* harmony export */ UnzipInflate: () => (/* binding */ UnzipInflate),\n/* harmony export */ UnzipPassThrough: () => (/* binding */ UnzipPassThrough),\n/* harmony export */ Unzlib: () => (/* binding */ Unzlib),\n/* harmony export */ Zip: () => (/* binding */ Zip),\n/* harmony export */ ZipDeflate: () => (/* binding */ ZipDeflate),\n/* harmony export */ ZipPassThrough: () => (/* binding */ ZipPassThrough),\n/* harmony export */ Zlib: () => (/* binding */ Zlib),\n/* harmony export */ compress: () => (/* binding */ gzip),\n/* harmony export */ compressSync: () => (/* binding */ gzipSync),\n/* harmony export */ decompress: () => (/* binding */ decompress),\n/* harmony export */ decompressSync: () => (/* binding */ decompressSync),\n/* harmony export */ deflate: () => (/* binding */ deflate),\n/* harmony export */ deflateSync: () => (/* binding */ deflateSync),\n/* harmony export */ gunzip: () => (/* binding */ gunzip),\n/* harmony export */ gunzipSync: () => (/* binding */ gunzipSync),\n/* harmony export */ gzip: () => (/* binding */ gzip),\n/* harmony export */ gzipSync: () => (/* binding */ gzipSync),\n/* harmony export */ inflate: () => (/* binding */ inflate),\n/* harmony export */ inflateSync: () => (/* binding */ inflateSync),\n/* harmony export */ strFromU8: () => (/* binding */ strFromU8),\n/* harmony export */ strToU8: () => (/* binding */ strToU8),\n/* harmony export */ unzip: () => (/* binding */ unzip),\n/* harmony export */ unzipSync: () => (/* binding */ unzipSync),\n/* harmony export */ unzlib: () => (/* binding */ unzlib),\n/* harmony export */ unzlibSync: () => (/* binding */ unzlibSync),\n/* harmony export */ zip: () => (/* binding */ zip),\n/* harmony export */ zipSync: () => (/* binding */ zipSync),\n/* harmony export */ zlib: () => (/* binding */ zlib),\n/* harmony export */ zlibSync: () => (/* binding */ zlibSync)\n/* harmony export */ });\n/*!\nfflate - fast JavaScript compression/decompression\n\nLicensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE\nversion 0.6.9\n*/\n\n// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Some of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\nvar ch2 = {};\nvar durl = function (c) { return URL.createObjectURL(new Blob([c], { type: 'text/javascript' })); };\nvar cwk = function (u) { return new Worker(u); };\ntry {\n URL.revokeObjectURL(durl(''));\n}\ncatch (e) {\n // We're in Deno or a very old browser\n durl = function (c) { return 'data:application/javascript;charset=UTF-8,' + encodeURI(c); };\n // If Deno, this is necessary; if not, this changes nothing\n cwk = function (u) { return new Worker(u, { type: 'module' }); };\n}\nvar wk = (function (c, id, msg, transfer, cb) {\n var w = cwk(ch2[id] || (ch2[id] = durl(c)));\n w.onerror = function (e) { return cb(e.error, null); };\n w.onmessage = function (e) { return cb(null, e.data); };\n w.postMessage(msg, transfer);\n return w;\n});\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;\n// fixed length extra bits\nvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\n// see fleb note\nvar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n var b = new u16(31);\n for (var i = 0; i < 31; ++i) {\n b[i] = start += 1 << eb[i - 1];\n }\n // numbers here are at max 18 bits\n var r = new u32(b[30]);\n for (var i = 1; i < 30; ++i) {\n for (var j = b[i]; j < b[i + 1]; ++j) {\n r[j] = ((j - b[i]) << 5) | i;\n }\n }\n return [b, r];\n};\nvar _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n // reverse table algorithm from SO\n var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);\n x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);\n x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);\n rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n var s = cd.length;\n // index\n var i = 0;\n // u16 \"map\": index -> # of codes with bit length = index\n var l = new u16(mb);\n // length of cd must be 288 (total # of codes)\n for (; i < s; ++i)\n ++l[cd[i] - 1];\n // u16 \"map\": index -> minimum code for bit length = index\n var le = new u16(mb);\n for (i = 0; i < mb; ++i) {\n le[i] = (le[i - 1] + l[i - 1]) << 1;\n }\n var co;\n if (r) {\n // u16 \"map\": index -> number of actual bits, symbol for code\n co = new u16(1 << mb);\n // bits to remove for reverser\n var rvb = 15 - mb;\n for (i = 0; i < s; ++i) {\n // ignore 0 lengths\n if (cd[i]) {\n // num encoding both symbol and bits read\n var sv = (i << 4) | cd[i];\n // free bits\n var r_1 = mb - cd[i];\n // start value\n var v = le[cd[i] - 1]++ << r_1;\n // m is end value\n for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n // every 16 bit value starting with the code yields the same result\n co[rev[v] >>> rvb] = sv;\n }\n }\n }\n }\n else {\n co = new u16(s);\n for (i = 0; i < s; ++i) {\n if (cd[i]) {\n co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);\n }\n }\n }\n return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n var m = a[0];\n for (var i = 1; i < a.length; ++i) {\n if (a[i] > m)\n m = a[i];\n }\n return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p / 8) | 0) + (p & 7 && 1); };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n if (s == null || s < 0)\n s = 0;\n if (e == null || e > v.length)\n e = v.length;\n // can't use .constructor in case user-supplied\n var n = new (v instanceof u16 ? u16 : v instanceof u32 ? u32 : u8)(e - s);\n n.set(v.subarray(s, e));\n return n;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, buf, st) {\n // source length\n var sl = dat.length;\n if (!sl || (st && !st.l && sl < 5))\n return buf || new u8(0);\n // have to estimate size\n var noBuf = !buf || st;\n // no state\n var noSt = !st || st.i;\n if (!st)\n st = {};\n // Assumes roughly 33% compression ratio average\n if (!buf)\n buf = new u8(sl * 3);\n // ensure buffer can fit at least l elements\n var cbuf = function (l) {\n var bl = buf.length;\n // need to increase size to fit\n if (l > bl) {\n // Double or set to necessary, whichever is greater\n var nbuf = new u8(Math.max(bl * 2, l));\n nbuf.set(buf);\n buf = nbuf;\n }\n };\n // last chunk bitpos bytes\n var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n // total bits\n var tbts = sl * 8;\n do {\n if (!lm) {\n // BFINAL - this is only 1 when last chunk is next\n st.f = final = bits(dat, pos, 1);\n // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n var type = bits(dat, pos + 1, 3);\n pos += 3;\n if (!type) {\n // go to end of byte boundary\n var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n if (t > sl) {\n if (noSt)\n throw 'unexpected EOF';\n break;\n }\n // ensure size\n if (noBuf)\n cbuf(bt + l);\n // Copy over uncompressed data\n buf.set(dat.subarray(s, t), bt);\n // Get new bitpos, update byte count\n st.b = bt += l, st.p = pos = t * 8;\n continue;\n }\n else if (type == 1)\n lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n else if (type == 2) {\n // literal lengths\n var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n var tl = hLit + bits(dat, pos + 5, 31) + 1;\n pos += 14;\n // length+distance tree\n var ldt = new u8(tl);\n // code length tree\n var clt = new u8(19);\n for (var i = 0; i < hcLen; ++i) {\n // use index map to get real code\n clt[clim[i]] = bits(dat, pos + i * 3, 7);\n }\n pos += hcLen * 3;\n // code lengths bits\n var clb = max(clt), clbmsk = (1 << clb) - 1;\n // code lengths map\n var clm = hMap(clt, clb, 1);\n for (var i = 0; i < tl;) {\n var r = clm[bits(dat, pos, clbmsk)];\n // bits read\n pos += r & 15;\n // symbol\n var s = r >>> 4;\n // code length to copy\n if (s < 16) {\n ldt[i++] = s;\n }\n else {\n // copy count\n var c = 0, n = 0;\n if (s == 16)\n n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n else if (s == 17)\n n = 3 + bits(dat, pos, 7), pos += 3;\n else if (s == 18)\n n = 11 + bits(dat, pos, 127), pos += 7;\n while (n--)\n ldt[i++] = c;\n }\n }\n // length tree distance tree\n var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n // max length bits\n lbt = max(lt);\n // max dist bits\n dbt = max(dt);\n lm = hMap(lt, lbt, 1);\n dm = hMap(dt, dbt, 1);\n }\n else\n throw 'invalid block type';\n if (pos > tbts) {\n if (noSt)\n throw 'unexpected EOF';\n break;\n }\n }\n // Make sure the buffer can hold this + the largest possible addition\n // Maximum chunk size (practically, theoretically infinite) is 2^17;\n if (noBuf)\n cbuf(bt + 131072);\n var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n var lpos = pos;\n for (;; lpos = pos) {\n // bits read, code\n var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;\n pos += c & 15;\n if (pos > tbts) {\n if (noSt)\n throw 'unexpected EOF';\n break;\n }\n if (!c)\n throw 'invalid length/literal';\n if (sym < 256)\n buf[bt++] = sym;\n else if (sym == 256) {\n lpos = pos, lm = null;\n break;\n }\n else {\n var add = sym - 254;\n // no extra bits needed if less\n if (sym > 264) {\n // index\n var i = sym - 257, b = fleb[i];\n add = bits(dat, pos, (1 << b) - 1) + fl[i];\n pos += b;\n }\n // dist\n var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;\n if (!d)\n throw 'invalid distance';\n pos += d & 15;\n var dt = fd[dsym];\n if (dsym > 3) {\n var b = fdeb[dsym];\n dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;\n }\n if (pos > tbts) {\n if (noSt)\n throw 'unexpected EOF';\n break;\n }\n if (noBuf)\n cbuf(bt + 131072);\n var end = bt + add;\n for (; bt < end; bt += 4) {\n buf[bt] = buf[bt - dt];\n buf[bt + 1] = buf[bt + 1 - dt];\n buf[bt + 2] = buf[bt + 2 - dt];\n buf[bt + 3] = buf[bt + 3 - dt];\n }\n bt = end;\n }\n }\n st.l = lm, st.p = lpos, st.b = bt;\n if (lm)\n final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n } while (!final);\n return bt == buf.length ? buf : slc(buf, 0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n d[o + 2] |= v >>> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n // Need extra info to make a tree\n var t = [];\n for (var i = 0; i < d.length; ++i) {\n if (d[i])\n t.push({ s: i, f: d[i] });\n }\n var s = t.length;\n var t2 = t.slice();\n if (!s)\n return [et, 0];\n if (s == 1) {\n var v = new u8(t[0].s + 1);\n v[t[0].s] = 1;\n return [v, 1];\n }\n t.sort(function (a, b) { return a.f - b.f; });\n // after i2 reaches last ind, will be stopped\n // freq must be greater than largest possible number of symbols\n t.push({ s: -1, f: 25001 });\n var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n // efficient algorithm from UZIP.js\n // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n // symbols that combined have high freq, will start processing i2 (high-freq,\n // non-composite) symbols instead\n // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n while (i1 != s - 1) {\n l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n }\n var maxSym = t2[0].s;\n for (var i = 1; i < s; ++i) {\n if (t2[i].s > maxSym)\n maxSym = t2[i].s;\n }\n // code lengths\n var tr = new u16(maxSym + 1);\n // max bits in tree\n var mbt = ln(t[i1 - 1], tr, 0);\n if (mbt > mb) {\n // more algorithms from UZIP.js\n // TODO: find out how this code works (debt)\n // ind debt\n var i = 0, dt = 0;\n // left cost\n var lft = mbt - mb, cst = 1 << lft;\n t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n for (; i < s; ++i) {\n var i2_1 = t2[i].s;\n if (tr[i2_1] > mb) {\n dt += cst - (1 << (mbt - tr[i2_1]));\n tr[i2_1] = mb;\n }\n else\n break;\n }\n dt >>>= lft;\n while (dt > 0) {\n var i2_2 = t2[i].s;\n if (tr[i2_2] < mb)\n dt -= 1 << (mb - tr[i2_2]++ - 1);\n else\n ++i;\n }\n for (; i >= 0 && dt; --i) {\n var i2_3 = t2[i].s;\n if (tr[i2_3] == mb) {\n --tr[i2_3];\n ++dt;\n }\n }\n mbt = mb;\n }\n return [new u8(tr), mbt];\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n return n.s == -1\n ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n var s = c.length;\n // Note that the semicolon was intentional\n while (s && !c[--s])\n ;\n var cl = new u16(++s);\n // ind num streak\n var cli = 0, cln = c[0], cls = 1;\n var w = function (v) { cl[cli++] = v; };\n for (var i = 1; i <= s; ++i) {\n if (c[i] == cln && i != s)\n ++cls;\n else {\n if (!cln && cls > 2) {\n for (; cls > 138; cls -= 138)\n w(32754);\n if (cls > 2) {\n w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n cls = 0;\n }\n }\n else if (cls > 3) {\n w(cln), --cls;\n for (; cls > 6; cls -= 6)\n w(8304);\n if (cls > 2)\n w(((cls - 3) << 5) | 8208), cls = 0;\n }\n while (cls--)\n w(cln);\n cls = 1;\n cln = c[i];\n }\n }\n return [cl.subarray(0, cli), s];\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n var l = 0;\n for (var i = 0; i < cl.length; ++i)\n l += cf[i] * cl[i];\n return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n // no need to write 00 as type: TypedArray defaults to 0\n var s = dat.length;\n var o = shft(pos + 2);\n out[o] = s & 255;\n out[o + 1] = s >>> 8;\n out[o + 2] = out[o] ^ 255;\n out[o + 3] = out[o + 1] ^ 255;\n for (var i = 0; i < s; ++i)\n out[o + i + 4] = dat[i];\n return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n wbits(out, p++, final);\n ++lf[256];\n var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1];\n var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1];\n var _c = lc(dlt), lclt = _c[0], nlc = _c[1];\n var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];\n var lcfreq = new u16(19);\n for (var i = 0; i < lclt.length; ++i)\n lcfreq[lclt[i] & 31]++;\n for (var i = 0; i < lcdt.length; ++i)\n lcfreq[lcdt[i] & 31]++;\n var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];\n var nlcc = 19;\n for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n ;\n var flen = (bl + 5) << 3;\n var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);\n if (flen <= ftlen && flen <= dtlen)\n return wfblk(out, p, dat.subarray(bs, bs + bl));\n var lm, ll, dm, dl;\n wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n if (dtlen < ftlen) {\n lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n var llm = hMap(lct, mlcb, 0);\n wbits(out, p, nlc - 257);\n wbits(out, p + 5, ndc - 1);\n wbits(out, p + 10, nlcc - 4);\n p += 14;\n for (var i = 0; i < nlcc; ++i)\n wbits(out, p + 3 * i, lct[clim[i]]);\n p += 3 * nlcc;\n var lcts = [lclt, lcdt];\n for (var it = 0; it < 2; ++it) {\n var clct = lcts[it];\n for (var i = 0; i < clct.length; ++i) {\n var len = clct[i] & 31;\n wbits(out, p, llm[len]), p += lct[len];\n if (len > 15)\n wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12;\n }\n }\n }\n else {\n lm = flm, ll = flt, dm = fdm, dl = fdt;\n }\n for (var i = 0; i < li; ++i) {\n if (syms[i] > 255) {\n var len = (syms[i] >>> 18) & 31;\n wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n if (len > 7)\n wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len];\n var dst = syms[i] & 31;\n wbits16(out, p, dm[dst]), p += dl[dst];\n if (dst > 3)\n wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst];\n }\n else {\n wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];\n }\n }\n wbits16(out, p, lm[256]);\n return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, lst) {\n var s = dat.length;\n var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);\n // writing to this writes to the output buffer\n var w = o.subarray(pre, o.length - post);\n var pos = 0;\n if (!lvl || s < 8) {\n for (var i = 0; i <= s; i += 65535) {\n // end\n var e = i + 65535;\n if (e < s) {\n // write full block\n pos = wfblk(w, pos, dat.subarray(i, e));\n }\n else {\n // write final block\n w[i] = lst;\n pos = wfblk(w, pos, dat.subarray(i, s));\n }\n }\n }\n else {\n var opt = deo[lvl - 1];\n var n = opt >>> 13, c = opt & 8191;\n var msk_1 = (1 << plvl) - 1;\n // prev 2-byte val map curr 2-byte val map\n var prev = new u16(32768), head = new u16(msk_1 + 1);\n var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n // 24576 is an arbitrary number of maximum symbols per block\n // 424 buffer for last block\n var syms = new u32(25000);\n // length/literal freq distance freq\n var lf = new u16(288), df = new u16(32);\n // l/lcnt exbits index l/lind waitdx bitpos\n var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;\n for (; i < s; ++i) {\n // hash value\n // deopt when i > s - 3 - at end, deopt acceptable\n var hv = hsh(i);\n // index mod 32768 previous index mod\n var imod = i & 32767, pimod = head[hv];\n prev[imod] = pimod;\n head[hv] = imod;\n // We always should modify head and prev, but only add symbols if\n // this data is not yet processed (\"wait\" for wait index)\n if (wi <= i) {\n // bytes remaining\n var rem = s - i;\n if ((lc_1 > 7000 || li > 24576) && rem > 423) {\n pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n li = lc_1 = eb = 0, bs = i;\n for (var j = 0; j < 286; ++j)\n lf[j] = 0;\n for (var j = 0; j < 30; ++j)\n df[j] = 0;\n }\n // len dist chain\n var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767;\n if (rem > 2 && hv == hsh(i - dif)) {\n var maxn = Math.min(n, rem) - 1;\n var maxd = Math.min(32767, i);\n // max possible length\n // not capped at dif because decompressors implement \"rolling\" index population\n var ml = Math.min(258, rem);\n while (dif <= maxd && --ch_1 && imod != pimod) {\n if (dat[i + l] == dat[i + l - dif]) {\n var nl = 0;\n for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n ;\n if (nl > l) {\n l = nl, d = dif;\n // break out early when we reach \"nice\" (we are satisfied enough)\n if (nl > maxn)\n break;\n // now, find the rarest 2-byte sequence within this\n // length of literals and search for that instead.\n // Much faster than just using the start\n var mmd = Math.min(dif, nl - 2);\n var md = 0;\n for (var j = 0; j < mmd; ++j) {\n var ti = (i - dif + j + 32768) & 32767;\n var pti = prev[ti];\n var cd = (ti - pti + 32768) & 32767;\n if (cd > md)\n md = cd, pimod = ti;\n }\n }\n }\n // check the previous match\n imod = pimod, pimod = prev[imod];\n dif += (imod - pimod + 32768) & 32767;\n }\n }\n // d will be nonzero only when a match was found\n if (d) {\n // store both dist and len data in one Uint32\n // Make sure this is recognized as a len/dist with 28th bit (2^28)\n syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n var lin = revfl[l] & 31, din = revfd[d] & 31;\n eb += fleb[lin] + fdeb[din];\n ++lf[257 + lin];\n ++df[din];\n wi = i + l;\n ++lc_1;\n }\n else {\n syms[li++] = dat[i];\n ++lf[dat[i]];\n }\n }\n }\n pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n // this is the easiest way to avoid needing to maintain state\n if (!lst && pos & 7)\n pos = wfblk(w, pos + 1, et);\n }\n return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n var t = new u32(256);\n for (var i = 0; i < 256; ++i) {\n var c = i, k = 9;\n while (--k)\n c = ((c & 1) && 0xEDB88320) ^ (c >>> 1);\n t[i] = c;\n }\n return t;\n})();\n// CRC32\nvar crc = function () {\n var c = -1;\n return {\n p: function (d) {\n // closures have awful performance\n var cr = c;\n for (var i = 0; i < d.length; ++i)\n cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n c = cr;\n },\n d: function () { return ~c; }\n };\n};\n// Alder32\nvar adler = function () {\n var a = 1, b = 0;\n return {\n p: function (d) {\n // closures have awful performance\n var n = a, m = b;\n var l = d.length;\n for (var i = 0; i != l;) {\n var e = Math.min(i + 2655, l);\n for (; i < e; ++i)\n m += n += d[i];\n n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);\n }\n a = n, b = m;\n },\n d: function () {\n a %= 65521, b %= 65521;\n return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8);\n }\n };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n var o = {};\n for (var k in a)\n o[k] = a[k];\n for (var k in b)\n o[k] = b[k];\n return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n var dt = fn();\n var st = fn.toString();\n var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/ /g, '').split(',');\n for (var i = 0; i < dt.length; ++i) {\n var v = dt[i], k = ks[i];\n if (typeof v == 'function') {\n fnStr += ';' + k + '=';\n var st_1 = v.toString();\n if (v.prototype) {\n // for global objects\n if (st_1.indexOf('[native code]') != -1) {\n var spInd = st_1.indexOf(' ', 8) + 1;\n fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n }\n else {\n fnStr += st_1;\n for (var t in v.prototype)\n fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n }\n }\n else\n fnStr += st_1;\n }\n else\n td[k] = v;\n }\n return [fnStr, td];\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n var tl = [];\n for (var k in v) {\n if (v[k] instanceof u8 || v[k] instanceof u16 || v[k] instanceof u32)\n tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n }\n return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n var _a;\n if (!ch[id]) {\n var fnStr = '', td_1 = {}, m = fns.length - 1;\n for (var i = 0; i < m; ++i)\n _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1];\n ch[id] = wcln(fns[m], fnStr, td_1);\n }\n var td = mrg({}, ch[id][1]);\n return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, hMap, max, bits, bits16, shft, slc, inflt, inflateSync, pbf, gu8]; };\nvar bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zlv]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get u8\nvar gu8 = function (o) { return o && o.size && new u8(o.size); };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n var w = wrkr(fns, init, id, function (err, dat) {\n w.terminate();\n cb(err, dat);\n });\n w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);\n return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n return function (ev) { return strm.push(ev.data[0], ev.data[1]); };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id) {\n var t;\n var w = wrkr(fns, init, id, function (err, dat) {\n if (err)\n w.terminate(), strm.ondata.call(strm, err);\n else {\n if (dat[1])\n w.terminate();\n strm.ondata.call(strm, err, dat[0], dat[1]);\n }\n });\n w.postMessage(opts);\n strm.push = function (d, f) {\n if (t)\n throw 'stream finished';\n if (!strm.ondata)\n throw 'no stream handler';\n w.postMessage([d, t = f], [d.buffer]);\n };\n strm.terminate = function () { w.terminate(); };\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };\nvar b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };\n// write bytes\nvar wbytes = function (d, b, v) {\n for (; v; ++b)\n d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n var fn = o.filename;\n c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n if (o.mtime != 0)\n wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n if (fn) {\n c[3] = 8;\n for (var i = 0; i <= fn.length; ++i)\n c[i + 10] = fn.charCodeAt(i);\n }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n throw 'invalid gzip data';\n var flg = d[3];\n var st = 10;\n if (flg & 4)\n st += d[10] | (d[11] << 8) + 2;\n for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n ;\n return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n var l = d.length;\n return ((d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) | (d[l - 1] << 24)) >>> 0;\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };\n// zlib header\nvar zlh = function (c, o) {\n var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1);\n};\n// zlib valid\nvar zlv = function (d) {\n if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n throw 'invalid zlib data';\n if (d[1] & 32)\n throw 'invalid zlib data: preset dictionaries not supported';\n};\nfunction AsyncCmpStrm(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n return opts;\n}\n// zlib footer: -4 to -0 is Adler32\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n function Deflate(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n this.o = opts || {};\n }\n Deflate.prototype.p = function (c, f) {\n this.ondata(dopt(c, this.o, 0, 0, !f), f);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Deflate.prototype.push = function (chunk, final) {\n if (this.d)\n throw 'stream finished';\n if (!this.ondata)\n throw 'no stream handler';\n this.d = final;\n this.p(chunk, final || false);\n };\n return Deflate;\n}());\n\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n function AsyncDeflate(opts, cb) {\n astrmify([\n bDflt,\n function () { return [astrm, Deflate]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Deflate(ev.data);\n onmessage = astrm(strm);\n }, 6);\n }\n return AsyncDeflate;\n}());\n\nfunction deflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return cbify(data, opts, [\n bDflt,\n ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nfunction deflateSync(data, opts) {\n return dopt(data, opts || {}, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n /**\n * Creates an inflation stream\n * @param cb The callback to call whenever data is inflated\n */\n function Inflate(cb) {\n this.s = {};\n this.p = new u8(0);\n this.ondata = cb;\n }\n Inflate.prototype.e = function (c) {\n if (this.d)\n throw 'stream finished';\n if (!this.ondata)\n throw 'no stream handler';\n var l = this.p.length;\n var n = new u8(l + c.length);\n n.set(this.p), n.set(c, l), this.p = n;\n };\n Inflate.prototype.c = function (final) {\n this.d = this.s.i = final || false;\n var bts = this.s.b;\n var dt = inflt(this.p, this.o, this.s);\n this.ondata(slc(dt, bts, this.s.b), this.d);\n this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;\n };\n /**\n * Pushes a chunk to be inflated\n * @param chunk The chunk to push\n * @param final Whether this is the final chunk\n */\n Inflate.prototype.push = function (chunk, final) {\n this.e(chunk), this.c(final);\n };\n return Inflate;\n}());\n\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous inflation stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncInflate(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n function () { return [astrm, Inflate]; }\n ], this, 0, function () {\n var strm = new Inflate();\n onmessage = astrm(strm);\n }, 7);\n }\n return AsyncInflate;\n}());\n\nfunction inflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return cbify(data, opts, [\n bInflt\n ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);\n}\n/**\n * Expands DEFLATE data with no wrapper\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nfunction inflateSync(data, out) {\n return inflt(data, out);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n function Gzip(opts, cb) {\n this.c = crc();\n this.l = 0;\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be GZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gzip.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Gzip.prototype.p = function (c, f) {\n this.c.p(c);\n this.l += c.length;\n var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f);\n if (this.v)\n gzh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n this.ondata(raw, f);\n };\n return Gzip;\n}());\n\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n function AsyncGzip(opts, cb) {\n astrmify([\n bDflt,\n gze,\n function () { return [astrm, Deflate, Gzip]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Gzip(ev.data);\n onmessage = astrm(strm);\n }, 8);\n }\n return AsyncGzip;\n}());\n\nfunction gzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return cbify(data, opts, [\n bDflt,\n gze,\n function () { return [gzipSync]; }\n ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nfunction gzipSync(data, opts) {\n if (!opts)\n opts = {};\n var c = crc(), l = data.length;\n c.p(data);\n var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n /**\n * Creates a GUNZIP stream\n * @param cb The callback to call whenever data is inflated\n */\n function Gunzip(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be GUNZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gunzip.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n var s = this.p.length > 3 ? gzs(this.p) : 4;\n if (s >= this.p.length && !final)\n return;\n this.p = this.p.subarray(s), this.v = 0;\n }\n if (final) {\n if (this.p.length < 8)\n throw 'invalid gzip stream';\n this.p = this.p.subarray(0, -8);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Gunzip;\n}());\n\n/**\n * Asynchronous streaming GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous GUNZIP stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncGunzip(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n guze,\n function () { return [astrm, Inflate, Gunzip]; }\n ], this, 0, function () {\n var strm = new Gunzip();\n onmessage = astrm(strm);\n }, 9);\n }\n return AsyncGunzip;\n}());\n\nfunction gunzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return cbify(data, opts, [\n bInflt,\n guze,\n function () { return [gunzipSync]; }\n ], function (ev) { return pbf(gunzipSync(ev.data[0])); }, 3, cb);\n}\n/**\n * Expands GZIP data\n * @param data The data to decompress\n * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory.\n * @returns The decompressed version of the data\n */\nfunction gunzipSync(data, out) {\n return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n function Zlib(opts, cb) {\n this.c = adler();\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be zlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Zlib.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Zlib.prototype.p = function (c, f) {\n this.c.p(c);\n var raw = dopt(c, this.o, this.v && 2, f && 4, !f);\n if (this.v)\n zlh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 4, this.c.d());\n this.ondata(raw, f);\n };\n return Zlib;\n}());\n\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n function AsyncZlib(opts, cb) {\n astrmify([\n bDflt,\n zle,\n function () { return [astrm, Deflate, Zlib]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Zlib(ev.data);\n onmessage = astrm(strm);\n }, 10);\n }\n return AsyncZlib;\n}());\n\nfunction zlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return cbify(data, opts, [\n bDflt,\n zle,\n function () { return [zlibSync]; }\n ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nfunction zlibSync(data, opts) {\n if (!opts)\n opts = {};\n var a = adler();\n a.p(data);\n var d = dopt(data, opts, 2, 4);\n return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n /**\n * Creates a Zlib decompression stream\n * @param cb The callback to call whenever data is inflated\n */\n function Unzlib(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be unzlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzlib.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n if (this.p.length < 2 && !final)\n return;\n this.p = this.p.subarray(2), this.v = 0;\n }\n if (final) {\n if (this.p.length < 4)\n throw 'invalid zlib stream';\n this.p = this.p.subarray(0, -4);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Unzlib;\n}());\n\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous Zlib decompression stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncUnzlib(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n zule,\n function () { return [astrm, Inflate, Unzlib]; }\n ], this, 0, function () {\n var strm = new Unzlib();\n onmessage = astrm(strm);\n }, 11);\n }\n return AsyncUnzlib;\n}());\n\nfunction unzlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return cbify(data, opts, [\n bInflt,\n zule,\n function () { return [unzlibSync]; }\n ], function (ev) { return pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))); }, 5, cb);\n}\n/**\n * Expands Zlib data\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nfunction unzlibSync(data, out) {\n return inflt((zlv(data), data.subarray(2, -4)), out);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\n\n// Default algorithm for compression (used because having a known output size allows faster decompression)\n\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n /**\n * Creates a decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function Decompress(cb) {\n this.G = Gunzip;\n this.I = Inflate;\n this.Z = Unzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Decompress.prototype.push = function (chunk, final) {\n if (!this.ondata)\n throw 'no stream handler';\n if (!this.s) {\n if (this.p && this.p.length) {\n var n = new u8(this.p.length + chunk.length);\n n.set(this.p), n.set(chunk, this.p.length);\n }\n else\n this.p = chunk;\n if (this.p.length > 2) {\n var _this_1 = this;\n var cb = function () { _this_1.ondata.apply(_this_1, arguments); };\n this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n ? new this.G(cb)\n : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n ? new this.I(cb)\n : new this.Z(cb);\n this.s.push(this.p, final);\n this.p = null;\n }\n }\n else\n this.s.push(chunk, final);\n };\n return Decompress;\n}());\n\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function AsyncDecompress(cb) {\n this.G = AsyncGunzip;\n this.I = AsyncInflate;\n this.Z = AsyncUnzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncDecompress.prototype.push = function (chunk, final) {\n Decompress.prototype.push.call(this, chunk, final);\n };\n return AsyncDecompress;\n}());\n\nfunction decompress(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzip(data, opts, cb)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflate(data, opts, cb)\n : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nfunction decompressSync(data, out) {\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzipSync(data, out)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflateSync(data, out)\n : unzlibSync(data, out);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n for (var k in d) {\n var val = d[k], n = p + k;\n if (val instanceof u8)\n t[n] = [val, o];\n else if (Array.isArray(val))\n t[n] = [val[0], mrg(o, val[1])];\n else\n fltn(val, n + '/', t, o);\n }\n};\n// text encoder\nvar te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();\n// text decoder\nvar td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();\n// text decoder stream\nvar tds = 0;\ntry {\n td.decode(et, { stream: true });\n tds = 1;\n}\ncatch (e) { }\n// decode UTF8\nvar dutf8 = function (d) {\n for (var r = '', i = 0;;) {\n var c = d[i++];\n var eb = (c > 127) + (c > 223) + (c > 239);\n if (i + eb > d.length)\n return [r, slc(d, i - 1)];\n if (!eb)\n r += String.fromCharCode(c);\n else if (eb == 3) {\n c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,\n r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n }\n else if (eb & 1)\n r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));\n else\n r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));\n }\n};\n/**\n * Streaming UTF-8 decoding\n */\nvar DecodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is decoded\n */\n function DecodeUTF8(cb) {\n this.ondata = cb;\n if (tds)\n this.t = new TextDecoder();\n else\n this.p = et;\n }\n /**\n * Pushes a chunk to be decoded from UTF-8 binary\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n DecodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n throw 'no callback';\n final = !!final;\n if (this.t) {\n this.ondata(this.t.decode(chunk, { stream: true }), final);\n if (final) {\n if (this.t.decode().length)\n throw 'invalid utf-8 data';\n this.t = null;\n }\n return;\n }\n if (!this.p)\n throw 'stream finished';\n var dat = new u8(this.p.length + chunk.length);\n dat.set(this.p);\n dat.set(chunk, this.p.length);\n var _a = dutf8(dat), ch = _a[0], np = _a[1];\n if (final) {\n if (np.length)\n throw 'invalid utf-8 data';\n this.p = null;\n }\n else\n this.p = np;\n this.ondata(ch, final);\n };\n return DecodeUTF8;\n}());\n\n/**\n * Streaming UTF-8 encoding\n */\nvar EncodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is encoded\n */\n function EncodeUTF8(cb) {\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be encoded to UTF-8\n * @param chunk The string data to push\n * @param final Whether this is the last chunk\n */\n EncodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n throw 'no callback';\n if (this.d)\n throw 'stream finished';\n this.ondata(strToU8(chunk), this.d = final || false);\n };\n return EncodeUTF8;\n}());\n\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nfunction strToU8(str, latin1) {\n if (latin1) {\n var ar_1 = new u8(str.length);\n for (var i = 0; i < str.length; ++i)\n ar_1[i] = str.charCodeAt(i);\n return ar_1;\n }\n if (te)\n return te.encode(str);\n var l = str.length;\n var ar = new u8(str.length + (str.length >> 1));\n var ai = 0;\n var w = function (v) { ar[ai++] = v; };\n for (var i = 0; i < l; ++i) {\n if (ai + 5 > ar.length) {\n var n = new u8(ai + 8 + ((l - i) << 1));\n n.set(ar);\n ar = n;\n }\n var c = str.charCodeAt(i);\n if (c < 128 || latin1)\n w(c);\n else if (c < 2048)\n w(192 | (c >> 6)), w(128 | (c & 63));\n else if (c > 55295 && c < 57344)\n c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n else\n w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n }\n return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nfunction strFromU8(dat, latin1) {\n if (latin1) {\n var r = '';\n for (var i = 0; i < dat.length; i += 16384)\n r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));\n return r;\n }\n else if (td)\n return td.decode(dat);\n else {\n var _a = dutf8(dat), out = _a[0], ext = _a[1];\n if (ext.length)\n throw 'invalid utf-8 data';\n return out;\n }\n}\n;\n// deflate bit flag\nvar dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);\n var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];\n return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];\n};\n// read zip64 extra field\nvar z64e = function (d, b) {\n for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))\n ;\n return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];\n};\n// extra field length\nvar exfl = function (ex) {\n var le = 0;\n if (ex) {\n for (var k in ex) {\n var l = ex[k].length;\n if (l > 65535)\n throw 'extra field too long';\n le += l + 4;\n }\n }\n return le;\n};\n// write zip header\nvar wzh = function (d, b, f, fn, u, c, ce, co) {\n var fl = fn.length, ex = f.extra, col = co && co.length;\n var exl = exfl(ex);\n wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n if (ce != null)\n d[b++] = 20, d[b++] = f.os;\n d[b] = 20, b += 2; // spec compliance? what's that?\n d[b++] = (f.flag << 1) | (c == null && 8), d[b++] = u && 8;\n d[b++] = f.compression & 255, d[b++] = f.compression >> 8;\n var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;\n if (y < 0 || y > 119)\n throw 'date not in range 1980-2099';\n wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1)), b += 4;\n if (c != null) {\n wbytes(d, b, f.crc);\n wbytes(d, b + 4, c);\n wbytes(d, b + 8, f.size);\n }\n wbytes(d, b + 12, fl);\n wbytes(d, b + 14, exl), b += 16;\n if (ce != null) {\n wbytes(d, b, col);\n wbytes(d, b + 6, f.attrs);\n wbytes(d, b + 10, ce), b += 14;\n }\n d.set(fn, b);\n b += fl;\n if (exl) {\n for (var k in ex) {\n var exf = ex[k], l = exf.length;\n wbytes(d, b, +k);\n wbytes(d, b + 2, l);\n d.set(exf, b + 4), b += 4 + l;\n }\n }\n if (col)\n d.set(co, b), b += col;\n return b;\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n wbytes(o, b, 0x6054B50); // skip disk\n wbytes(o, b + 8, c);\n wbytes(o, b + 10, c);\n wbytes(o, b + 12, d);\n wbytes(o, b + 16, e);\n};\n/**\n * A pass-through stream to keep data uncompressed in a ZIP archive.\n */\nvar ZipPassThrough = /*#__PURE__*/ (function () {\n /**\n * Creates a pass-through stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n */\n function ZipPassThrough(filename) {\n this.filename = filename;\n this.c = crc();\n this.size = 0;\n this.compression = 0;\n }\n /**\n * Processes a chunk and pushes to the output stream. You can override this\n * method in a subclass for custom behavior, but by default this passes\n * the data through. You must call this.ondata(err, chunk, final) at some\n * point in this method.\n * @param chunk The chunk to process\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.process = function (chunk, final) {\n this.ondata(null, chunk, final);\n };\n /**\n * Pushes a chunk to be added. If you are subclassing this with a custom\n * compression algorithm, note that you must push data from the source\n * file only, pre-compression.\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.push = function (chunk, final) {\n if (!this.ondata)\n throw 'no callback - add to ZIP archive before pushing';\n this.c.p(chunk);\n this.size += chunk.length;\n if (final)\n this.crc = this.c.d();\n this.process(chunk, final || false);\n };\n return ZipPassThrough;\n}());\n\n// I don't extend because TypeScript extension adds 1kB of runtime bloat\n/**\n * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate\n * for better performance\n */\nvar ZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function ZipDeflate(filename, opts) {\n var _this_1 = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new Deflate(opts, function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n }\n ZipDeflate.prototype.process = function (chunk, final) {\n try {\n this.d.push(chunk, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return ZipDeflate;\n}());\n\n/**\n * Asynchronous streaming DEFLATE compression for ZIP archives\n */\nvar AsyncZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function AsyncZipDeflate(filename, opts) {\n var _this_1 = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new AsyncDeflate(opts, function (err, dat, final) {\n _this_1.ondata(err, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n this.terminate = this.d.terminate;\n }\n AsyncZipDeflate.prototype.process = function (chunk, final) {\n this.d.push(chunk, final);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return AsyncZipDeflate;\n}());\n\n// TODO: Better tree shaking\n/**\n * A zippable archive to which files can incrementally be added\n */\nvar Zip = /*#__PURE__*/ (function () {\n /**\n * Creates an empty ZIP archive to which files can be added\n * @param cb The callback to call whenever data for the generated ZIP archive\n * is available\n */\n function Zip(cb) {\n this.ondata = cb;\n this.u = [];\n this.d = 1;\n }\n /**\n * Adds a file to the ZIP archive\n * @param file The file stream to add\n */\n Zip.prototype.add = function (file) {\n var _this_1 = this;\n if (this.d & 2)\n throw 'stream finished';\n var f = strToU8(file.filename), fl = f.length;\n var com = file.comment, o = com && strToU8(com);\n var u = fl != file.filename.length || (o && (com.length != o.length));\n var hl = fl + exfl(file.extra) + 30;\n if (fl > 65535)\n throw 'filename too long';\n var header = new u8(hl);\n wzh(header, 0, file, f, u);\n var chks = [header];\n var pAll = function () {\n for (var _i = 0, chks_1 = chks; _i < chks_1.length; _i++) {\n var chk = chks_1[_i];\n _this_1.ondata(null, chk, false);\n }\n chks = [];\n };\n var tr = this.d;\n this.d = 0;\n var ind = this.u.length;\n var uf = mrg(file, {\n f: f,\n u: u,\n o: o,\n t: function () {\n if (file.terminate)\n file.terminate();\n },\n r: function () {\n pAll();\n if (tr) {\n var nxt = _this_1.u[ind + 1];\n if (nxt)\n nxt.r();\n else\n _this_1.d = 1;\n }\n tr = 1;\n }\n });\n var cl = 0;\n file.ondata = function (err, dat, final) {\n if (err) {\n _this_1.ondata(err, dat, final);\n _this_1.terminate();\n }\n else {\n cl += dat.length;\n chks.push(dat);\n if (final) {\n var dd = new u8(16);\n wbytes(dd, 0, 0x8074B50);\n wbytes(dd, 4, file.crc);\n wbytes(dd, 8, cl);\n wbytes(dd, 12, file.size);\n chks.push(dd);\n uf.c = cl, uf.b = hl + cl + 16, uf.crc = file.crc, uf.size = file.size;\n if (tr)\n uf.r();\n tr = 1;\n }\n else if (tr)\n pAll();\n }\n };\n this.u.push(uf);\n };\n /**\n * Ends the process of adding files and prepares to emit the final chunks.\n * This *must* be called after adding all desired files for the resulting\n * ZIP file to work properly.\n */\n Zip.prototype.end = function () {\n var _this_1 = this;\n if (this.d & 2) {\n if (this.d & 1)\n throw 'stream finishing';\n throw 'stream finished';\n }\n if (this.d)\n this.e();\n else\n this.u.push({\n r: function () {\n if (!(_this_1.d & 1))\n return;\n _this_1.u.splice(-1, 1);\n _this_1.e();\n },\n t: function () { }\n });\n this.d = 3;\n };\n Zip.prototype.e = function () {\n var bt = 0, l = 0, tl = 0;\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);\n }\n var out = new u8(tl + 22);\n for (var _b = 0, _c = this.u; _b < _c.length; _b++) {\n var f = _c[_b];\n wzh(out, bt, f, f.f, f.u, f.c, l, f.o);\n bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;\n }\n wzf(out, bt, this.u.length, tl, l);\n this.ondata(null, out, true);\n this.d = 2;\n };\n /**\n * A method to terminate any internal workers used by the stream. Subsequent\n * calls to add() will fail.\n */\n Zip.prototype.terminate = function () {\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n f.t();\n }\n this.d = 2;\n };\n return Zip;\n}());\n\nfunction zip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n throw 'no callback';\n var r = {};\n fltn(data, '', r, opts);\n var k = Object.keys(r);\n var lft = k.length, o = 0, tot = 0;\n var slft = lft, files = new Array(lft);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var cbf = function () {\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n tot = 0;\n for (var i = 0; i < slft; ++i) {\n var f = files[i];\n try {\n var l = f.c.length;\n wzh(out, tot, f, f.f, f.u, l);\n var badd = 30 + f.f.length + exfl(f.extra);\n var loc = tot + badd;\n out.set(f.c, loc);\n wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;\n }\n catch (e) {\n return cb(e, null);\n }\n }\n wzf(out, o, files.length, cdl, oe);\n cb(null, out);\n };\n if (!lft)\n cbf();\n var _loop_1 = function (i) {\n var fn = k[i];\n var _a = r[fn], file = _a[0], p = _a[1];\n var c = crc(), size = file.length;\n c.p(file);\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n var compression = p.level == 0 ? 0 : 8;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cb(e, null);\n }\n else {\n var l = d.length;\n files[i] = mrg(p, {\n size: size,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n compression: compression\n });\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n if (!--lft)\n cbf();\n }\n };\n if (s > 65535)\n cbl('filename too long', null);\n if (!compression)\n cbl(null, file);\n else if (size < 160000) {\n try {\n cbl(null, deflateSync(file, p));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(deflate(file, p, cbl));\n };\n // Cannot use lft because it can decrease\n for (var i = 0; i < slft; ++i) {\n _loop_1(i);\n }\n return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nfunction zipSync(data, opts) {\n if (!opts)\n opts = {};\n var r = {};\n var files = [];\n fltn(data, '', r, opts);\n var o = 0;\n var tot = 0;\n for (var fn in r) {\n var _a = r[fn], file = _a[0], p = _a[1];\n var compression = p.level == 0 ? 0 : 8;\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n if (s > 65535)\n throw 'filename too long';\n var d = compression ? deflateSync(file, p) : file, l = d.length;\n var c = crc();\n c.p(file);\n files.push(mrg(p, {\n size: file.length,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n o: o,\n compression: compression\n }));\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n }\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n for (var i = 0; i < files.length; ++i) {\n var f = files[i];\n wzh(out, f.o, f, f.f, f.u, f.c.length);\n var badd = 30 + f.f.length + exfl(f.extra);\n out.set(f.c, f.o + badd);\n wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);\n }\n wzf(out, o, files.length, cdl, oe);\n return out;\n}\n/**\n * Streaming pass-through decompression for ZIP archives\n */\nvar UnzipPassThrough = /*#__PURE__*/ (function () {\n function UnzipPassThrough() {\n }\n UnzipPassThrough.prototype.push = function (data, final) {\n this.ondata(null, data, final);\n };\n UnzipPassThrough.compression = 0;\n return UnzipPassThrough;\n}());\n\n/**\n * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for\n * better performance.\n */\nvar UnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function UnzipInflate() {\n var _this_1 = this;\n this.i = new Inflate(function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n }\n UnzipInflate.prototype.push = function (data, final) {\n try {\n this.i.push(data, final);\n }\n catch (e) {\n this.ondata(e, data, final);\n }\n };\n UnzipInflate.compression = 8;\n return UnzipInflate;\n}());\n\n/**\n * Asynchronous streaming DEFLATE decompression for ZIP archives\n */\nvar AsyncUnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function AsyncUnzipInflate(_, sz) {\n var _this_1 = this;\n if (sz < 320000) {\n this.i = new Inflate(function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n }\n else {\n this.i = new AsyncInflate(function (err, dat, final) {\n _this_1.ondata(err, dat, final);\n });\n this.terminate = this.i.terminate;\n }\n }\n AsyncUnzipInflate.prototype.push = function (data, final) {\n if (this.i.terminate)\n data = slc(data, 0);\n this.i.push(data, final);\n };\n AsyncUnzipInflate.compression = 8;\n return AsyncUnzipInflate;\n}());\n\n/**\n * A ZIP archive decompression stream that emits files as they are discovered\n */\nvar Unzip = /*#__PURE__*/ (function () {\n /**\n * Creates a ZIP decompression stream\n * @param cb The callback to call whenever a file in the ZIP archive is found\n */\n function Unzip(cb) {\n this.onfile = cb;\n this.k = [];\n this.o = {\n 0: UnzipPassThrough\n };\n this.p = et;\n }\n /**\n * Pushes a chunk to be unzipped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzip.prototype.push = function (chunk, final) {\n var _this_1 = this;\n if (!this.onfile)\n throw 'no callback';\n if (!this.p)\n throw 'stream finished';\n if (this.c > 0) {\n var len = Math.min(this.c, chunk.length);\n var toAdd = chunk.subarray(0, len);\n this.c -= len;\n if (this.d)\n this.d.push(toAdd, !this.c);\n else\n this.k[0].push(toAdd);\n chunk = chunk.subarray(len);\n if (chunk.length)\n return this.push(chunk, final);\n }\n else {\n var f = 0, i = 0, is = void 0, buf = void 0;\n if (!this.p.length)\n buf = chunk;\n else if (!chunk.length)\n buf = this.p;\n else {\n buf = new u8(this.p.length + chunk.length);\n buf.set(this.p), buf.set(chunk, this.p.length);\n }\n var l = buf.length, oc = this.c, add = oc && this.d;\n var _loop_2 = function () {\n var _a;\n var sig = b4(buf, i);\n if (sig == 0x4034B50) {\n f = 1, is = i;\n this_1.d = null;\n this_1.c = 0;\n var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);\n if (l > i + 30 + fnl + es) {\n var chks_2 = [];\n this_1.k.unshift(chks_2);\n f = 2;\n var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);\n var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);\n if (sc_1 == 4294967295) {\n _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];\n }\n else if (dd)\n sc_1 = -1;\n i += es;\n this_1.c = sc_1;\n var d_1;\n var file_1 = {\n name: fn_1,\n compression: cmp_1,\n start: function () {\n if (!file_1.ondata)\n throw 'no callback';\n if (!sc_1)\n file_1.ondata(null, et, true);\n else {\n var ctr = _this_1.o[cmp_1];\n if (!ctr)\n throw 'unknown compression type ' + cmp_1;\n d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);\n d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };\n for (var _i = 0, chks_3 = chks_2; _i < chks_3.length; _i++) {\n var dat = chks_3[_i];\n d_1.push(dat, false);\n }\n if (_this_1.k[0] == chks_2 && _this_1.c)\n _this_1.d = d_1;\n else\n d_1.push(et, true);\n }\n },\n terminate: function () {\n if (d_1 && d_1.terminate)\n d_1.terminate();\n }\n };\n if (sc_1 >= 0)\n file_1.size = sc_1, file_1.originalSize = su_1;\n this_1.onfile(file_1);\n }\n return \"break\";\n }\n else if (oc) {\n if (sig == 0x8074B50) {\n is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;\n return \"break\";\n }\n else if (sig == 0x2014B50) {\n is = i -= 4, f = 3, this_1.c = 0;\n return \"break\";\n }\n }\n };\n var this_1 = this;\n for (; i < l - 4; ++i) {\n var state_1 = _loop_2();\n if (state_1 === \"break\")\n break;\n }\n this.p = et;\n if (oc < 0) {\n var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);\n if (add)\n add.push(dat, !!f);\n else\n this.k[+(f == 2)].push(dat);\n }\n if (f & 2)\n return this.push(buf.subarray(i), final);\n this.p = buf.subarray(i);\n }\n if (final) {\n if (this.c)\n throw 'invalid zip file';\n this.p = null;\n }\n };\n /**\n * Registers a decoder with the stream, allowing for files compressed with\n * the compression type provided to be expanded correctly\n * @param decoder The decoder constructor\n */\n Unzip.prototype.register = function (decoder) {\n this.o[decoder.compression] = decoder;\n };\n return Unzip;\n}());\n\n/**\n * Asynchronously decompresses a ZIP archive\n * @param data The raw compressed ZIP file\n * @param cb The callback to call with the decompressed files\n * @returns A function that can be used to immediately terminate the unzipping\n */\nfunction unzip(data, cb) {\n if (typeof cb != 'function')\n throw 'no callback';\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var files = {};\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558) {\n cb('invalid zip file', null);\n return;\n }\n }\n ;\n var lft = b2(data, e + 8);\n if (!lft)\n cb(null, {});\n var c = lft;\n var o = b4(data, e + 16);\n var z = o == 4294967295;\n if (z) {\n e = b4(data, e - 12);\n if (b4(data, e) != 0x6064B50) {\n cb('invalid zip file', null);\n return;\n }\n c = lft = b4(data, e + 32);\n o = b4(data, e + 48);\n }\n var _loop_3 = function (i) {\n var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cb(e, null);\n }\n else {\n files[fn] = d;\n if (!--lft)\n cb(null, files);\n }\n };\n if (!c_1)\n cbl(null, slc(data, b, b + sc));\n else if (c_1 == 8) {\n var infl = data.subarray(b, b + sc);\n if (sc < 320000) {\n try {\n cbl(null, inflateSync(infl, new u8(su)));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(inflate(infl, { size: su }, cbl));\n }\n else\n cbl('unknown compression type ' + c_1, null);\n };\n for (var i = 0; i < c; ++i) {\n _loop_3(i);\n }\n return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @returns The decompressed files\n */\nfunction unzipSync(data) {\n var files = {};\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558)\n throw 'invalid zip file';\n }\n ;\n var c = b2(data, e + 8);\n if (!c)\n return {};\n var o = b4(data, e + 16);\n var z = o == 4294967295;\n if (z) {\n e = b4(data, e - 12);\n if (b4(data, e) != 0x6064B50)\n throw 'invalid zip file';\n c = b4(data, e + 32);\n o = b4(data, e + 48);\n }\n for (var i = 0; i < c; ++i) {\n var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n if (!c_2)\n files[fn] = slc(data, b, b + sc);\n else if (c_2 == 8)\n files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su));\n else\n throw 'unknown compression type ' + c_2;\n }\n return files;\n}\n\n\n//# sourceURL=webpack://MaterialXView/./node_modules/three/examples/jsm/libs/fflate.module.js?"); + +/***/ }), + +/***/ "./node_modules/three/examples/jsm/loaders/GLTFLoader.js": +/*!***************************************************************!*\ + !*** ./node_modules/three/examples/jsm/loaders/GLTFLoader.js ***! + \***************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ GLTFLoader: () => (/* binding */ GLTFLoader)\n/* harmony export */ });\n/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! three */ \"./node_modules/three/build/three.module.js\");\n/* harmony import */ var _utils_BufferGeometryUtils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/BufferGeometryUtils.js */ \"./node_modules/three/examples/jsm/utils/BufferGeometryUtils.js\");\n\n\n\nclass GLTFLoader extends three__WEBPACK_IMPORTED_MODULE_0__.Loader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t\tthis.dracoLoader = null;\n\t\tthis.ktx2Loader = null;\n\t\tthis.meshoptDecoder = null;\n\n\t\tthis.pluginCallbacks = [];\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFMaterialsClearcoatExtension( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFTextureBasisUExtension( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFTextureWebPExtension( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFTextureAVIFExtension( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFMaterialsSheenExtension( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFMaterialsTransmissionExtension( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFMaterialsVolumeExtension( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFMaterialsIorExtension( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFMaterialsEmissiveStrengthExtension( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFMaterialsSpecularExtension( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFMaterialsIridescenceExtension( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFLightsExtension( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFMeshoptCompression( parser );\n\n\t\t} );\n\n\t\tthis.register( function ( parser ) {\n\n\t\t\treturn new GLTFMeshGpuInstancing( parser );\n\n\t\t} );\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tconst scope = this;\n\n\t\tlet resourcePath;\n\n\t\tif ( this.resourcePath !== '' ) {\n\n\t\t\tresourcePath = this.resourcePath;\n\n\t\t} else if ( this.path !== '' ) {\n\n\t\t\tresourcePath = this.path;\n\n\t\t} else {\n\n\t\t\tresourcePath = three__WEBPACK_IMPORTED_MODULE_0__.LoaderUtils.extractUrlBase( url );\n\n\t\t}\n\n\t\t// Tells the LoadingManager to track an extra item, which resolves after\n\t\t// the model is fully loaded. This means the count of items loaded will\n\t\t// be incorrect, but ensures manager.onLoad() does not fire early.\n\t\tthis.manager.itemStart( url );\n\n\t\tconst _onError = function ( e ) {\n\n\t\t\tif ( onError ) {\n\n\t\t\t\tonError( e );\n\n\t\t\t} else {\n\n\t\t\t\tconsole.error( e );\n\n\t\t\t}\n\n\t\t\tscope.manager.itemError( url );\n\t\t\tscope.manager.itemEnd( url );\n\n\t\t};\n\n\t\tconst loader = new three__WEBPACK_IMPORTED_MODULE_0__.FileLoader( this.manager );\n\n\t\tloader.setPath( this.path );\n\t\tloader.setResponseType( 'arraybuffer' );\n\t\tloader.setRequestHeader( this.requestHeader );\n\t\tloader.setWithCredentials( this.withCredentials );\n\n\t\tloader.load( url, function ( data ) {\n\n\t\t\ttry {\n\n\t\t\t\tscope.parse( data, resourcePath, function ( gltf ) {\n\n\t\t\t\t\tonLoad( gltf );\n\n\t\t\t\t\tscope.manager.itemEnd( url );\n\n\t\t\t\t}, _onError );\n\n\t\t\t} catch ( e ) {\n\n\t\t\t\t_onError( e );\n\n\t\t\t}\n\n\t\t}, onProgress, _onError );\n\n\t}\n\n\tsetDRACOLoader( dracoLoader ) {\n\n\t\tthis.dracoLoader = dracoLoader;\n\t\treturn this;\n\n\t}\n\n\tsetDDSLoader() {\n\n\t\tthrow new Error(\n\n\t\t\t'THREE.GLTFLoader: \"MSFT_texture_dds\" no longer supported. Please update to \"KHR_texture_basisu\".'\n\n\t\t);\n\n\t}\n\n\tsetKTX2Loader( ktx2Loader ) {\n\n\t\tthis.ktx2Loader = ktx2Loader;\n\t\treturn this;\n\n\t}\n\n\tsetMeshoptDecoder( meshoptDecoder ) {\n\n\t\tthis.meshoptDecoder = meshoptDecoder;\n\t\treturn this;\n\n\t}\n\n\tregister( callback ) {\n\n\t\tif ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {\n\n\t\t\tthis.pluginCallbacks.push( callback );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tunregister( callback ) {\n\n\t\tif ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {\n\n\t\t\tthis.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tparse( data, path, onLoad, onError ) {\n\n\t\tlet json;\n\t\tconst extensions = {};\n\t\tconst plugins = {};\n\t\tconst textDecoder = new TextDecoder();\n\n\t\tif ( typeof data === 'string' ) {\n\n\t\t\tjson = JSON.parse( data );\n\n\t\t} else if ( data instanceof ArrayBuffer ) {\n\n\t\t\tconst magic = textDecoder.decode( new Uint8Array( data, 0, 4 ) );\n\n\t\t\tif ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {\n\n\t\t\t\ttry {\n\n\t\t\t\t\textensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );\n\n\t\t\t\t} catch ( error ) {\n\n\t\t\t\t\tif ( onError ) onError( error );\n\t\t\t\t\treturn;\n\n\t\t\t\t}\n\n\t\t\t\tjson = JSON.parse( extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content );\n\n\t\t\t} else {\n\n\t\t\t\tjson = JSON.parse( textDecoder.decode( data ) );\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tjson = data;\n\n\t\t}\n\n\t\tif ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {\n\n\t\t\tif ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );\n\t\t\treturn;\n\n\t\t}\n\n\t\tconst parser = new GLTFParser( json, {\n\n\t\t\tpath: path || this.resourcePath || '',\n\t\t\tcrossOrigin: this.crossOrigin,\n\t\t\trequestHeader: this.requestHeader,\n\t\t\tmanager: this.manager,\n\t\t\tktx2Loader: this.ktx2Loader,\n\t\t\tmeshoptDecoder: this.meshoptDecoder\n\n\t\t} );\n\n\t\tparser.fileLoader.setRequestHeader( this.requestHeader );\n\n\t\tfor ( let i = 0; i < this.pluginCallbacks.length; i ++ ) {\n\n\t\t\tconst plugin = this.pluginCallbacks[ i ]( parser );\n\t\t\tplugins[ plugin.name ] = plugin;\n\n\t\t\t// Workaround to avoid determining as unknown extension\n\t\t\t// in addUnknownExtensionsToUserData().\n\t\t\t// Remove this workaround if we move all the existing\n\t\t\t// extension handlers to plugin system\n\t\t\textensions[ plugin.name ] = true;\n\n\t\t}\n\n\t\tif ( json.extensionsUsed ) {\n\n\t\t\tfor ( let i = 0; i < json.extensionsUsed.length; ++ i ) {\n\n\t\t\t\tconst extensionName = json.extensionsUsed[ i ];\n\t\t\t\tconst extensionsRequired = json.extensionsRequired || [];\n\n\t\t\t\tswitch ( extensionName ) {\n\n\t\t\t\t\tcase EXTENSIONS.KHR_MATERIALS_UNLIT:\n\t\t\t\t\t\textensions[ extensionName ] = new GLTFMaterialsUnlitExtension();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:\n\t\t\t\t\t\textensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase EXTENSIONS.KHR_TEXTURE_TRANSFORM:\n\t\t\t\t\t\textensions[ extensionName ] = new GLTFTextureTransformExtension();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase EXTENSIONS.KHR_MESH_QUANTIZATION:\n\t\t\t\t\t\textensions[ extensionName ] = new GLTFMeshQuantizationExtension();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\n\t\t\t\t\t\tif ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {\n\n\t\t\t\t\t\t\tconsole.warn( 'THREE.GLTFLoader: Unknown extension \"' + extensionName + '\".' );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tparser.setExtensions( extensions );\n\t\tparser.setPlugins( plugins );\n\t\tparser.parse( onLoad, onError );\n\n\t}\n\n\tparseAsync( data, path ) {\n\n\t\tconst scope = this;\n\n\t\treturn new Promise( function ( resolve, reject ) {\n\n\t\t\tscope.parse( data, path, resolve, reject );\n\n\t\t} );\n\n\t}\n\n}\n\n/* GLTFREGISTRY */\n\nfunction GLTFRegistry() {\n\n\tlet objects = {};\n\n\treturn\t{\n\n\t\tget: function ( key ) {\n\n\t\t\treturn objects[ key ];\n\n\t\t},\n\n\t\tadd: function ( key, object ) {\n\n\t\t\tobjects[ key ] = object;\n\n\t\t},\n\n\t\tremove: function ( key ) {\n\n\t\t\tdelete objects[ key ];\n\n\t\t},\n\n\t\tremoveAll: function () {\n\n\t\t\tobjects = {};\n\n\t\t}\n\n\t};\n\n}\n\n/*********************************/\n/********** EXTENSIONS ***********/\n/*********************************/\n\nconst EXTENSIONS = {\n\tKHR_BINARY_GLTF: 'KHR_binary_glTF',\n\tKHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',\n\tKHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',\n\tKHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',\n\tKHR_MATERIALS_IOR: 'KHR_materials_ior',\n\tKHR_MATERIALS_SHEEN: 'KHR_materials_sheen',\n\tKHR_MATERIALS_SPECULAR: 'KHR_materials_specular',\n\tKHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',\n\tKHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence',\n\tKHR_MATERIALS_UNLIT: 'KHR_materials_unlit',\n\tKHR_MATERIALS_VOLUME: 'KHR_materials_volume',\n\tKHR_TEXTURE_BASISU: 'KHR_texture_basisu',\n\tKHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',\n\tKHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',\n\tKHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength',\n\tEXT_TEXTURE_WEBP: 'EXT_texture_webp',\n\tEXT_TEXTURE_AVIF: 'EXT_texture_avif',\n\tEXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',\n\tEXT_MESH_GPU_INSTANCING: 'EXT_mesh_gpu_instancing'\n};\n\n/**\n * Punctual Lights Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual\n */\nclass GLTFLightsExtension {\n\n\tconstructor( parser ) {\n\n\t\tthis.parser = parser;\n\t\tthis.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;\n\n\t\t// Object3D instance caches\n\t\tthis.cache = { refs: {}, uses: {} };\n\n\t}\n\n\t_markDefs() {\n\n\t\tconst parser = this.parser;\n\t\tconst nodeDefs = this.parser.json.nodes || [];\n\n\t\tfor ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {\n\n\t\t\tconst nodeDef = nodeDefs[ nodeIndex ];\n\n\t\t\tif ( nodeDef.extensions\n\t\t\t\t\t&& nodeDef.extensions[ this.name ]\n\t\t\t\t\t&& nodeDef.extensions[ this.name ].light !== undefined ) {\n\n\t\t\t\tparser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t_loadLight( lightIndex ) {\n\n\t\tconst parser = this.parser;\n\t\tconst cacheKey = 'light:' + lightIndex;\n\t\tlet dependency = parser.cache.get( cacheKey );\n\n\t\tif ( dependency ) return dependency;\n\n\t\tconst json = parser.json;\n\t\tconst extensions = ( json.extensions && json.extensions[ this.name ] ) || {};\n\t\tconst lightDefs = extensions.lights || [];\n\t\tconst lightDef = lightDefs[ lightIndex ];\n\t\tlet lightNode;\n\n\t\tconst color = new three__WEBPACK_IMPORTED_MODULE_0__.Color( 0xffffff );\n\n\t\tif ( lightDef.color !== undefined ) color.fromArray( lightDef.color );\n\n\t\tconst range = lightDef.range !== undefined ? lightDef.range : 0;\n\n\t\tswitch ( lightDef.type ) {\n\n\t\t\tcase 'directional':\n\t\t\t\tlightNode = new three__WEBPACK_IMPORTED_MODULE_0__.DirectionalLight( color );\n\t\t\t\tlightNode.target.position.set( 0, 0, - 1 );\n\t\t\t\tlightNode.add( lightNode.target );\n\t\t\t\tbreak;\n\n\t\t\tcase 'point':\n\t\t\t\tlightNode = new three__WEBPACK_IMPORTED_MODULE_0__.PointLight( color );\n\t\t\t\tlightNode.distance = range;\n\t\t\t\tbreak;\n\n\t\t\tcase 'spot':\n\t\t\t\tlightNode = new three__WEBPACK_IMPORTED_MODULE_0__.SpotLight( color );\n\t\t\t\tlightNode.distance = range;\n\t\t\t\t// Handle spotlight properties.\n\t\t\t\tlightDef.spot = lightDef.spot || {};\n\t\t\t\tlightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;\n\t\t\t\tlightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;\n\t\t\t\tlightNode.angle = lightDef.spot.outerConeAngle;\n\t\t\t\tlightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;\n\t\t\t\tlightNode.target.position.set( 0, 0, - 1 );\n\t\t\t\tlightNode.add( lightNode.target );\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tthrow new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );\n\n\t\t}\n\n\t\t// Some lights (e.g. spot) default to a position other than the origin. Reset the position\n\t\t// here, because node-level parsing will only override position if explicitly specified.\n\t\tlightNode.position.set( 0, 0, 0 );\n\n\t\tlightNode.decay = 2;\n\n\t\tassignExtrasToUserData( lightNode, lightDef );\n\n\t\tif ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;\n\n\t\tlightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );\n\n\t\tdependency = Promise.resolve( lightNode );\n\n\t\tparser.cache.add( cacheKey, dependency );\n\n\t\treturn dependency;\n\n\t}\n\n\tgetDependency( type, index ) {\n\n\t\tif ( type !== 'light' ) return;\n\n\t\treturn this._loadLight( index );\n\n\t}\n\n\tcreateNodeAttachment( nodeIndex ) {\n\n\t\tconst self = this;\n\t\tconst parser = this.parser;\n\t\tconst json = parser.json;\n\t\tconst nodeDef = json.nodes[ nodeIndex ];\n\t\tconst lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};\n\t\tconst lightIndex = lightDef.light;\n\n\t\tif ( lightIndex === undefined ) return null;\n\n\t\treturn this._loadLight( lightIndex ).then( function ( light ) {\n\n\t\t\treturn parser._getNodeRef( self.cache, lightIndex, light );\n\n\t\t} );\n\n\t}\n\n}\n\n/**\n * Unlit Materials Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit\n */\nclass GLTFMaterialsUnlitExtension {\n\n\tconstructor() {\n\n\t\tthis.name = EXTENSIONS.KHR_MATERIALS_UNLIT;\n\n\t}\n\n\tgetMaterialType() {\n\n\t\treturn three__WEBPACK_IMPORTED_MODULE_0__.MeshBasicMaterial;\n\n\t}\n\n\textendParams( materialParams, materialDef, parser ) {\n\n\t\tconst pending = [];\n\n\t\tmaterialParams.color = new three__WEBPACK_IMPORTED_MODULE_0__.Color( 1.0, 1.0, 1.0 );\n\t\tmaterialParams.opacity = 1.0;\n\n\t\tconst metallicRoughness = materialDef.pbrMetallicRoughness;\n\n\t\tif ( metallicRoughness ) {\n\n\t\t\tif ( Array.isArray( metallicRoughness.baseColorFactor ) ) {\n\n\t\t\t\tconst array = metallicRoughness.baseColorFactor;\n\n\t\t\t\tmaterialParams.color.fromArray( array );\n\t\t\t\tmaterialParams.opacity = array[ 3 ];\n\n\t\t\t}\n\n\t\t\tif ( metallicRoughness.baseColorTexture !== undefined ) {\n\n\t\t\t\tpending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, three__WEBPACK_IMPORTED_MODULE_0__.SRGBColorSpace ) );\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn Promise.all( pending );\n\n\t}\n\n}\n\n/**\n * Materials Emissive Strength Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md\n */\nclass GLTFMaterialsEmissiveStrengthExtension {\n\n\tconstructor( parser ) {\n\n\t\tthis.parser = parser;\n\t\tthis.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH;\n\n\t}\n\n\textendMaterialParams( materialIndex, materialParams ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {\n\n\t\t\treturn Promise.resolve();\n\n\t\t}\n\n\t\tconst emissiveStrength = materialDef.extensions[ this.name ].emissiveStrength;\n\n\t\tif ( emissiveStrength !== undefined ) {\n\n\t\t\tmaterialParams.emissiveIntensity = emissiveStrength;\n\n\t\t}\n\n\t\treturn Promise.resolve();\n\n\t}\n\n}\n\n/**\n * Clearcoat Materials Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat\n */\nclass GLTFMaterialsClearcoatExtension {\n\n\tconstructor( parser ) {\n\n\t\tthis.parser = parser;\n\t\tthis.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;\n\n\t}\n\n\tgetMaterialType( materialIndex ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;\n\n\t\treturn three__WEBPACK_IMPORTED_MODULE_0__.MeshPhysicalMaterial;\n\n\t}\n\n\textendMaterialParams( materialIndex, materialParams ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {\n\n\t\t\treturn Promise.resolve();\n\n\t\t}\n\n\t\tconst pending = [];\n\n\t\tconst extension = materialDef.extensions[ this.name ];\n\n\t\tif ( extension.clearcoatFactor !== undefined ) {\n\n\t\t\tmaterialParams.clearcoat = extension.clearcoatFactor;\n\n\t\t}\n\n\t\tif ( extension.clearcoatTexture !== undefined ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );\n\n\t\t}\n\n\t\tif ( extension.clearcoatRoughnessFactor !== undefined ) {\n\n\t\t\tmaterialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;\n\n\t\t}\n\n\t\tif ( extension.clearcoatRoughnessTexture !== undefined ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );\n\n\t\t}\n\n\t\tif ( extension.clearcoatNormalTexture !== undefined ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );\n\n\t\t\tif ( extension.clearcoatNormalTexture.scale !== undefined ) {\n\n\t\t\t\tconst scale = extension.clearcoatNormalTexture.scale;\n\n\t\t\t\tmaterialParams.clearcoatNormalScale = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2( scale, scale );\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn Promise.all( pending );\n\n\t}\n\n}\n\n/**\n * Iridescence Materials Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence\n */\nclass GLTFMaterialsIridescenceExtension {\n\n\tconstructor( parser ) {\n\n\t\tthis.parser = parser;\n\t\tthis.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE;\n\n\t}\n\n\tgetMaterialType( materialIndex ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;\n\n\t\treturn three__WEBPACK_IMPORTED_MODULE_0__.MeshPhysicalMaterial;\n\n\t}\n\n\textendMaterialParams( materialIndex, materialParams ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {\n\n\t\t\treturn Promise.resolve();\n\n\t\t}\n\n\t\tconst pending = [];\n\n\t\tconst extension = materialDef.extensions[ this.name ];\n\n\t\tif ( extension.iridescenceFactor !== undefined ) {\n\n\t\t\tmaterialParams.iridescence = extension.iridescenceFactor;\n\n\t\t}\n\n\t\tif ( extension.iridescenceTexture !== undefined ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'iridescenceMap', extension.iridescenceTexture ) );\n\n\t\t}\n\n\t\tif ( extension.iridescenceIor !== undefined ) {\n\n\t\t\tmaterialParams.iridescenceIOR = extension.iridescenceIor;\n\n\t\t}\n\n\t\tif ( materialParams.iridescenceThicknessRange === undefined ) {\n\n\t\t\tmaterialParams.iridescenceThicknessRange = [ 100, 400 ];\n\n\t\t}\n\n\t\tif ( extension.iridescenceThicknessMinimum !== undefined ) {\n\n\t\t\tmaterialParams.iridescenceThicknessRange[ 0 ] = extension.iridescenceThicknessMinimum;\n\n\t\t}\n\n\t\tif ( extension.iridescenceThicknessMaximum !== undefined ) {\n\n\t\t\tmaterialParams.iridescenceThicknessRange[ 1 ] = extension.iridescenceThicknessMaximum;\n\n\t\t}\n\n\t\tif ( extension.iridescenceThicknessTexture !== undefined ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture ) );\n\n\t\t}\n\n\t\treturn Promise.all( pending );\n\n\t}\n\n}\n\n/**\n * Sheen Materials Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen\n */\nclass GLTFMaterialsSheenExtension {\n\n\tconstructor( parser ) {\n\n\t\tthis.parser = parser;\n\t\tthis.name = EXTENSIONS.KHR_MATERIALS_SHEEN;\n\n\t}\n\n\tgetMaterialType( materialIndex ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;\n\n\t\treturn three__WEBPACK_IMPORTED_MODULE_0__.MeshPhysicalMaterial;\n\n\t}\n\n\textendMaterialParams( materialIndex, materialParams ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {\n\n\t\t\treturn Promise.resolve();\n\n\t\t}\n\n\t\tconst pending = [];\n\n\t\tmaterialParams.sheenColor = new three__WEBPACK_IMPORTED_MODULE_0__.Color( 0, 0, 0 );\n\t\tmaterialParams.sheenRoughness = 0;\n\t\tmaterialParams.sheen = 1;\n\n\t\tconst extension = materialDef.extensions[ this.name ];\n\n\t\tif ( extension.sheenColorFactor !== undefined ) {\n\n\t\t\tmaterialParams.sheenColor.fromArray( extension.sheenColorFactor );\n\n\t\t}\n\n\t\tif ( extension.sheenRoughnessFactor !== undefined ) {\n\n\t\t\tmaterialParams.sheenRoughness = extension.sheenRoughnessFactor;\n\n\t\t}\n\n\t\tif ( extension.sheenColorTexture !== undefined ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'sheenColorMap', extension.sheenColorTexture, three__WEBPACK_IMPORTED_MODULE_0__.SRGBColorSpace ) );\n\n\t\t}\n\n\t\tif ( extension.sheenRoughnessTexture !== undefined ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture ) );\n\n\t\t}\n\n\t\treturn Promise.all( pending );\n\n\t}\n\n}\n\n/**\n * Transmission Materials Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission\n * Draft: https://github.com/KhronosGroup/glTF/pull/1698\n */\nclass GLTFMaterialsTransmissionExtension {\n\n\tconstructor( parser ) {\n\n\t\tthis.parser = parser;\n\t\tthis.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;\n\n\t}\n\n\tgetMaterialType( materialIndex ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;\n\n\t\treturn three__WEBPACK_IMPORTED_MODULE_0__.MeshPhysicalMaterial;\n\n\t}\n\n\textendMaterialParams( materialIndex, materialParams ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {\n\n\t\t\treturn Promise.resolve();\n\n\t\t}\n\n\t\tconst pending = [];\n\n\t\tconst extension = materialDef.extensions[ this.name ];\n\n\t\tif ( extension.transmissionFactor !== undefined ) {\n\n\t\t\tmaterialParams.transmission = extension.transmissionFactor;\n\n\t\t}\n\n\t\tif ( extension.transmissionTexture !== undefined ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );\n\n\t\t}\n\n\t\treturn Promise.all( pending );\n\n\t}\n\n}\n\n/**\n * Materials Volume Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume\n */\nclass GLTFMaterialsVolumeExtension {\n\n\tconstructor( parser ) {\n\n\t\tthis.parser = parser;\n\t\tthis.name = EXTENSIONS.KHR_MATERIALS_VOLUME;\n\n\t}\n\n\tgetMaterialType( materialIndex ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;\n\n\t\treturn three__WEBPACK_IMPORTED_MODULE_0__.MeshPhysicalMaterial;\n\n\t}\n\n\textendMaterialParams( materialIndex, materialParams ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {\n\n\t\t\treturn Promise.resolve();\n\n\t\t}\n\n\t\tconst pending = [];\n\n\t\tconst extension = materialDef.extensions[ this.name ];\n\n\t\tmaterialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0;\n\n\t\tif ( extension.thicknessTexture !== undefined ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) );\n\n\t\t}\n\n\t\tmaterialParams.attenuationDistance = extension.attenuationDistance || Infinity;\n\n\t\tconst colorArray = extension.attenuationColor || [ 1, 1, 1 ];\n\t\tmaterialParams.attenuationColor = new three__WEBPACK_IMPORTED_MODULE_0__.Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] );\n\n\t\treturn Promise.all( pending );\n\n\t}\n\n}\n\n/**\n * Materials ior Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior\n */\nclass GLTFMaterialsIorExtension {\n\n\tconstructor( parser ) {\n\n\t\tthis.parser = parser;\n\t\tthis.name = EXTENSIONS.KHR_MATERIALS_IOR;\n\n\t}\n\n\tgetMaterialType( materialIndex ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;\n\n\t\treturn three__WEBPACK_IMPORTED_MODULE_0__.MeshPhysicalMaterial;\n\n\t}\n\n\textendMaterialParams( materialIndex, materialParams ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {\n\n\t\t\treturn Promise.resolve();\n\n\t\t}\n\n\t\tconst extension = materialDef.extensions[ this.name ];\n\n\t\tmaterialParams.ior = extension.ior !== undefined ? extension.ior : 1.5;\n\n\t\treturn Promise.resolve();\n\n\t}\n\n}\n\n/**\n * Materials specular Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular\n */\nclass GLTFMaterialsSpecularExtension {\n\n\tconstructor( parser ) {\n\n\t\tthis.parser = parser;\n\t\tthis.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;\n\n\t}\n\n\tgetMaterialType( materialIndex ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;\n\n\t\treturn three__WEBPACK_IMPORTED_MODULE_0__.MeshPhysicalMaterial;\n\n\t}\n\n\textendMaterialParams( materialIndex, materialParams ) {\n\n\t\tconst parser = this.parser;\n\t\tconst materialDef = parser.json.materials[ materialIndex ];\n\n\t\tif ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {\n\n\t\t\treturn Promise.resolve();\n\n\t\t}\n\n\t\tconst pending = [];\n\n\t\tconst extension = materialDef.extensions[ this.name ];\n\n\t\tmaterialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0;\n\n\t\tif ( extension.specularTexture !== undefined ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) );\n\n\t\t}\n\n\t\tconst colorArray = extension.specularColorFactor || [ 1, 1, 1 ];\n\t\tmaterialParams.specularColor = new three__WEBPACK_IMPORTED_MODULE_0__.Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] );\n\n\t\tif ( extension.specularColorTexture !== undefined ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'specularColorMap', extension.specularColorTexture, three__WEBPACK_IMPORTED_MODULE_0__.SRGBColorSpace ) );\n\n\t\t}\n\n\t\treturn Promise.all( pending );\n\n\t}\n\n}\n\n/**\n * BasisU Texture Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu\n */\nclass GLTFTextureBasisUExtension {\n\n\tconstructor( parser ) {\n\n\t\tthis.parser = parser;\n\t\tthis.name = EXTENSIONS.KHR_TEXTURE_BASISU;\n\n\t}\n\n\tloadTexture( textureIndex ) {\n\n\t\tconst parser = this.parser;\n\t\tconst json = parser.json;\n\n\t\tconst textureDef = json.textures[ textureIndex ];\n\n\t\tif ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\tconst extension = textureDef.extensions[ this.name ];\n\t\tconst loader = parser.options.ktx2Loader;\n\n\t\tif ( ! loader ) {\n\n\t\t\tif ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {\n\n\t\t\t\tthrow new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );\n\n\t\t\t} else {\n\n\t\t\t\t// Assumes that the extension is optional and that a fallback texture is present\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn parser.loadTextureImage( textureIndex, extension.source, loader );\n\n\t}\n\n}\n\n/**\n * WebP Texture Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp\n */\nclass GLTFTextureWebPExtension {\n\n\tconstructor( parser ) {\n\n\t\tthis.parser = parser;\n\t\tthis.name = EXTENSIONS.EXT_TEXTURE_WEBP;\n\t\tthis.isSupported = null;\n\n\t}\n\n\tloadTexture( textureIndex ) {\n\n\t\tconst name = this.name;\n\t\tconst parser = this.parser;\n\t\tconst json = parser.json;\n\n\t\tconst textureDef = json.textures[ textureIndex ];\n\n\t\tif ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\tconst extension = textureDef.extensions[ name ];\n\t\tconst source = json.images[ extension.source ];\n\n\t\tlet loader = parser.textureLoader;\n\t\tif ( source.uri ) {\n\n\t\t\tconst handler = parser.options.manager.getHandler( source.uri );\n\t\t\tif ( handler !== null ) loader = handler;\n\n\t\t}\n\n\t\treturn this.detectSupport().then( function ( isSupported ) {\n\n\t\t\tif ( isSupported ) return parser.loadTextureImage( textureIndex, extension.source, loader );\n\n\t\t\tif ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {\n\n\t\t\t\tthrow new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' );\n\n\t\t\t}\n\n\t\t\t// Fall back to PNG or JPEG.\n\t\t\treturn parser.loadTexture( textureIndex );\n\n\t\t} );\n\n\t}\n\n\tdetectSupport() {\n\n\t\tif ( ! this.isSupported ) {\n\n\t\t\tthis.isSupported = new Promise( function ( resolve ) {\n\n\t\t\t\tconst image = new Image();\n\n\t\t\t\t// Lossy test image. Support for lossy images doesn't guarantee support for all\n\t\t\t\t// WebP images, unfortunately.\n\t\t\t\timage.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';\n\n\t\t\t\timage.onload = image.onerror = function () {\n\n\t\t\t\t\tresolve( image.height === 1 );\n\n\t\t\t\t};\n\n\t\t\t} );\n\n\t\t}\n\n\t\treturn this.isSupported;\n\n\t}\n\n}\n\n/**\n * AVIF Texture Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_avif\n */\nclass GLTFTextureAVIFExtension {\n\n\tconstructor( parser ) {\n\n\t\tthis.parser = parser;\n\t\tthis.name = EXTENSIONS.EXT_TEXTURE_AVIF;\n\t\tthis.isSupported = null;\n\n\t}\n\n\tloadTexture( textureIndex ) {\n\n\t\tconst name = this.name;\n\t\tconst parser = this.parser;\n\t\tconst json = parser.json;\n\n\t\tconst textureDef = json.textures[ textureIndex ];\n\n\t\tif ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\tconst extension = textureDef.extensions[ name ];\n\t\tconst source = json.images[ extension.source ];\n\n\t\tlet loader = parser.textureLoader;\n\t\tif ( source.uri ) {\n\n\t\t\tconst handler = parser.options.manager.getHandler( source.uri );\n\t\t\tif ( handler !== null ) loader = handler;\n\n\t\t}\n\n\t\treturn this.detectSupport().then( function ( isSupported ) {\n\n\t\t\tif ( isSupported ) return parser.loadTextureImage( textureIndex, extension.source, loader );\n\n\t\t\tif ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {\n\n\t\t\t\tthrow new Error( 'THREE.GLTFLoader: AVIF required by asset but unsupported.' );\n\n\t\t\t}\n\n\t\t\t// Fall back to PNG or JPEG.\n\t\t\treturn parser.loadTexture( textureIndex );\n\n\t\t} );\n\n\t}\n\n\tdetectSupport() {\n\n\t\tif ( ! this.isSupported ) {\n\n\t\t\tthis.isSupported = new Promise( function ( resolve ) {\n\n\t\t\t\tconst image = new Image();\n\n\t\t\t\t// Lossy test image.\n\t\t\t\timage.src = 'data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=';\n\t\t\t\timage.onload = image.onerror = function () {\n\n\t\t\t\t\tresolve( image.height === 1 );\n\n\t\t\t\t};\n\n\t\t\t} );\n\n\t\t}\n\n\t\treturn this.isSupported;\n\n\t}\n\n}\n\n/**\n * meshopt BufferView Compression Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression\n */\nclass GLTFMeshoptCompression {\n\n\tconstructor( parser ) {\n\n\t\tthis.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;\n\t\tthis.parser = parser;\n\n\t}\n\n\tloadBufferView( index ) {\n\n\t\tconst json = this.parser.json;\n\t\tconst bufferView = json.bufferViews[ index ];\n\n\t\tif ( bufferView.extensions && bufferView.extensions[ this.name ] ) {\n\n\t\t\tconst extensionDef = bufferView.extensions[ this.name ];\n\n\t\t\tconst buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );\n\t\t\tconst decoder = this.parser.options.meshoptDecoder;\n\n\t\t\tif ( ! decoder || ! decoder.supported ) {\n\n\t\t\t\tif ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {\n\n\t\t\t\t\tthrow new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// Assumes that the extension is optional and that fallback buffer data is present\n\t\t\t\t\treturn null;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn buffer.then( function ( res ) {\n\n\t\t\t\tconst byteOffset = extensionDef.byteOffset || 0;\n\t\t\t\tconst byteLength = extensionDef.byteLength || 0;\n\n\t\t\t\tconst count = extensionDef.count;\n\t\t\t\tconst stride = extensionDef.byteStride;\n\n\t\t\t\tconst source = new Uint8Array( res, byteOffset, byteLength );\n\n\t\t\t\tif ( decoder.decodeGltfBufferAsync ) {\n\n\t\t\t\t\treturn decoder.decodeGltfBufferAsync( count, stride, source, extensionDef.mode, extensionDef.filter ).then( function ( res ) {\n\n\t\t\t\t\t\treturn res.buffer;\n\n\t\t\t\t\t} );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync\n\t\t\t\t\treturn decoder.ready.then( function () {\n\n\t\t\t\t\t\tconst result = new ArrayBuffer( count * stride );\n\t\t\t\t\t\tdecoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );\n\t\t\t\t\t\treturn result;\n\n\t\t\t\t\t} );\n\n\t\t\t\t}\n\n\t\t\t} );\n\n\t\t} else {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t}\n\n}\n\n/**\n * GPU Instancing Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing\n *\n */\nclass GLTFMeshGpuInstancing {\n\n\tconstructor( parser ) {\n\n\t\tthis.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING;\n\t\tthis.parser = parser;\n\n\t}\n\n\tcreateNodeMesh( nodeIndex ) {\n\n\t\tconst json = this.parser.json;\n\t\tconst nodeDef = json.nodes[ nodeIndex ];\n\n\t\tif ( ! nodeDef.extensions || ! nodeDef.extensions[ this.name ] ||\n\t\t\tnodeDef.mesh === undefined ) {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\tconst meshDef = json.meshes[ nodeDef.mesh ];\n\n\t\t// No Points or Lines + Instancing support yet\n\n\t\tfor ( const primitive of meshDef.primitives ) {\n\n\t\t\tif ( primitive.mode !== WEBGL_CONSTANTS.TRIANGLES &&\n\t\t\t\t primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP &&\n\t\t\t\t primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN &&\n\t\t\t\t primitive.mode !== undefined ) {\n\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t}\n\n\t\tconst extensionDef = nodeDef.extensions[ this.name ];\n\t\tconst attributesDef = extensionDef.attributes;\n\n\t\t// @TODO: Can we support InstancedMesh + SkinnedMesh?\n\n\t\tconst pending = [];\n\t\tconst attributes = {};\n\n\t\tfor ( const key in attributesDef ) {\n\n\t\t\tpending.push( this.parser.getDependency( 'accessor', attributesDef[ key ] ).then( accessor => {\n\n\t\t\t\tattributes[ key ] = accessor;\n\t\t\t\treturn attributes[ key ];\n\n\t\t\t} ) );\n\n\t\t}\n\n\t\tif ( pending.length < 1 ) {\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\tpending.push( this.parser.createNodeMesh( nodeIndex ) );\n\n\t\treturn Promise.all( pending ).then( results => {\n\n\t\t\tconst nodeObject = results.pop();\n\t\t\tconst meshes = nodeObject.isGroup ? nodeObject.children : [ nodeObject ];\n\t\t\tconst count = results[ 0 ].count; // All attribute counts should be same\n\t\t\tconst instancedMeshes = [];\n\n\t\t\tfor ( const mesh of meshes ) {\n\n\t\t\t\t// Temporal variables\n\t\t\t\tconst m = new three__WEBPACK_IMPORTED_MODULE_0__.Matrix4();\n\t\t\t\tconst p = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\t\t\t\tconst q = new three__WEBPACK_IMPORTED_MODULE_0__.Quaternion();\n\t\t\t\tconst s = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3( 1, 1, 1 );\n\n\t\t\t\tconst instancedMesh = new three__WEBPACK_IMPORTED_MODULE_0__.InstancedMesh( mesh.geometry, mesh.material, count );\n\n\t\t\t\tfor ( let i = 0; i < count; i ++ ) {\n\n\t\t\t\t\tif ( attributes.TRANSLATION ) {\n\n\t\t\t\t\t\tp.fromBufferAttribute( attributes.TRANSLATION, i );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( attributes.ROTATION ) {\n\n\t\t\t\t\t\tq.fromBufferAttribute( attributes.ROTATION, i );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( attributes.SCALE ) {\n\n\t\t\t\t\t\ts.fromBufferAttribute( attributes.SCALE, i );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tinstancedMesh.setMatrixAt( i, m.compose( p, q, s ) );\n\n\t\t\t\t}\n\n\t\t\t\t// Add instance attributes to the geometry, excluding TRS.\n\t\t\t\tfor ( const attributeName in attributes ) {\n\n\t\t\t\t\tif ( attributeName !== 'TRANSLATION' &&\n\t\t\t\t\t\t attributeName !== 'ROTATION' &&\n\t\t\t\t\t\t attributeName !== 'SCALE' ) {\n\n\t\t\t\t\t\tmesh.geometry.setAttribute( attributeName, attributes[ attributeName ] );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\t// Just in case\n\t\t\t\tthree__WEBPACK_IMPORTED_MODULE_0__.Object3D.prototype.copy.call( instancedMesh, mesh );\n\n\t\t\t\tthis.parser.assignFinalMaterial( instancedMesh );\n\n\t\t\t\tinstancedMeshes.push( instancedMesh );\n\n\t\t\t}\n\n\t\t\tif ( nodeObject.isGroup ) {\n\n\t\t\t\tnodeObject.clear();\n\n\t\t\t\tnodeObject.add( ... instancedMeshes );\n\n\t\t\t\treturn nodeObject;\n\n\t\t\t}\n\n\t\t\treturn instancedMeshes[ 0 ];\n\n\t\t} );\n\n\t}\n\n}\n\n/* BINARY EXTENSION */\nconst BINARY_EXTENSION_HEADER_MAGIC = 'glTF';\nconst BINARY_EXTENSION_HEADER_LENGTH = 12;\nconst BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };\n\nclass GLTFBinaryExtension {\n\n\tconstructor( data ) {\n\n\t\tthis.name = EXTENSIONS.KHR_BINARY_GLTF;\n\t\tthis.content = null;\n\t\tthis.body = null;\n\n\t\tconst headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );\n\t\tconst textDecoder = new TextDecoder();\n\n\t\tthis.header = {\n\t\t\tmagic: textDecoder.decode( new Uint8Array( data.slice( 0, 4 ) ) ),\n\t\t\tversion: headerView.getUint32( 4, true ),\n\t\t\tlength: headerView.getUint32( 8, true )\n\t\t};\n\n\t\tif ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {\n\n\t\t\tthrow new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );\n\n\t\t} else if ( this.header.version < 2.0 ) {\n\n\t\t\tthrow new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );\n\n\t\t}\n\n\t\tconst chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;\n\t\tconst chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );\n\t\tlet chunkIndex = 0;\n\n\t\twhile ( chunkIndex < chunkContentsLength ) {\n\n\t\t\tconst chunkLength = chunkView.getUint32( chunkIndex, true );\n\t\t\tchunkIndex += 4;\n\n\t\t\tconst chunkType = chunkView.getUint32( chunkIndex, true );\n\t\t\tchunkIndex += 4;\n\n\t\t\tif ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {\n\n\t\t\t\tconst contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );\n\t\t\t\tthis.content = textDecoder.decode( contentArray );\n\n\t\t\t} else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {\n\n\t\t\t\tconst byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;\n\t\t\t\tthis.body = data.slice( byteOffset, byteOffset + chunkLength );\n\n\t\t\t}\n\n\t\t\t// Clients must ignore chunks with unknown types.\n\n\t\t\tchunkIndex += chunkLength;\n\n\t\t}\n\n\t\tif ( this.content === null ) {\n\n\t\t\tthrow new Error( 'THREE.GLTFLoader: JSON content not found.' );\n\n\t\t}\n\n\t}\n\n}\n\n/**\n * DRACO Mesh Compression Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression\n */\nclass GLTFDracoMeshCompressionExtension {\n\n\tconstructor( json, dracoLoader ) {\n\n\t\tif ( ! dracoLoader ) {\n\n\t\t\tthrow new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );\n\n\t\t}\n\n\t\tthis.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;\n\t\tthis.json = json;\n\t\tthis.dracoLoader = dracoLoader;\n\t\tthis.dracoLoader.preload();\n\n\t}\n\n\tdecodePrimitive( primitive, parser ) {\n\n\t\tconst json = this.json;\n\t\tconst dracoLoader = this.dracoLoader;\n\t\tconst bufferViewIndex = primitive.extensions[ this.name ].bufferView;\n\t\tconst gltfAttributeMap = primitive.extensions[ this.name ].attributes;\n\t\tconst threeAttributeMap = {};\n\t\tconst attributeNormalizedMap = {};\n\t\tconst attributeTypeMap = {};\n\n\t\tfor ( const attributeName in gltfAttributeMap ) {\n\n\t\t\tconst threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();\n\n\t\t\tthreeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];\n\n\t\t}\n\n\t\tfor ( const attributeName in primitive.attributes ) {\n\n\t\t\tconst threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();\n\n\t\t\tif ( gltfAttributeMap[ attributeName ] !== undefined ) {\n\n\t\t\t\tconst accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];\n\t\t\t\tconst componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];\n\n\t\t\t\tattributeTypeMap[ threeAttributeName ] = componentType.name;\n\t\t\t\tattributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {\n\n\t\t\treturn new Promise( function ( resolve ) {\n\n\t\t\t\tdracoLoader.decodeDracoFile( bufferView, function ( geometry ) {\n\n\t\t\t\t\tfor ( const attributeName in geometry.attributes ) {\n\n\t\t\t\t\t\tconst attribute = geometry.attributes[ attributeName ];\n\t\t\t\t\t\tconst normalized = attributeNormalizedMap[ attributeName ];\n\n\t\t\t\t\t\tif ( normalized !== undefined ) attribute.normalized = normalized;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve( geometry );\n\n\t\t\t\t}, threeAttributeMap, attributeTypeMap );\n\n\t\t\t} );\n\n\t\t} );\n\n\t}\n\n}\n\n/**\n * Texture Transform Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform\n */\nclass GLTFTextureTransformExtension {\n\n\tconstructor() {\n\n\t\tthis.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;\n\n\t}\n\n\textendTexture( texture, transform ) {\n\n\t\tif ( ( transform.texCoord === undefined || transform.texCoord === texture.channel )\n\t\t\t&& transform.offset === undefined\n\t\t\t&& transform.rotation === undefined\n\t\t\t&& transform.scale === undefined ) {\n\n\t\t\t// See https://github.com/mrdoob/three.js/issues/21819.\n\t\t\treturn texture;\n\n\t\t}\n\n\t\ttexture = texture.clone();\n\n\t\tif ( transform.texCoord !== undefined ) {\n\n\t\t\ttexture.channel = transform.texCoord;\n\n\t\t}\n\n\t\tif ( transform.offset !== undefined ) {\n\n\t\t\ttexture.offset.fromArray( transform.offset );\n\n\t\t}\n\n\t\tif ( transform.rotation !== undefined ) {\n\n\t\t\ttexture.rotation = transform.rotation;\n\n\t\t}\n\n\t\tif ( transform.scale !== undefined ) {\n\n\t\t\ttexture.repeat.fromArray( transform.scale );\n\n\t\t}\n\n\t\ttexture.needsUpdate = true;\n\n\t\treturn texture;\n\n\t}\n\n}\n\n/**\n * Mesh Quantization Extension\n *\n * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization\n */\nclass GLTFMeshQuantizationExtension {\n\n\tconstructor() {\n\n\t\tthis.name = EXTENSIONS.KHR_MESH_QUANTIZATION;\n\n\t}\n\n}\n\n/*********************************/\n/********** INTERPOLATION ********/\n/*********************************/\n\n// Spline Interpolation\n// Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation\nclass GLTFCubicSplineInterpolant extends three__WEBPACK_IMPORTED_MODULE_0__.Interpolant {\n\n\tconstructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {\n\n\t\tsuper( parameterPositions, sampleValues, sampleSize, resultBuffer );\n\n\t}\n\n\tcopySampleValue_( index ) {\n\n\t\t// Copies a sample value to the result buffer. See description of glTF\n\t\t// CUBICSPLINE values layout in interpolate_() function below.\n\n\t\tconst result = this.resultBuffer,\n\t\t\tvalues = this.sampleValues,\n\t\t\tvalueSize = this.valueSize,\n\t\t\toffset = index * valueSize * 3 + valueSize;\n\n\t\tfor ( let i = 0; i !== valueSize; i ++ ) {\n\n\t\t\tresult[ i ] = values[ offset + i ];\n\n\t\t}\n\n\t\treturn result;\n\n\t}\n\n\tinterpolate_( i1, t0, t, t1 ) {\n\n\t\tconst result = this.resultBuffer;\n\t\tconst values = this.sampleValues;\n\t\tconst stride = this.valueSize;\n\n\t\tconst stride2 = stride * 2;\n\t\tconst stride3 = stride * 3;\n\n\t\tconst td = t1 - t0;\n\n\t\tconst p = ( t - t0 ) / td;\n\t\tconst pp = p * p;\n\t\tconst ppp = pp * p;\n\n\t\tconst offset1 = i1 * stride3;\n\t\tconst offset0 = offset1 - stride3;\n\n\t\tconst s2 = - 2 * ppp + 3 * pp;\n\t\tconst s3 = ppp - pp;\n\t\tconst s0 = 1 - s2;\n\t\tconst s1 = s3 - pp + p;\n\n\t\t// Layout of keyframe output values for CUBICSPLINE animations:\n\t\t// [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]\n\t\tfor ( let i = 0; i !== stride; i ++ ) {\n\n\t\t\tconst p0 = values[ offset0 + i + stride ]; // splineVertex_k\n\t\t\tconst m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)\n\t\t\tconst p1 = values[ offset1 + i + stride ]; // splineVertex_k+1\n\t\t\tconst m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)\n\n\t\t\tresult[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;\n\n\t\t}\n\n\t\treturn result;\n\n\t}\n\n}\n\nconst _q = new three__WEBPACK_IMPORTED_MODULE_0__.Quaternion();\n\nclass GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {\n\n\tinterpolate_( i1, t0, t, t1 ) {\n\n\t\tconst result = super.interpolate_( i1, t0, t, t1 );\n\n\t\t_q.fromArray( result ).normalize().toArray( result );\n\n\t\treturn result;\n\n\t}\n\n}\n\n\n/*********************************/\n/********** INTERNALS ************/\n/*********************************/\n\n/* CONSTANTS */\n\nconst WEBGL_CONSTANTS = {\n\tFLOAT: 5126,\n\t//FLOAT_MAT2: 35674,\n\tFLOAT_MAT3: 35675,\n\tFLOAT_MAT4: 35676,\n\tFLOAT_VEC2: 35664,\n\tFLOAT_VEC3: 35665,\n\tFLOAT_VEC4: 35666,\n\tLINEAR: 9729,\n\tREPEAT: 10497,\n\tSAMPLER_2D: 35678,\n\tPOINTS: 0,\n\tLINES: 1,\n\tLINE_LOOP: 2,\n\tLINE_STRIP: 3,\n\tTRIANGLES: 4,\n\tTRIANGLE_STRIP: 5,\n\tTRIANGLE_FAN: 6,\n\tUNSIGNED_BYTE: 5121,\n\tUNSIGNED_SHORT: 5123\n};\n\nconst WEBGL_COMPONENT_TYPES = {\n\t5120: Int8Array,\n\t5121: Uint8Array,\n\t5122: Int16Array,\n\t5123: Uint16Array,\n\t5125: Uint32Array,\n\t5126: Float32Array\n};\n\nconst WEBGL_FILTERS = {\n\t9728: three__WEBPACK_IMPORTED_MODULE_0__.NearestFilter,\n\t9729: three__WEBPACK_IMPORTED_MODULE_0__.LinearFilter,\n\t9984: three__WEBPACK_IMPORTED_MODULE_0__.NearestMipmapNearestFilter,\n\t9985: three__WEBPACK_IMPORTED_MODULE_0__.LinearMipmapNearestFilter,\n\t9986: three__WEBPACK_IMPORTED_MODULE_0__.NearestMipmapLinearFilter,\n\t9987: three__WEBPACK_IMPORTED_MODULE_0__.LinearMipmapLinearFilter\n};\n\nconst WEBGL_WRAPPINGS = {\n\t33071: three__WEBPACK_IMPORTED_MODULE_0__.ClampToEdgeWrapping,\n\t33648: three__WEBPACK_IMPORTED_MODULE_0__.MirroredRepeatWrapping,\n\t10497: three__WEBPACK_IMPORTED_MODULE_0__.RepeatWrapping\n};\n\nconst WEBGL_TYPE_SIZES = {\n\t'SCALAR': 1,\n\t'VEC2': 2,\n\t'VEC3': 3,\n\t'VEC4': 4,\n\t'MAT2': 4,\n\t'MAT3': 9,\n\t'MAT4': 16\n};\n\nconst ATTRIBUTES = {\n\tPOSITION: 'position',\n\tNORMAL: 'normal',\n\tTANGENT: 'tangent',\n\tTEXCOORD_0: 'uv',\n\tTEXCOORD_1: 'uv1',\n\tTEXCOORD_2: 'uv2',\n\tTEXCOORD_3: 'uv3',\n\tCOLOR_0: 'color',\n\tWEIGHTS_0: 'skinWeight',\n\tJOINTS_0: 'skinIndex',\n};\n\nconst PATH_PROPERTIES = {\n\tscale: 'scale',\n\ttranslation: 'position',\n\trotation: 'quaternion',\n\tweights: 'morphTargetInfluences'\n};\n\nconst INTERPOLATION = {\n\tCUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each\n\t\t // keyframe track will be initialized with a default interpolation type, then modified.\n\tLINEAR: three__WEBPACK_IMPORTED_MODULE_0__.InterpolateLinear,\n\tSTEP: three__WEBPACK_IMPORTED_MODULE_0__.InterpolateDiscrete\n};\n\nconst ALPHA_MODES = {\n\tOPAQUE: 'OPAQUE',\n\tMASK: 'MASK',\n\tBLEND: 'BLEND'\n};\n\n/**\n * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material\n */\nfunction createDefaultMaterial( cache ) {\n\n\tif ( cache[ 'DefaultMaterial' ] === undefined ) {\n\n\t\tcache[ 'DefaultMaterial' ] = new three__WEBPACK_IMPORTED_MODULE_0__.MeshStandardMaterial( {\n\t\t\tcolor: 0xFFFFFF,\n\t\t\temissive: 0x000000,\n\t\t\tmetalness: 1,\n\t\t\troughness: 1,\n\t\t\ttransparent: false,\n\t\t\tdepthTest: true,\n\t\t\tside: three__WEBPACK_IMPORTED_MODULE_0__.FrontSide\n\t\t} );\n\n\t}\n\n\treturn cache[ 'DefaultMaterial' ];\n\n}\n\nfunction addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {\n\n\t// Add unknown glTF extensions to an object's userData.\n\n\tfor ( const name in objectDef.extensions ) {\n\n\t\tif ( knownExtensions[ name ] === undefined ) {\n\n\t\t\tobject.userData.gltfExtensions = object.userData.gltfExtensions || {};\n\t\t\tobject.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];\n\n\t\t}\n\n\t}\n\n}\n\n/**\n * @param {Object3D|Material|BufferGeometry} object\n * @param {GLTF.definition} gltfDef\n */\nfunction assignExtrasToUserData( object, gltfDef ) {\n\n\tif ( gltfDef.extras !== undefined ) {\n\n\t\tif ( typeof gltfDef.extras === 'object' ) {\n\n\t\t\tObject.assign( object.userData, gltfDef.extras );\n\n\t\t} else {\n\n\t\t\tconsole.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );\n\n\t\t}\n\n\t}\n\n}\n\n/**\n * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets\n *\n * @param {BufferGeometry} geometry\n * @param {Array} targets\n * @param {GLTFParser} parser\n * @return {Promise}\n */\nfunction addMorphTargets( geometry, targets, parser ) {\n\n\tlet hasMorphPosition = false;\n\tlet hasMorphNormal = false;\n\tlet hasMorphColor = false;\n\n\tfor ( let i = 0, il = targets.length; i < il; i ++ ) {\n\n\t\tconst target = targets[ i ];\n\n\t\tif ( target.POSITION !== undefined ) hasMorphPosition = true;\n\t\tif ( target.NORMAL !== undefined ) hasMorphNormal = true;\n\t\tif ( target.COLOR_0 !== undefined ) hasMorphColor = true;\n\n\t\tif ( hasMorphPosition && hasMorphNormal && hasMorphColor ) break;\n\n\t}\n\n\tif ( ! hasMorphPosition && ! hasMorphNormal && ! hasMorphColor ) return Promise.resolve( geometry );\n\n\tconst pendingPositionAccessors = [];\n\tconst pendingNormalAccessors = [];\n\tconst pendingColorAccessors = [];\n\n\tfor ( let i = 0, il = targets.length; i < il; i ++ ) {\n\n\t\tconst target = targets[ i ];\n\n\t\tif ( hasMorphPosition ) {\n\n\t\t\tconst pendingAccessor = target.POSITION !== undefined\n\t\t\t\t? parser.getDependency( 'accessor', target.POSITION )\n\t\t\t\t: geometry.attributes.position;\n\n\t\t\tpendingPositionAccessors.push( pendingAccessor );\n\n\t\t}\n\n\t\tif ( hasMorphNormal ) {\n\n\t\t\tconst pendingAccessor = target.NORMAL !== undefined\n\t\t\t\t? parser.getDependency( 'accessor', target.NORMAL )\n\t\t\t\t: geometry.attributes.normal;\n\n\t\t\tpendingNormalAccessors.push( pendingAccessor );\n\n\t\t}\n\n\t\tif ( hasMorphColor ) {\n\n\t\t\tconst pendingAccessor = target.COLOR_0 !== undefined\n\t\t\t\t? parser.getDependency( 'accessor', target.COLOR_0 )\n\t\t\t\t: geometry.attributes.color;\n\n\t\t\tpendingColorAccessors.push( pendingAccessor );\n\n\t\t}\n\n\t}\n\n\treturn Promise.all( [\n\t\tPromise.all( pendingPositionAccessors ),\n\t\tPromise.all( pendingNormalAccessors ),\n\t\tPromise.all( pendingColorAccessors )\n\t] ).then( function ( accessors ) {\n\n\t\tconst morphPositions = accessors[ 0 ];\n\t\tconst morphNormals = accessors[ 1 ];\n\t\tconst morphColors = accessors[ 2 ];\n\n\t\tif ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;\n\t\tif ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;\n\t\tif ( hasMorphColor ) geometry.morphAttributes.color = morphColors;\n\t\tgeometry.morphTargetsRelative = true;\n\n\t\treturn geometry;\n\n\t} );\n\n}\n\n/**\n * @param {Mesh} mesh\n * @param {GLTF.Mesh} meshDef\n */\nfunction updateMorphTargets( mesh, meshDef ) {\n\n\tmesh.updateMorphTargets();\n\n\tif ( meshDef.weights !== undefined ) {\n\n\t\tfor ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) {\n\n\t\t\tmesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];\n\n\t\t}\n\n\t}\n\n\t// .extras has user-defined data, so check that .extras.targetNames is an array.\n\tif ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {\n\n\t\tconst targetNames = meshDef.extras.targetNames;\n\n\t\tif ( mesh.morphTargetInfluences.length === targetNames.length ) {\n\n\t\t\tmesh.morphTargetDictionary = {};\n\n\t\t\tfor ( let i = 0, il = targetNames.length; i < il; i ++ ) {\n\n\t\t\t\tmesh.morphTargetDictionary[ targetNames[ i ] ] = i;\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tconsole.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );\n\n\t\t}\n\n\t}\n\n}\n\nfunction createPrimitiveKey( primitiveDef ) {\n\n\tconst dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];\n\tlet geometryKey;\n\n\tif ( dracoExtension ) {\n\n\t\tgeometryKey = 'draco:' + dracoExtension.bufferView\n\t\t\t\t+ ':' + dracoExtension.indices\n\t\t\t\t+ ':' + createAttributesKey( dracoExtension.attributes );\n\n\t} else {\n\n\t\tgeometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;\n\n\t}\n\n\treturn geometryKey;\n\n}\n\nfunction createAttributesKey( attributes ) {\n\n\tlet attributesKey = '';\n\n\tconst keys = Object.keys( attributes ).sort();\n\n\tfor ( let i = 0, il = keys.length; i < il; i ++ ) {\n\n\t\tattributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';\n\n\t}\n\n\treturn attributesKey;\n\n}\n\nfunction getNormalizedComponentScale( constructor ) {\n\n\t// Reference:\n\t// https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data\n\n\tswitch ( constructor ) {\n\n\t\tcase Int8Array:\n\t\t\treturn 1 / 127;\n\n\t\tcase Uint8Array:\n\t\t\treturn 1 / 255;\n\n\t\tcase Int16Array:\n\t\t\treturn 1 / 32767;\n\n\t\tcase Uint16Array:\n\t\t\treturn 1 / 65535;\n\n\t\tdefault:\n\t\t\tthrow new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' );\n\n\t}\n\n}\n\nfunction getImageURIMimeType( uri ) {\n\n\tif ( uri.search( /\\.jpe?g($|\\?)/i ) > 0 || uri.search( /^data\\:image\\/jpeg/ ) === 0 ) return 'image/jpeg';\n\tif ( uri.search( /\\.webp($|\\?)/i ) > 0 || uri.search( /^data\\:image\\/webp/ ) === 0 ) return 'image/webp';\n\n\treturn 'image/png';\n\n}\n\nconst _identityMatrix = new three__WEBPACK_IMPORTED_MODULE_0__.Matrix4();\n\n/* GLTF PARSER */\n\nclass GLTFParser {\n\n\tconstructor( json = {}, options = {} ) {\n\n\t\tthis.json = json;\n\t\tthis.extensions = {};\n\t\tthis.plugins = {};\n\t\tthis.options = options;\n\n\t\t// loader object cache\n\t\tthis.cache = new GLTFRegistry();\n\n\t\t// associations between Three.js objects and glTF elements\n\t\tthis.associations = new Map();\n\n\t\t// BufferGeometry caching\n\t\tthis.primitiveCache = {};\n\n\t\t// Node cache\n\t\tthis.nodeCache = {};\n\n\t\t// Object3D instance caches\n\t\tthis.meshCache = { refs: {}, uses: {} };\n\t\tthis.cameraCache = { refs: {}, uses: {} };\n\t\tthis.lightCache = { refs: {}, uses: {} };\n\n\t\tthis.sourceCache = {};\n\t\tthis.textureCache = {};\n\n\t\t// Track node names, to ensure no duplicates\n\t\tthis.nodeNamesUsed = {};\n\n\t\t// Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the\n\t\t// expensive work of uploading a texture to the GPU off the main thread.\n\n\t\tlet isSafari = false;\n\t\tlet isFirefox = false;\n\t\tlet firefoxVersion = - 1;\n\n\t\tif ( typeof navigator !== 'undefined' ) {\n\n\t\t\tisSafari = /^((?!chrome|android).)*safari/i.test( navigator.userAgent ) === true;\n\t\t\tisFirefox = navigator.userAgent.indexOf( 'Firefox' ) > - 1;\n\t\t\tfirefoxVersion = isFirefox ? navigator.userAgent.match( /Firefox\\/([0-9]+)\\./ )[ 1 ] : - 1;\n\n\t\t}\n\n\t\tif ( typeof createImageBitmap === 'undefined' || isSafari || ( isFirefox && firefoxVersion < 98 ) ) {\n\n\t\t\tthis.textureLoader = new three__WEBPACK_IMPORTED_MODULE_0__.TextureLoader( this.options.manager );\n\n\t\t} else {\n\n\t\t\tthis.textureLoader = new three__WEBPACK_IMPORTED_MODULE_0__.ImageBitmapLoader( this.options.manager );\n\n\t\t}\n\n\t\tthis.textureLoader.setCrossOrigin( this.options.crossOrigin );\n\t\tthis.textureLoader.setRequestHeader( this.options.requestHeader );\n\n\t\tthis.fileLoader = new three__WEBPACK_IMPORTED_MODULE_0__.FileLoader( this.options.manager );\n\t\tthis.fileLoader.setResponseType( 'arraybuffer' );\n\n\t\tif ( this.options.crossOrigin === 'use-credentials' ) {\n\n\t\t\tthis.fileLoader.setWithCredentials( true );\n\n\t\t}\n\n\t}\n\n\tsetExtensions( extensions ) {\n\n\t\tthis.extensions = extensions;\n\n\t}\n\n\tsetPlugins( plugins ) {\n\n\t\tthis.plugins = plugins;\n\n\t}\n\n\tparse( onLoad, onError ) {\n\n\t\tconst parser = this;\n\t\tconst json = this.json;\n\t\tconst extensions = this.extensions;\n\n\t\t// Clear the loader cache\n\t\tthis.cache.removeAll();\n\t\tthis.nodeCache = {};\n\n\t\t// Mark the special nodes/meshes in json for efficient parse\n\t\tthis._invokeAll( function ( ext ) {\n\n\t\t\treturn ext._markDefs && ext._markDefs();\n\n\t\t} );\n\n\t\tPromise.all( this._invokeAll( function ( ext ) {\n\n\t\t\treturn ext.beforeRoot && ext.beforeRoot();\n\n\t\t} ) ).then( function () {\n\n\t\t\treturn Promise.all( [\n\n\t\t\t\tparser.getDependencies( 'scene' ),\n\t\t\t\tparser.getDependencies( 'animation' ),\n\t\t\t\tparser.getDependencies( 'camera' ),\n\n\t\t\t] );\n\n\t\t} ).then( function ( dependencies ) {\n\n\t\t\tconst result = {\n\t\t\t\tscene: dependencies[ 0 ][ json.scene || 0 ],\n\t\t\t\tscenes: dependencies[ 0 ],\n\t\t\t\tanimations: dependencies[ 1 ],\n\t\t\t\tcameras: dependencies[ 2 ],\n\t\t\t\tasset: json.asset,\n\t\t\t\tparser: parser,\n\t\t\t\tuserData: {}\n\t\t\t};\n\n\t\t\taddUnknownExtensionsToUserData( extensions, result, json );\n\n\t\t\tassignExtrasToUserData( result, json );\n\n\t\t\tPromise.all( parser._invokeAll( function ( ext ) {\n\n\t\t\t\treturn ext.afterRoot && ext.afterRoot( result );\n\n\t\t\t} ) ).then( function () {\n\n\t\t\t\tonLoad( result );\n\n\t\t\t} );\n\n\t\t} ).catch( onError );\n\n\t}\n\n\t/**\n\t * Marks the special nodes/meshes in json for efficient parse.\n\t */\n\t_markDefs() {\n\n\t\tconst nodeDefs = this.json.nodes || [];\n\t\tconst skinDefs = this.json.skins || [];\n\t\tconst meshDefs = this.json.meshes || [];\n\n\t\t// Nothing in the node definition indicates whether it is a Bone or an\n\t\t// Object3D. Use the skins' joint references to mark bones.\n\t\tfor ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {\n\n\t\t\tconst joints = skinDefs[ skinIndex ].joints;\n\n\t\t\tfor ( let i = 0, il = joints.length; i < il; i ++ ) {\n\n\t\t\t\tnodeDefs[ joints[ i ] ].isBone = true;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// Iterate over all nodes, marking references to shared resources,\n\t\t// as well as skeleton joints.\n\t\tfor ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {\n\n\t\t\tconst nodeDef = nodeDefs[ nodeIndex ];\n\n\t\t\tif ( nodeDef.mesh !== undefined ) {\n\n\t\t\t\tthis._addNodeRef( this.meshCache, nodeDef.mesh );\n\n\t\t\t\t// Nothing in the mesh definition indicates whether it is\n\t\t\t\t// a SkinnedMesh or Mesh. Use the node's mesh reference\n\t\t\t\t// to mark SkinnedMesh if node has skin.\n\t\t\t\tif ( nodeDef.skin !== undefined ) {\n\n\t\t\t\t\tmeshDefs[ nodeDef.mesh ].isSkinnedMesh = true;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( nodeDef.camera !== undefined ) {\n\n\t\t\t\tthis._addNodeRef( this.cameraCache, nodeDef.camera );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t/**\n\t * Counts references to shared node / Object3D resources. These resources\n\t * can be reused, or \"instantiated\", at multiple nodes in the scene\n\t * hierarchy. Mesh, Camera, and Light instances are instantiated and must\n\t * be marked. Non-scenegraph resources (like Materials, Geometries, and\n\t * Textures) can be reused directly and are not marked here.\n\t *\n\t * Example: CesiumMilkTruck sample model reuses \"Wheel\" meshes.\n\t */\n\t_addNodeRef( cache, index ) {\n\n\t\tif ( index === undefined ) return;\n\n\t\tif ( cache.refs[ index ] === undefined ) {\n\n\t\t\tcache.refs[ index ] = cache.uses[ index ] = 0;\n\n\t\t}\n\n\t\tcache.refs[ index ] ++;\n\n\t}\n\n\t/** Returns a reference to a shared resource, cloning it if necessary. */\n\t_getNodeRef( cache, index, object ) {\n\n\t\tif ( cache.refs[ index ] <= 1 ) return object;\n\n\t\tconst ref = object.clone();\n\n\t\t// Propagates mappings to the cloned object, prevents mappings on the\n\t\t// original object from being lost.\n\t\tconst updateMappings = ( original, clone ) => {\n\n\t\t\tconst mappings = this.associations.get( original );\n\t\t\tif ( mappings != null ) {\n\n\t\t\t\tthis.associations.set( clone, mappings );\n\n\t\t\t}\n\n\t\t\tfor ( const [ i, child ] of original.children.entries() ) {\n\n\t\t\t\tupdateMappings( child, clone.children[ i ] );\n\n\t\t\t}\n\n\t\t};\n\n\t\tupdateMappings( object, ref );\n\n\t\tref.name += '_instance_' + ( cache.uses[ index ] ++ );\n\n\t\treturn ref;\n\n\t}\n\n\t_invokeOne( func ) {\n\n\t\tconst extensions = Object.values( this.plugins );\n\t\textensions.push( this );\n\n\t\tfor ( let i = 0; i < extensions.length; i ++ ) {\n\n\t\t\tconst result = func( extensions[ i ] );\n\n\t\t\tif ( result ) return result;\n\n\t\t}\n\n\t\treturn null;\n\n\t}\n\n\t_invokeAll( func ) {\n\n\t\tconst extensions = Object.values( this.plugins );\n\t\textensions.unshift( this );\n\n\t\tconst pending = [];\n\n\t\tfor ( let i = 0; i < extensions.length; i ++ ) {\n\n\t\t\tconst result = func( extensions[ i ] );\n\n\t\t\tif ( result ) pending.push( result );\n\n\t\t}\n\n\t\treturn pending;\n\n\t}\n\n\t/**\n\t * Requests the specified dependency asynchronously, with caching.\n\t * @param {string} type\n\t * @param {number} index\n\t * @return {Promise}\n\t */\n\tgetDependency( type, index ) {\n\n\t\tconst cacheKey = type + ':' + index;\n\t\tlet dependency = this.cache.get( cacheKey );\n\n\t\tif ( ! dependency ) {\n\n\t\t\tswitch ( type ) {\n\n\t\t\t\tcase 'scene':\n\t\t\t\t\tdependency = this.loadScene( index );\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'node':\n\t\t\t\t\tdependency = this._invokeOne( function ( ext ) {\n\n\t\t\t\t\t\treturn ext.loadNode && ext.loadNode( index );\n\n\t\t\t\t\t} );\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'mesh':\n\t\t\t\t\tdependency = this._invokeOne( function ( ext ) {\n\n\t\t\t\t\t\treturn ext.loadMesh && ext.loadMesh( index );\n\n\t\t\t\t\t} );\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'accessor':\n\t\t\t\t\tdependency = this.loadAccessor( index );\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'bufferView':\n\t\t\t\t\tdependency = this._invokeOne( function ( ext ) {\n\n\t\t\t\t\t\treturn ext.loadBufferView && ext.loadBufferView( index );\n\n\t\t\t\t\t} );\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'buffer':\n\t\t\t\t\tdependency = this.loadBuffer( index );\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'material':\n\t\t\t\t\tdependency = this._invokeOne( function ( ext ) {\n\n\t\t\t\t\t\treturn ext.loadMaterial && ext.loadMaterial( index );\n\n\t\t\t\t\t} );\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'texture':\n\t\t\t\t\tdependency = this._invokeOne( function ( ext ) {\n\n\t\t\t\t\t\treturn ext.loadTexture && ext.loadTexture( index );\n\n\t\t\t\t\t} );\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'skin':\n\t\t\t\t\tdependency = this.loadSkin( index );\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'animation':\n\t\t\t\t\tdependency = this._invokeOne( function ( ext ) {\n\n\t\t\t\t\t\treturn ext.loadAnimation && ext.loadAnimation( index );\n\n\t\t\t\t\t} );\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'camera':\n\t\t\t\t\tdependency = this.loadCamera( index );\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tdependency = this._invokeOne( function ( ext ) {\n\n\t\t\t\t\t\treturn ext != this && ext.getDependency && ext.getDependency( type, index );\n\n\t\t\t\t\t} );\n\n\t\t\t\t\tif ( ! dependency ) {\n\n\t\t\t\t\t\tthrow new Error( 'Unknown type: ' + type );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\tthis.cache.add( cacheKey, dependency );\n\n\t\t}\n\n\t\treturn dependency;\n\n\t}\n\n\t/**\n\t * Requests all dependencies of the specified type asynchronously, with caching.\n\t * @param {string} type\n\t * @return {Promise>}\n\t */\n\tgetDependencies( type ) {\n\n\t\tlet dependencies = this.cache.get( type );\n\n\t\tif ( ! dependencies ) {\n\n\t\t\tconst parser = this;\n\t\t\tconst defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];\n\n\t\t\tdependencies = Promise.all( defs.map( function ( def, index ) {\n\n\t\t\t\treturn parser.getDependency( type, index );\n\n\t\t\t} ) );\n\n\t\t\tthis.cache.add( type, dependencies );\n\n\t\t}\n\n\t\treturn dependencies;\n\n\t}\n\n\t/**\n\t * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views\n\t * @param {number} bufferIndex\n\t * @return {Promise}\n\t */\n\tloadBuffer( bufferIndex ) {\n\n\t\tconst bufferDef = this.json.buffers[ bufferIndex ];\n\t\tconst loader = this.fileLoader;\n\n\t\tif ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {\n\n\t\t\tthrow new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );\n\n\t\t}\n\n\t\t// If present, GLB container is required to be the first buffer.\n\t\tif ( bufferDef.uri === undefined && bufferIndex === 0 ) {\n\n\t\t\treturn Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );\n\n\t\t}\n\n\t\tconst options = this.options;\n\n\t\treturn new Promise( function ( resolve, reject ) {\n\n\t\t\tloader.load( three__WEBPACK_IMPORTED_MODULE_0__.LoaderUtils.resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {\n\n\t\t\t\treject( new Error( 'THREE.GLTFLoader: Failed to load buffer \"' + bufferDef.uri + '\".' ) );\n\n\t\t\t} );\n\n\t\t} );\n\n\t}\n\n\t/**\n\t * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views\n\t * @param {number} bufferViewIndex\n\t * @return {Promise}\n\t */\n\tloadBufferView( bufferViewIndex ) {\n\n\t\tconst bufferViewDef = this.json.bufferViews[ bufferViewIndex ];\n\n\t\treturn this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {\n\n\t\t\tconst byteLength = bufferViewDef.byteLength || 0;\n\t\t\tconst byteOffset = bufferViewDef.byteOffset || 0;\n\t\t\treturn buffer.slice( byteOffset, byteOffset + byteLength );\n\n\t\t} );\n\n\t}\n\n\t/**\n\t * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors\n\t * @param {number} accessorIndex\n\t * @return {Promise}\n\t */\n\tloadAccessor( accessorIndex ) {\n\n\t\tconst parser = this;\n\t\tconst json = this.json;\n\n\t\tconst accessorDef = this.json.accessors[ accessorIndex ];\n\n\t\tif ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {\n\n\t\t\tconst itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];\n\t\t\tconst TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];\n\t\t\tconst normalized = accessorDef.normalized === true;\n\n\t\t\tconst array = new TypedArray( accessorDef.count * itemSize );\n\t\t\treturn Promise.resolve( new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute( array, itemSize, normalized ) );\n\n\t\t}\n\n\t\tconst pendingBufferViews = [];\n\n\t\tif ( accessorDef.bufferView !== undefined ) {\n\n\t\t\tpendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );\n\n\t\t} else {\n\n\t\t\tpendingBufferViews.push( null );\n\n\t\t}\n\n\t\tif ( accessorDef.sparse !== undefined ) {\n\n\t\t\tpendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );\n\t\t\tpendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );\n\n\t\t}\n\n\t\treturn Promise.all( pendingBufferViews ).then( function ( bufferViews ) {\n\n\t\t\tconst bufferView = bufferViews[ 0 ];\n\n\t\t\tconst itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];\n\t\t\tconst TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];\n\n\t\t\t// For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.\n\t\t\tconst elementBytes = TypedArray.BYTES_PER_ELEMENT;\n\t\t\tconst itemBytes = elementBytes * itemSize;\n\t\t\tconst byteOffset = accessorDef.byteOffset || 0;\n\t\t\tconst byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;\n\t\t\tconst normalized = accessorDef.normalized === true;\n\t\t\tlet array, bufferAttribute;\n\n\t\t\t// The buffer is not interleaved if the stride is the item size in bytes.\n\t\t\tif ( byteStride && byteStride !== itemBytes ) {\n\n\t\t\t\t// Each \"slice\" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer\n\t\t\t\t// This makes sure that IBA.count reflects accessor.count properly\n\t\t\t\tconst ibSlice = Math.floor( byteOffset / byteStride );\n\t\t\t\tconst ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;\n\t\t\t\tlet ib = parser.cache.get( ibCacheKey );\n\n\t\t\t\tif ( ! ib ) {\n\n\t\t\t\t\tarray = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );\n\n\t\t\t\t\t// Integer parameters to IB/IBA are in array elements, not bytes.\n\t\t\t\t\tib = new three__WEBPACK_IMPORTED_MODULE_0__.InterleavedBuffer( array, byteStride / elementBytes );\n\n\t\t\t\t\tparser.cache.add( ibCacheKey, ib );\n\n\t\t\t\t}\n\n\t\t\t\tbufferAttribute = new three__WEBPACK_IMPORTED_MODULE_0__.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );\n\n\t\t\t} else {\n\n\t\t\t\tif ( bufferView === null ) {\n\n\t\t\t\t\tarray = new TypedArray( accessorDef.count * itemSize );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tarray = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );\n\n\t\t\t\t}\n\n\t\t\t\tbufferAttribute = new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute( array, itemSize, normalized );\n\n\t\t\t}\n\n\t\t\t// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors\n\t\t\tif ( accessorDef.sparse !== undefined ) {\n\n\t\t\t\tconst itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;\n\t\t\t\tconst TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];\n\n\t\t\t\tconst byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;\n\t\t\t\tconst byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;\n\n\t\t\t\tconst sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );\n\t\t\t\tconst sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );\n\n\t\t\t\tif ( bufferView !== null ) {\n\n\t\t\t\t\t// Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.\n\t\t\t\t\tbufferAttribute = new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );\n\n\t\t\t\t}\n\n\t\t\t\tfor ( let i = 0, il = sparseIndices.length; i < il; i ++ ) {\n\n\t\t\t\t\tconst index = sparseIndices[ i ];\n\n\t\t\t\t\tbufferAttribute.setX( index, sparseValues[ i * itemSize ] );\n\t\t\t\t\tif ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );\n\t\t\t\t\tif ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );\n\t\t\t\t\tif ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );\n\t\t\t\t\tif ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn bufferAttribute;\n\n\t\t} );\n\n\t}\n\n\t/**\n\t * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures\n\t * @param {number} textureIndex\n\t * @return {Promise}\n\t */\n\tloadTexture( textureIndex ) {\n\n\t\tconst json = this.json;\n\t\tconst options = this.options;\n\t\tconst textureDef = json.textures[ textureIndex ];\n\t\tconst sourceIndex = textureDef.source;\n\t\tconst sourceDef = json.images[ sourceIndex ];\n\n\t\tlet loader = this.textureLoader;\n\n\t\tif ( sourceDef.uri ) {\n\n\t\t\tconst handler = options.manager.getHandler( sourceDef.uri );\n\t\t\tif ( handler !== null ) loader = handler;\n\n\t\t}\n\n\t\treturn this.loadTextureImage( textureIndex, sourceIndex, loader );\n\n\t}\n\n\tloadTextureImage( textureIndex, sourceIndex, loader ) {\n\n\t\tconst parser = this;\n\t\tconst json = this.json;\n\n\t\tconst textureDef = json.textures[ textureIndex ];\n\t\tconst sourceDef = json.images[ sourceIndex ];\n\n\t\tconst cacheKey = ( sourceDef.uri || sourceDef.bufferView ) + ':' + textureDef.sampler;\n\n\t\tif ( this.textureCache[ cacheKey ] ) {\n\n\t\t\t// See https://github.com/mrdoob/three.js/issues/21559.\n\t\t\treturn this.textureCache[ cacheKey ];\n\n\t\t}\n\n\t\tconst promise = this.loadImageSource( sourceIndex, loader ).then( function ( texture ) {\n\n\t\t\ttexture.flipY = false;\n\n\t\t\ttexture.name = textureDef.name || sourceDef.name || '';\n\n\t\t\tif ( texture.name === '' && typeof sourceDef.uri === 'string' && sourceDef.uri.startsWith( 'data:image/' ) === false ) {\n\n\t\t\t\ttexture.name = sourceDef.uri;\n\n\t\t\t}\n\n\t\t\tconst samplers = json.samplers || {};\n\t\t\tconst sampler = samplers[ textureDef.sampler ] || {};\n\n\t\t\ttexture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || three__WEBPACK_IMPORTED_MODULE_0__.LinearFilter;\n\t\t\ttexture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || three__WEBPACK_IMPORTED_MODULE_0__.LinearMipmapLinearFilter;\n\t\t\ttexture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || three__WEBPACK_IMPORTED_MODULE_0__.RepeatWrapping;\n\t\t\ttexture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || three__WEBPACK_IMPORTED_MODULE_0__.RepeatWrapping;\n\n\t\t\tparser.associations.set( texture, { textures: textureIndex } );\n\n\t\t\treturn texture;\n\n\t\t} ).catch( function () {\n\n\t\t\treturn null;\n\n\t\t} );\n\n\t\tthis.textureCache[ cacheKey ] = promise;\n\n\t\treturn promise;\n\n\t}\n\n\tloadImageSource( sourceIndex, loader ) {\n\n\t\tconst parser = this;\n\t\tconst json = this.json;\n\t\tconst options = this.options;\n\n\t\tif ( this.sourceCache[ sourceIndex ] !== undefined ) {\n\n\t\t\treturn this.sourceCache[ sourceIndex ].then( ( texture ) => texture.clone() );\n\n\t\t}\n\n\t\tconst sourceDef = json.images[ sourceIndex ];\n\n\t\tconst URL = self.URL || self.webkitURL;\n\n\t\tlet sourceURI = sourceDef.uri || '';\n\t\tlet isObjectURL = false;\n\n\t\tif ( sourceDef.bufferView !== undefined ) {\n\n\t\t\t// Load binary image data from bufferView, if provided.\n\n\t\t\tsourceURI = parser.getDependency( 'bufferView', sourceDef.bufferView ).then( function ( bufferView ) {\n\n\t\t\t\tisObjectURL = true;\n\t\t\t\tconst blob = new Blob( [ bufferView ], { type: sourceDef.mimeType } );\n\t\t\t\tsourceURI = URL.createObjectURL( blob );\n\t\t\t\treturn sourceURI;\n\n\t\t\t} );\n\n\t\t} else if ( sourceDef.uri === undefined ) {\n\n\t\t\tthrow new Error( 'THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView' );\n\n\t\t}\n\n\t\tconst promise = Promise.resolve( sourceURI ).then( function ( sourceURI ) {\n\n\t\t\treturn new Promise( function ( resolve, reject ) {\n\n\t\t\t\tlet onLoad = resolve;\n\n\t\t\t\tif ( loader.isImageBitmapLoader === true ) {\n\n\t\t\t\t\tonLoad = function ( imageBitmap ) {\n\n\t\t\t\t\t\tconst texture = new three__WEBPACK_IMPORTED_MODULE_0__.Texture( imageBitmap );\n\t\t\t\t\t\ttexture.needsUpdate = true;\n\n\t\t\t\t\t\tresolve( texture );\n\n\t\t\t\t\t};\n\n\t\t\t\t}\n\n\t\t\t\tloader.load( three__WEBPACK_IMPORTED_MODULE_0__.LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject );\n\n\t\t\t} );\n\n\t\t} ).then( function ( texture ) {\n\n\t\t\t// Clean up resources and configure Texture.\n\n\t\t\tif ( isObjectURL === true ) {\n\n\t\t\t\tURL.revokeObjectURL( sourceURI );\n\n\t\t\t}\n\n\t\t\ttexture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType( sourceDef.uri );\n\n\t\t\treturn texture;\n\n\t\t} ).catch( function ( error ) {\n\n\t\t\tconsole.error( 'THREE.GLTFLoader: Couldn\\'t load texture', sourceURI );\n\t\t\tthrow error;\n\n\t\t} );\n\n\t\tthis.sourceCache[ sourceIndex ] = promise;\n\t\treturn promise;\n\n\t}\n\n\t/**\n\t * Asynchronously assigns a texture to the given material parameters.\n\t * @param {Object} materialParams\n\t * @param {string} mapName\n\t * @param {Object} mapDef\n\t * @return {Promise}\n\t */\n\tassignTexture( materialParams, mapName, mapDef, colorSpace ) {\n\n\t\tconst parser = this;\n\n\t\treturn this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {\n\n\t\t\tif ( ! texture ) return null;\n\n\t\t\tif ( mapDef.texCoord !== undefined && mapDef.texCoord > 0 ) {\n\n\t\t\t\ttexture = texture.clone();\n\t\t\t\ttexture.channel = mapDef.texCoord;\n\n\t\t\t}\n\n\t\t\tif ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {\n\n\t\t\t\tconst transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;\n\n\t\t\t\tif ( transform ) {\n\n\t\t\t\t\tconst gltfReference = parser.associations.get( texture );\n\t\t\t\t\ttexture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );\n\t\t\t\t\tparser.associations.set( texture, gltfReference );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( colorSpace !== undefined ) {\n\n\t\t\t\ttexture.colorSpace = colorSpace;\n\n\t\t\t}\n\n\t\t\tmaterialParams[ mapName ] = texture;\n\n\t\t\treturn texture;\n\n\t\t} );\n\n\t}\n\n\t/**\n\t * Assigns final material to a Mesh, Line, or Points instance. The instance\n\t * already has a material (generated from the glTF material options alone)\n\t * but reuse of the same glTF material may require multiple threejs materials\n\t * to accommodate different primitive types, defines, etc. New materials will\n\t * be created if necessary, and reused from a cache.\n\t * @param {Object3D} mesh Mesh, Line, or Points instance.\n\t */\n\tassignFinalMaterial( mesh ) {\n\n\t\tconst geometry = mesh.geometry;\n\t\tlet material = mesh.material;\n\n\t\tconst useDerivativeTangents = geometry.attributes.tangent === undefined;\n\t\tconst useVertexColors = geometry.attributes.color !== undefined;\n\t\tconst useFlatShading = geometry.attributes.normal === undefined;\n\n\t\tif ( mesh.isPoints ) {\n\n\t\t\tconst cacheKey = 'PointsMaterial:' + material.uuid;\n\n\t\t\tlet pointsMaterial = this.cache.get( cacheKey );\n\n\t\t\tif ( ! pointsMaterial ) {\n\n\t\t\t\tpointsMaterial = new three__WEBPACK_IMPORTED_MODULE_0__.PointsMaterial();\n\t\t\t\tthree__WEBPACK_IMPORTED_MODULE_0__.Material.prototype.copy.call( pointsMaterial, material );\n\t\t\t\tpointsMaterial.color.copy( material.color );\n\t\t\t\tpointsMaterial.map = material.map;\n\t\t\t\tpointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px\n\n\t\t\t\tthis.cache.add( cacheKey, pointsMaterial );\n\n\t\t\t}\n\n\t\t\tmaterial = pointsMaterial;\n\n\t\t} else if ( mesh.isLine ) {\n\n\t\t\tconst cacheKey = 'LineBasicMaterial:' + material.uuid;\n\n\t\t\tlet lineMaterial = this.cache.get( cacheKey );\n\n\t\t\tif ( ! lineMaterial ) {\n\n\t\t\t\tlineMaterial = new three__WEBPACK_IMPORTED_MODULE_0__.LineBasicMaterial();\n\t\t\t\tthree__WEBPACK_IMPORTED_MODULE_0__.Material.prototype.copy.call( lineMaterial, material );\n\t\t\t\tlineMaterial.color.copy( material.color );\n\t\t\t\tlineMaterial.map = material.map;\n\n\t\t\t\tthis.cache.add( cacheKey, lineMaterial );\n\n\t\t\t}\n\n\t\t\tmaterial = lineMaterial;\n\n\t\t}\n\n\t\t// Clone the material if it will be modified\n\t\tif ( useDerivativeTangents || useVertexColors || useFlatShading ) {\n\n\t\t\tlet cacheKey = 'ClonedMaterial:' + material.uuid + ':';\n\n\t\t\tif ( useDerivativeTangents ) cacheKey += 'derivative-tangents:';\n\t\t\tif ( useVertexColors ) cacheKey += 'vertex-colors:';\n\t\t\tif ( useFlatShading ) cacheKey += 'flat-shading:';\n\n\t\t\tlet cachedMaterial = this.cache.get( cacheKey );\n\n\t\t\tif ( ! cachedMaterial ) {\n\n\t\t\t\tcachedMaterial = material.clone();\n\n\t\t\t\tif ( useVertexColors ) cachedMaterial.vertexColors = true;\n\t\t\t\tif ( useFlatShading ) cachedMaterial.flatShading = true;\n\n\t\t\t\tif ( useDerivativeTangents ) {\n\n\t\t\t\t\t// https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995\n\t\t\t\t\tif ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= - 1;\n\t\t\t\t\tif ( cachedMaterial.clearcoatNormalScale ) cachedMaterial.clearcoatNormalScale.y *= - 1;\n\n\t\t\t\t}\n\n\t\t\t\tthis.cache.add( cacheKey, cachedMaterial );\n\n\t\t\t\tthis.associations.set( cachedMaterial, this.associations.get( material ) );\n\n\t\t\t}\n\n\t\t\tmaterial = cachedMaterial;\n\n\t\t}\n\n\t\tmesh.material = material;\n\n\t}\n\n\tgetMaterialType( /* materialIndex */ ) {\n\n\t\treturn three__WEBPACK_IMPORTED_MODULE_0__.MeshStandardMaterial;\n\n\t}\n\n\t/**\n\t * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials\n\t * @param {number} materialIndex\n\t * @return {Promise}\n\t */\n\tloadMaterial( materialIndex ) {\n\n\t\tconst parser = this;\n\t\tconst json = this.json;\n\t\tconst extensions = this.extensions;\n\t\tconst materialDef = json.materials[ materialIndex ];\n\n\t\tlet materialType;\n\t\tconst materialParams = {};\n\t\tconst materialExtensions = materialDef.extensions || {};\n\n\t\tconst pending = [];\n\n\t\tif ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {\n\n\t\t\tconst kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];\n\t\t\tmaterialType = kmuExtension.getMaterialType();\n\t\t\tpending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );\n\n\t\t} else {\n\n\t\t\t// Specification:\n\t\t\t// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material\n\n\t\t\tconst metallicRoughness = materialDef.pbrMetallicRoughness || {};\n\n\t\t\tmaterialParams.color = new three__WEBPACK_IMPORTED_MODULE_0__.Color( 1.0, 1.0, 1.0 );\n\t\t\tmaterialParams.opacity = 1.0;\n\n\t\t\tif ( Array.isArray( metallicRoughness.baseColorFactor ) ) {\n\n\t\t\t\tconst array = metallicRoughness.baseColorFactor;\n\n\t\t\t\tmaterialParams.color.fromArray( array );\n\t\t\t\tmaterialParams.opacity = array[ 3 ];\n\n\t\t\t}\n\n\t\t\tif ( metallicRoughness.baseColorTexture !== undefined ) {\n\n\t\t\t\tpending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, three__WEBPACK_IMPORTED_MODULE_0__.SRGBColorSpace ) );\n\n\t\t\t}\n\n\t\t\tmaterialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;\n\t\t\tmaterialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;\n\n\t\t\tif ( metallicRoughness.metallicRoughnessTexture !== undefined ) {\n\n\t\t\t\tpending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );\n\t\t\t\tpending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );\n\n\t\t\t}\n\n\t\t\tmaterialType = this._invokeOne( function ( ext ) {\n\n\t\t\t\treturn ext.getMaterialType && ext.getMaterialType( materialIndex );\n\n\t\t\t} );\n\n\t\t\tpending.push( Promise.all( this._invokeAll( function ( ext ) {\n\n\t\t\t\treturn ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );\n\n\t\t\t} ) ) );\n\n\t\t}\n\n\t\tif ( materialDef.doubleSided === true ) {\n\n\t\t\tmaterialParams.side = three__WEBPACK_IMPORTED_MODULE_0__.DoubleSide;\n\n\t\t}\n\n\t\tconst alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;\n\n\t\tif ( alphaMode === ALPHA_MODES.BLEND ) {\n\n\t\t\tmaterialParams.transparent = true;\n\n\t\t\t// See: https://github.com/mrdoob/three.js/issues/17706\n\t\t\tmaterialParams.depthWrite = false;\n\n\t\t} else {\n\n\t\t\tmaterialParams.transparent = false;\n\n\t\t\tif ( alphaMode === ALPHA_MODES.MASK ) {\n\n\t\t\t\tmaterialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( materialDef.normalTexture !== undefined && materialType !== three__WEBPACK_IMPORTED_MODULE_0__.MeshBasicMaterial ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );\n\n\t\t\tmaterialParams.normalScale = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2( 1, 1 );\n\n\t\t\tif ( materialDef.normalTexture.scale !== undefined ) {\n\n\t\t\t\tconst scale = materialDef.normalTexture.scale;\n\n\t\t\t\tmaterialParams.normalScale.set( scale, scale );\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( materialDef.occlusionTexture !== undefined && materialType !== three__WEBPACK_IMPORTED_MODULE_0__.MeshBasicMaterial ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );\n\n\t\t\tif ( materialDef.occlusionTexture.strength !== undefined ) {\n\n\t\t\t\tmaterialParams.aoMapIntensity = materialDef.occlusionTexture.strength;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( materialDef.emissiveFactor !== undefined && materialType !== three__WEBPACK_IMPORTED_MODULE_0__.MeshBasicMaterial ) {\n\n\t\t\tmaterialParams.emissive = new three__WEBPACK_IMPORTED_MODULE_0__.Color().fromArray( materialDef.emissiveFactor );\n\n\t\t}\n\n\t\tif ( materialDef.emissiveTexture !== undefined && materialType !== three__WEBPACK_IMPORTED_MODULE_0__.MeshBasicMaterial ) {\n\n\t\t\tpending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture, three__WEBPACK_IMPORTED_MODULE_0__.SRGBColorSpace ) );\n\n\t\t}\n\n\t\treturn Promise.all( pending ).then( function () {\n\n\t\t\tconst material = new materialType( materialParams );\n\n\t\t\tif ( materialDef.name ) material.name = materialDef.name;\n\n\t\t\tassignExtrasToUserData( material, materialDef );\n\n\t\t\tparser.associations.set( material, { materials: materialIndex } );\n\n\t\t\tif ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );\n\n\t\t\treturn material;\n\n\t\t} );\n\n\t}\n\n\t/** When Object3D instances are targeted by animation, they need unique names. */\n\tcreateUniqueName( originalName ) {\n\n\t\tconst sanitizedName = three__WEBPACK_IMPORTED_MODULE_0__.PropertyBinding.sanitizeNodeName( originalName || '' );\n\n\t\tlet name = sanitizedName;\n\n\t\tfor ( let i = 1; this.nodeNamesUsed[ name ]; ++ i ) {\n\n\t\t\tname = sanitizedName + '_' + i;\n\n\t\t}\n\n\t\tthis.nodeNamesUsed[ name ] = true;\n\n\t\treturn name;\n\n\t}\n\n\t/**\n\t * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry\n\t *\n\t * Creates BufferGeometries from primitives.\n\t *\n\t * @param {Array} primitives\n\t * @return {Promise>}\n\t */\n\tloadGeometries( primitives ) {\n\n\t\tconst parser = this;\n\t\tconst extensions = this.extensions;\n\t\tconst cache = this.primitiveCache;\n\n\t\tfunction createDracoPrimitive( primitive ) {\n\n\t\t\treturn extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]\n\t\t\t\t.decodePrimitive( primitive, parser )\n\t\t\t\t.then( function ( geometry ) {\n\n\t\t\t\t\treturn addPrimitiveAttributes( geometry, primitive, parser );\n\n\t\t\t\t} );\n\n\t\t}\n\n\t\tconst pending = [];\n\n\t\tfor ( let i = 0, il = primitives.length; i < il; i ++ ) {\n\n\t\t\tconst primitive = primitives[ i ];\n\t\t\tconst cacheKey = createPrimitiveKey( primitive );\n\n\t\t\t// See if we've already created this geometry\n\t\t\tconst cached = cache[ cacheKey ];\n\n\t\t\tif ( cached ) {\n\n\t\t\t\t// Use the cached geometry if it exists\n\t\t\t\tpending.push( cached.promise );\n\n\t\t\t} else {\n\n\t\t\t\tlet geometryPromise;\n\n\t\t\t\tif ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {\n\n\t\t\t\t\t// Use DRACO geometry if available\n\t\t\t\t\tgeometryPromise = createDracoPrimitive( primitive );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// Otherwise create a new geometry\n\t\t\t\t\tgeometryPromise = addPrimitiveAttributes( new three__WEBPACK_IMPORTED_MODULE_0__.BufferGeometry(), primitive, parser );\n\n\t\t\t\t}\n\n\t\t\t\t// Cache this geometry\n\t\t\t\tcache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };\n\n\t\t\t\tpending.push( geometryPromise );\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn Promise.all( pending );\n\n\t}\n\n\t/**\n\t * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes\n\t * @param {number} meshIndex\n\t * @return {Promise}\n\t */\n\tloadMesh( meshIndex ) {\n\n\t\tconst parser = this;\n\t\tconst json = this.json;\n\t\tconst extensions = this.extensions;\n\n\t\tconst meshDef = json.meshes[ meshIndex ];\n\t\tconst primitives = meshDef.primitives;\n\n\t\tconst pending = [];\n\n\t\tfor ( let i = 0, il = primitives.length; i < il; i ++ ) {\n\n\t\t\tconst material = primitives[ i ].material === undefined\n\t\t\t\t? createDefaultMaterial( this.cache )\n\t\t\t\t: this.getDependency( 'material', primitives[ i ].material );\n\n\t\t\tpending.push( material );\n\n\t\t}\n\n\t\tpending.push( parser.loadGeometries( primitives ) );\n\n\t\treturn Promise.all( pending ).then( function ( results ) {\n\n\t\t\tconst materials = results.slice( 0, results.length - 1 );\n\t\t\tconst geometries = results[ results.length - 1 ];\n\n\t\t\tconst meshes = [];\n\n\t\t\tfor ( let i = 0, il = geometries.length; i < il; i ++ ) {\n\n\t\t\t\tconst geometry = geometries[ i ];\n\t\t\t\tconst primitive = primitives[ i ];\n\n\t\t\t\t// 1. create Mesh\n\n\t\t\t\tlet mesh;\n\n\t\t\t\tconst material = materials[ i ];\n\n\t\t\t\tif ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||\n\t\t\t\t\t\tprimitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||\n\t\t\t\t\t\tprimitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||\n\t\t\t\t\t\tprimitive.mode === undefined ) {\n\n\t\t\t\t\t// .isSkinnedMesh isn't in glTF spec. See ._markDefs()\n\t\t\t\t\tmesh = meshDef.isSkinnedMesh === true\n\t\t\t\t\t\t? new three__WEBPACK_IMPORTED_MODULE_0__.SkinnedMesh( geometry, material )\n\t\t\t\t\t\t: new three__WEBPACK_IMPORTED_MODULE_0__.Mesh( geometry, material );\n\n\t\t\t\t\tif ( mesh.isSkinnedMesh === true ) {\n\n\t\t\t\t\t\t// normalize skin weights to fix malformed assets (see #15319)\n\t\t\t\t\t\tmesh.normalizeSkinWeights();\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {\n\n\t\t\t\t\t\tmesh.geometry = (0,_utils_BufferGeometryUtils_js__WEBPACK_IMPORTED_MODULE_1__.toTrianglesDrawMode)( mesh.geometry, three__WEBPACK_IMPORTED_MODULE_0__.TriangleStripDrawMode );\n\n\t\t\t\t\t} else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {\n\n\t\t\t\t\t\tmesh.geometry = (0,_utils_BufferGeometryUtils_js__WEBPACK_IMPORTED_MODULE_1__.toTrianglesDrawMode)( mesh.geometry, three__WEBPACK_IMPORTED_MODULE_0__.TriangleFanDrawMode );\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {\n\n\t\t\t\t\tmesh = new three__WEBPACK_IMPORTED_MODULE_0__.LineSegments( geometry, material );\n\n\t\t\t\t} else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {\n\n\t\t\t\t\tmesh = new three__WEBPACK_IMPORTED_MODULE_0__.Line( geometry, material );\n\n\t\t\t\t} else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {\n\n\t\t\t\t\tmesh = new three__WEBPACK_IMPORTED_MODULE_0__.LineLoop( geometry, material );\n\n\t\t\t\t} else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {\n\n\t\t\t\t\tmesh = new three__WEBPACK_IMPORTED_MODULE_0__.Points( geometry, material );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tthrow new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );\n\n\t\t\t\t}\n\n\t\t\t\tif ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {\n\n\t\t\t\t\tupdateMorphTargets( mesh, meshDef );\n\n\t\t\t\t}\n\n\t\t\t\tmesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );\n\n\t\t\t\tassignExtrasToUserData( mesh, meshDef );\n\n\t\t\t\tif ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );\n\n\t\t\t\tparser.assignFinalMaterial( mesh );\n\n\t\t\t\tmeshes.push( mesh );\n\n\t\t\t}\n\n\t\t\tfor ( let i = 0, il = meshes.length; i < il; i ++ ) {\n\n\t\t\t\tparser.associations.set( meshes[ i ], {\n\t\t\t\t\tmeshes: meshIndex,\n\t\t\t\t\tprimitives: i\n\t\t\t\t} );\n\n\t\t\t}\n\n\t\t\tif ( meshes.length === 1 ) {\n\n\t\t\t\treturn meshes[ 0 ];\n\n\t\t\t}\n\n\t\t\tconst group = new three__WEBPACK_IMPORTED_MODULE_0__.Group();\n\n\t\t\tparser.associations.set( group, { meshes: meshIndex } );\n\n\t\t\tfor ( let i = 0, il = meshes.length; i < il; i ++ ) {\n\n\t\t\t\tgroup.add( meshes[ i ] );\n\n\t\t\t}\n\n\t\t\treturn group;\n\n\t\t} );\n\n\t}\n\n\t/**\n\t * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras\n\t * @param {number} cameraIndex\n\t * @return {Promise}\n\t */\n\tloadCamera( cameraIndex ) {\n\n\t\tlet camera;\n\t\tconst cameraDef = this.json.cameras[ cameraIndex ];\n\t\tconst params = cameraDef[ cameraDef.type ];\n\n\t\tif ( ! params ) {\n\n\t\t\tconsole.warn( 'THREE.GLTFLoader: Missing camera parameters.' );\n\t\t\treturn;\n\n\t\t}\n\n\t\tif ( cameraDef.type === 'perspective' ) {\n\n\t\t\tcamera = new three__WEBPACK_IMPORTED_MODULE_0__.PerspectiveCamera( three__WEBPACK_IMPORTED_MODULE_0__.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );\n\n\t\t} else if ( cameraDef.type === 'orthographic' ) {\n\n\t\t\tcamera = new three__WEBPACK_IMPORTED_MODULE_0__.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );\n\n\t\t}\n\n\t\tif ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );\n\n\t\tassignExtrasToUserData( camera, cameraDef );\n\n\t\treturn Promise.resolve( camera );\n\n\t}\n\n\t/**\n\t * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins\n\t * @param {number} skinIndex\n\t * @return {Promise}\n\t */\n\tloadSkin( skinIndex ) {\n\n\t\tconst skinDef = this.json.skins[ skinIndex ];\n\n\t\tconst pending = [];\n\n\t\tfor ( let i = 0, il = skinDef.joints.length; i < il; i ++ ) {\n\n\t\t\tpending.push( this._loadNodeShallow( skinDef.joints[ i ] ) );\n\n\t\t}\n\n\t\tif ( skinDef.inverseBindMatrices !== undefined ) {\n\n\t\t\tpending.push( this.getDependency( 'accessor', skinDef.inverseBindMatrices ) );\n\n\t\t} else {\n\n\t\t\tpending.push( null );\n\n\t\t}\n\n\t\treturn Promise.all( pending ).then( function ( results ) {\n\n\t\t\tconst inverseBindMatrices = results.pop();\n\t\t\tconst jointNodes = results;\n\n\t\t\t// Note that bones (joint nodes) may or may not be in the\n\t\t\t// scene graph at this time.\n\n\t\t\tconst bones = [];\n\t\t\tconst boneInverses = [];\n\n\t\t\tfor ( let i = 0, il = jointNodes.length; i < il; i ++ ) {\n\n\t\t\t\tconst jointNode = jointNodes[ i ];\n\n\t\t\t\tif ( jointNode ) {\n\n\t\t\t\t\tbones.push( jointNode );\n\n\t\t\t\t\tconst mat = new three__WEBPACK_IMPORTED_MODULE_0__.Matrix4();\n\n\t\t\t\t\tif ( inverseBindMatrices !== null ) {\n\n\t\t\t\t\t\tmat.fromArray( inverseBindMatrices.array, i * 16 );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tboneInverses.push( mat );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tconsole.warn( 'THREE.GLTFLoader: Joint \"%s\" could not be found.', skinDef.joints[ i ] );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn new three__WEBPACK_IMPORTED_MODULE_0__.Skeleton( bones, boneInverses );\n\n\t\t} );\n\n\t}\n\n\t/**\n\t * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations\n\t * @param {number} animationIndex\n\t * @return {Promise}\n\t */\n\tloadAnimation( animationIndex ) {\n\n\t\tconst json = this.json;\n\n\t\tconst animationDef = json.animations[ animationIndex ];\n\t\tconst animationName = animationDef.name ? animationDef.name : 'animation_' + animationIndex;\n\n\t\tconst pendingNodes = [];\n\t\tconst pendingInputAccessors = [];\n\t\tconst pendingOutputAccessors = [];\n\t\tconst pendingSamplers = [];\n\t\tconst pendingTargets = [];\n\n\t\tfor ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) {\n\n\t\t\tconst channel = animationDef.channels[ i ];\n\t\t\tconst sampler = animationDef.samplers[ channel.sampler ];\n\t\t\tconst target = channel.target;\n\t\t\tconst name = target.node;\n\t\t\tconst input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;\n\t\t\tconst output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;\n\n\t\t\tif ( target.node === undefined ) continue;\n\n\t\t\tpendingNodes.push( this.getDependency( 'node', name ) );\n\t\t\tpendingInputAccessors.push( this.getDependency( 'accessor', input ) );\n\t\t\tpendingOutputAccessors.push( this.getDependency( 'accessor', output ) );\n\t\t\tpendingSamplers.push( sampler );\n\t\t\tpendingTargets.push( target );\n\n\t\t}\n\n\t\treturn Promise.all( [\n\n\t\t\tPromise.all( pendingNodes ),\n\t\t\tPromise.all( pendingInputAccessors ),\n\t\t\tPromise.all( pendingOutputAccessors ),\n\t\t\tPromise.all( pendingSamplers ),\n\t\t\tPromise.all( pendingTargets )\n\n\t\t] ).then( function ( dependencies ) {\n\n\t\t\tconst nodes = dependencies[ 0 ];\n\t\t\tconst inputAccessors = dependencies[ 1 ];\n\t\t\tconst outputAccessors = dependencies[ 2 ];\n\t\t\tconst samplers = dependencies[ 3 ];\n\t\t\tconst targets = dependencies[ 4 ];\n\n\t\t\tconst tracks = [];\n\n\t\t\tfor ( let i = 0, il = nodes.length; i < il; i ++ ) {\n\n\t\t\t\tconst node = nodes[ i ];\n\t\t\t\tconst inputAccessor = inputAccessors[ i ];\n\t\t\t\tconst outputAccessor = outputAccessors[ i ];\n\t\t\t\tconst sampler = samplers[ i ];\n\t\t\t\tconst target = targets[ i ];\n\n\t\t\t\tif ( node === undefined ) continue;\n\n\t\t\t\tnode.updateMatrix();\n\n\t\t\t\tlet TypedKeyframeTrack;\n\n\t\t\t\tswitch ( PATH_PROPERTIES[ target.path ] ) {\n\n\t\t\t\t\tcase PATH_PROPERTIES.weights:\n\n\t\t\t\t\t\tTypedKeyframeTrack = three__WEBPACK_IMPORTED_MODULE_0__.NumberKeyframeTrack;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase PATH_PROPERTIES.rotation:\n\n\t\t\t\t\t\tTypedKeyframeTrack = three__WEBPACK_IMPORTED_MODULE_0__.QuaternionKeyframeTrack;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase PATH_PROPERTIES.position:\n\t\t\t\t\tcase PATH_PROPERTIES.scale:\n\t\t\t\t\tdefault:\n\n\t\t\t\t\t\tTypedKeyframeTrack = three__WEBPACK_IMPORTED_MODULE_0__.VectorKeyframeTrack;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t\tconst targetName = node.name ? node.name : node.uuid;\n\n\t\t\t\tconst interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : three__WEBPACK_IMPORTED_MODULE_0__.InterpolateLinear;\n\n\t\t\t\tconst targetNames = [];\n\n\t\t\t\tif ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {\n\n\t\t\t\t\tnode.traverse( function ( object ) {\n\n\t\t\t\t\t\tif ( object.morphTargetInfluences ) {\n\n\t\t\t\t\t\t\ttargetNames.push( object.name ? object.name : object.uuid );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} );\n\n\t\t\t\t} else {\n\n\t\t\t\t\ttargetNames.push( targetName );\n\n\t\t\t\t}\n\n\t\t\t\tlet outputArray = outputAccessor.array;\n\n\t\t\t\tif ( outputAccessor.normalized ) {\n\n\t\t\t\t\tconst scale = getNormalizedComponentScale( outputArray.constructor );\n\t\t\t\t\tconst scaled = new Float32Array( outputArray.length );\n\n\t\t\t\t\tfor ( let j = 0, jl = outputArray.length; j < jl; j ++ ) {\n\n\t\t\t\t\t\tscaled[ j ] = outputArray[ j ] * scale;\n\n\t\t\t\t\t}\n\n\t\t\t\t\toutputArray = scaled;\n\n\t\t\t\t}\n\n\t\t\t\tfor ( let j = 0, jl = targetNames.length; j < jl; j ++ ) {\n\n\t\t\t\t\tconst track = new TypedKeyframeTrack(\n\t\t\t\t\t\ttargetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],\n\t\t\t\t\t\tinputAccessor.array,\n\t\t\t\t\t\toutputArray,\n\t\t\t\t\t\tinterpolation\n\t\t\t\t\t);\n\n\t\t\t\t\t// Override interpolation with custom factory method.\n\t\t\t\t\tif ( sampler.interpolation === 'CUBICSPLINE' ) {\n\n\t\t\t\t\t\ttrack.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {\n\n\t\t\t\t\t\t\t// A CUBICSPLINE keyframe in glTF has three output values for each input value,\n\t\t\t\t\t\t\t// representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()\n\t\t\t\t\t\t\t// must be divided by three to get the interpolant's sampleSize argument.\n\n\t\t\t\t\t\t\tconst interpolantType = ( this instanceof three__WEBPACK_IMPORTED_MODULE_0__.QuaternionKeyframeTrack ) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;\n\n\t\t\t\t\t\t\treturn new interpolantType( this.times, this.values, this.getValueSize() / 3, result );\n\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.\n\t\t\t\t\t\ttrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;\n\n\t\t\t\t\t}\n\n\t\t\t\t\ttracks.push( track );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn new three__WEBPACK_IMPORTED_MODULE_0__.AnimationClip( animationName, undefined, tracks );\n\n\t\t} );\n\n\t}\n\n\tcreateNodeMesh( nodeIndex ) {\n\n\t\tconst json = this.json;\n\t\tconst parser = this;\n\t\tconst nodeDef = json.nodes[ nodeIndex ];\n\n\t\tif ( nodeDef.mesh === undefined ) return null;\n\n\t\treturn parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {\n\n\t\t\tconst node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );\n\n\t\t\t// if weights are provided on the node, override weights on the mesh.\n\t\t\tif ( nodeDef.weights !== undefined ) {\n\n\t\t\t\tnode.traverse( function ( o ) {\n\n\t\t\t\t\tif ( ! o.isMesh ) return;\n\n\t\t\t\t\tfor ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) {\n\n\t\t\t\t\t\to.morphTargetInfluences[ i ] = nodeDef.weights[ i ];\n\n\t\t\t\t\t}\n\n\t\t\t\t} );\n\n\t\t\t}\n\n\t\t\treturn node;\n\n\t\t} );\n\n\t}\n\n\t/**\n\t * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy\n\t * @param {number} nodeIndex\n\t * @return {Promise}\n\t */\n\tloadNode( nodeIndex ) {\n\n\t\tconst json = this.json;\n\t\tconst parser = this;\n\n\t\tconst nodeDef = json.nodes[ nodeIndex ];\n\n\t\tconst nodePending = parser._loadNodeShallow( nodeIndex );\n\n\t\tconst childPending = [];\n\t\tconst childrenDef = nodeDef.children || [];\n\n\t\tfor ( let i = 0, il = childrenDef.length; i < il; i ++ ) {\n\n\t\t\tchildPending.push( parser.getDependency( 'node', childrenDef[ i ] ) );\n\n\t\t}\n\n\t\tconst skeletonPending = nodeDef.skin === undefined\n\t\t\t? Promise.resolve( null )\n\t\t\t: parser.getDependency( 'skin', nodeDef.skin );\n\n\t\treturn Promise.all( [\n\t\t\tnodePending,\n\t\t\tPromise.all( childPending ),\n\t\t\tskeletonPending\n\t\t] ).then( function ( results ) {\n\n\t\t\tconst node = results[ 0 ];\n\t\t\tconst children = results[ 1 ];\n\t\t\tconst skeleton = results[ 2 ];\n\n\t\t\tif ( skeleton !== null ) {\n\n\t\t\t\t// This full traverse should be fine because\n\t\t\t\t// child glTF nodes have not been added to this node yet.\n\t\t\t\tnode.traverse( function ( mesh ) {\n\n\t\t\t\t\tif ( ! mesh.isSkinnedMesh ) return;\n\n\t\t\t\t\tmesh.bind( skeleton, _identityMatrix );\n\n\t\t\t\t} );\n\n\t\t\t}\n\n\t\t\tfor ( let i = 0, il = children.length; i < il; i ++ ) {\n\n\t\t\t\tnode.add( children[ i ] );\n\n\t\t\t}\n\n\t\t\treturn node;\n\n\t\t} );\n\n\t}\n\n\t// ._loadNodeShallow() parses a single node.\n\t// skin and child nodes are created and added in .loadNode() (no '_' prefix).\n\t_loadNodeShallow( nodeIndex ) {\n\n\t\tconst json = this.json;\n\t\tconst extensions = this.extensions;\n\t\tconst parser = this;\n\n\t\t// This method is called from .loadNode() and .loadSkin().\n\t\t// Cache a node to avoid duplication.\n\n\t\tif ( this.nodeCache[ nodeIndex ] !== undefined ) {\n\n\t\t\treturn this.nodeCache[ nodeIndex ];\n\n\t\t}\n\n\t\tconst nodeDef = json.nodes[ nodeIndex ];\n\n\t\t// reserve node's name before its dependencies, so the root has the intended name.\n\t\tconst nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';\n\n\t\tconst pending = [];\n\n\t\tconst meshPromise = parser._invokeOne( function ( ext ) {\n\n\t\t\treturn ext.createNodeMesh && ext.createNodeMesh( nodeIndex );\n\n\t\t} );\n\n\t\tif ( meshPromise ) {\n\n\t\t\tpending.push( meshPromise );\n\n\t\t}\n\n\t\tif ( nodeDef.camera !== undefined ) {\n\n\t\t\tpending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {\n\n\t\t\t\treturn parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );\n\n\t\t\t} ) );\n\n\t\t}\n\n\t\tparser._invokeAll( function ( ext ) {\n\n\t\t\treturn ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );\n\n\t\t} ).forEach( function ( promise ) {\n\n\t\t\tpending.push( promise );\n\n\t\t} );\n\n\t\tthis.nodeCache[ nodeIndex ] = Promise.all( pending ).then( function ( objects ) {\n\n\t\t\tlet node;\n\n\t\t\t// .isBone isn't in glTF spec. See ._markDefs\n\t\t\tif ( nodeDef.isBone === true ) {\n\n\t\t\t\tnode = new three__WEBPACK_IMPORTED_MODULE_0__.Bone();\n\n\t\t\t} else if ( objects.length > 1 ) {\n\n\t\t\t\tnode = new three__WEBPACK_IMPORTED_MODULE_0__.Group();\n\n\t\t\t} else if ( objects.length === 1 ) {\n\n\t\t\t\tnode = objects[ 0 ];\n\n\t\t\t} else {\n\n\t\t\t\tnode = new three__WEBPACK_IMPORTED_MODULE_0__.Object3D();\n\n\t\t\t}\n\n\t\t\tif ( node !== objects[ 0 ] ) {\n\n\t\t\t\tfor ( let i = 0, il = objects.length; i < il; i ++ ) {\n\n\t\t\t\t\tnode.add( objects[ i ] );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( nodeDef.name ) {\n\n\t\t\t\tnode.userData.name = nodeDef.name;\n\t\t\t\tnode.name = nodeName;\n\n\t\t\t}\n\n\t\t\tassignExtrasToUserData( node, nodeDef );\n\n\t\t\tif ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );\n\n\t\t\tif ( nodeDef.matrix !== undefined ) {\n\n\t\t\t\tconst matrix = new three__WEBPACK_IMPORTED_MODULE_0__.Matrix4();\n\t\t\t\tmatrix.fromArray( nodeDef.matrix );\n\t\t\t\tnode.applyMatrix4( matrix );\n\n\t\t\t} else {\n\n\t\t\t\tif ( nodeDef.translation !== undefined ) {\n\n\t\t\t\t\tnode.position.fromArray( nodeDef.translation );\n\n\t\t\t\t}\n\n\t\t\t\tif ( nodeDef.rotation !== undefined ) {\n\n\t\t\t\t\tnode.quaternion.fromArray( nodeDef.rotation );\n\n\t\t\t\t}\n\n\t\t\t\tif ( nodeDef.scale !== undefined ) {\n\n\t\t\t\t\tnode.scale.fromArray( nodeDef.scale );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ( ! parser.associations.has( node ) ) {\n\n\t\t\t\tparser.associations.set( node, {} );\n\n\t\t\t}\n\n\t\t\tparser.associations.get( node ).nodes = nodeIndex;\n\n\t\t\treturn node;\n\n\t\t} );\n\n\t\treturn this.nodeCache[ nodeIndex ];\n\n\t}\n\n\t/**\n\t * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes\n\t * @param {number} sceneIndex\n\t * @return {Promise}\n\t */\n\tloadScene( sceneIndex ) {\n\n\t\tconst extensions = this.extensions;\n\t\tconst sceneDef = this.json.scenes[ sceneIndex ];\n\t\tconst parser = this;\n\n\t\t// Loader returns Group, not Scene.\n\t\t// See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172\n\t\tconst scene = new three__WEBPACK_IMPORTED_MODULE_0__.Group();\n\t\tif ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );\n\n\t\tassignExtrasToUserData( scene, sceneDef );\n\n\t\tif ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );\n\n\t\tconst nodeIds = sceneDef.nodes || [];\n\n\t\tconst pending = [];\n\n\t\tfor ( let i = 0, il = nodeIds.length; i < il; i ++ ) {\n\n\t\t\tpending.push( parser.getDependency( 'node', nodeIds[ i ] ) );\n\n\t\t}\n\n\t\treturn Promise.all( pending ).then( function ( nodes ) {\n\n\t\t\tfor ( let i = 0, il = nodes.length; i < il; i ++ ) {\n\n\t\t\t\tscene.add( nodes[ i ] );\n\n\t\t\t}\n\n\t\t\t// Removes dangling associations, associations that reference a node that\n\t\t\t// didn't make it into the scene.\n\t\t\tconst reduceAssociations = ( node ) => {\n\n\t\t\t\tconst reducedAssociations = new Map();\n\n\t\t\t\tfor ( const [ key, value ] of parser.associations ) {\n\n\t\t\t\t\tif ( key instanceof three__WEBPACK_IMPORTED_MODULE_0__.Material || key instanceof three__WEBPACK_IMPORTED_MODULE_0__.Texture ) {\n\n\t\t\t\t\t\treducedAssociations.set( key, value );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tnode.traverse( ( node ) => {\n\n\t\t\t\t\tconst mappings = parser.associations.get( node );\n\n\t\t\t\t\tif ( mappings != null ) {\n\n\t\t\t\t\t\treducedAssociations.set( node, mappings );\n\n\t\t\t\t\t}\n\n\t\t\t\t} );\n\n\t\t\t\treturn reducedAssociations;\n\n\t\t\t};\n\n\t\t\tparser.associations = reduceAssociations( scene );\n\n\t\t\treturn scene;\n\n\t\t} );\n\n\t}\n\n}\n\n/**\n * @param {BufferGeometry} geometry\n * @param {GLTF.Primitive} primitiveDef\n * @param {GLTFParser} parser\n */\nfunction computeBounds( geometry, primitiveDef, parser ) {\n\n\tconst attributes = primitiveDef.attributes;\n\n\tconst box = new three__WEBPACK_IMPORTED_MODULE_0__.Box3();\n\n\tif ( attributes.POSITION !== undefined ) {\n\n\t\tconst accessor = parser.json.accessors[ attributes.POSITION ];\n\n\t\tconst min = accessor.min;\n\t\tconst max = accessor.max;\n\n\t\t// glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.\n\n\t\tif ( min !== undefined && max !== undefined ) {\n\n\t\t\tbox.set(\n\t\t\t\tnew three__WEBPACK_IMPORTED_MODULE_0__.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),\n\t\t\t\tnew three__WEBPACK_IMPORTED_MODULE_0__.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] )\n\t\t\t);\n\n\t\t\tif ( accessor.normalized ) {\n\n\t\t\t\tconst boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );\n\t\t\t\tbox.min.multiplyScalar( boxScale );\n\t\t\t\tbox.max.multiplyScalar( boxScale );\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tconsole.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );\n\n\t\t\treturn;\n\n\t\t}\n\n\t} else {\n\n\t\treturn;\n\n\t}\n\n\tconst targets = primitiveDef.targets;\n\n\tif ( targets !== undefined ) {\n\n\t\tconst maxDisplacement = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\t\tconst vector = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\n\t\tfor ( let i = 0, il = targets.length; i < il; i ++ ) {\n\n\t\t\tconst target = targets[ i ];\n\n\t\t\tif ( target.POSITION !== undefined ) {\n\n\t\t\t\tconst accessor = parser.json.accessors[ target.POSITION ];\n\t\t\t\tconst min = accessor.min;\n\t\t\t\tconst max = accessor.max;\n\n\t\t\t\t// glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.\n\n\t\t\t\tif ( min !== undefined && max !== undefined ) {\n\n\t\t\t\t\t// we need to get max of absolute components because target weight is [-1,1]\n\t\t\t\t\tvector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );\n\t\t\t\t\tvector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );\n\t\t\t\t\tvector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );\n\n\n\t\t\t\t\tif ( accessor.normalized ) {\n\n\t\t\t\t\t\tconst boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );\n\t\t\t\t\t\tvector.multiplyScalar( boxScale );\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative\n\t\t\t\t\t// to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets\n\t\t\t\t\t// are used to implement key-frame animations and as such only two are active at a time - this results in very large\n\t\t\t\t\t// boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.\n\t\t\t\t\tmaxDisplacement.max( vector );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tconsole.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\t// As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.\n\t\tbox.expandByVector( maxDisplacement );\n\n\t}\n\n\tgeometry.boundingBox = box;\n\n\tconst sphere = new three__WEBPACK_IMPORTED_MODULE_0__.Sphere();\n\n\tbox.getCenter( sphere.center );\n\tsphere.radius = box.min.distanceTo( box.max ) / 2;\n\n\tgeometry.boundingSphere = sphere;\n\n}\n\n/**\n * @param {BufferGeometry} geometry\n * @param {GLTF.Primitive} primitiveDef\n * @param {GLTFParser} parser\n * @return {Promise}\n */\nfunction addPrimitiveAttributes( geometry, primitiveDef, parser ) {\n\n\tconst attributes = primitiveDef.attributes;\n\n\tconst pending = [];\n\n\tfunction assignAttributeAccessor( accessorIndex, attributeName ) {\n\n\t\treturn parser.getDependency( 'accessor', accessorIndex )\n\t\t\t.then( function ( accessor ) {\n\n\t\t\t\tgeometry.setAttribute( attributeName, accessor );\n\n\t\t\t} );\n\n\t}\n\n\tfor ( const gltfAttributeName in attributes ) {\n\n\t\tconst threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();\n\n\t\t// Skip attributes already provided by e.g. Draco extension.\n\t\tif ( threeAttributeName in geometry.attributes ) continue;\n\n\t\tpending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );\n\n\t}\n\n\tif ( primitiveDef.indices !== undefined && ! geometry.index ) {\n\n\t\tconst accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {\n\n\t\t\tgeometry.setIndex( accessor );\n\n\t\t} );\n\n\t\tpending.push( accessor );\n\n\t}\n\n\tassignExtrasToUserData( geometry, primitiveDef );\n\n\tcomputeBounds( geometry, primitiveDef, parser );\n\n\treturn Promise.all( pending ).then( function () {\n\n\t\treturn primitiveDef.targets !== undefined\n\t\t\t? addMorphTargets( geometry, primitiveDef.targets, parser )\n\t\t\t: geometry;\n\n\t} );\n\n}\n\n\n\n\n//# sourceURL=webpack://MaterialXView/./node_modules/three/examples/jsm/loaders/GLTFLoader.js?"); + +/***/ }), + +/***/ "./node_modules/three/examples/jsm/loaders/RGBELoader.js": +/*!***************************************************************!*\ + !*** ./node_modules/three/examples/jsm/loaders/RGBELoader.js ***! + \***************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RGBELoader: () => (/* binding */ RGBELoader)\n/* harmony export */ });\n/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! three */ \"./node_modules/three/build/three.module.js\");\n\n\n// https://github.com/mrdoob/three.js/issues/5552\n// http://en.wikipedia.org/wiki/RGBE_image_format\n\nclass RGBELoader extends three__WEBPACK_IMPORTED_MODULE_0__.DataTextureLoader {\n\n\tconstructor( manager ) {\n\n\t\tsuper( manager );\n\n\t\tthis.type = three__WEBPACK_IMPORTED_MODULE_0__.HalfFloatType;\n\n\t}\n\n\t// adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html\n\n\tparse( buffer ) {\n\n\t\tconst\n\t\t\t/* return codes for rgbe routines */\n\t\t\t//RGBE_RETURN_SUCCESS = 0,\n\t\t\tRGBE_RETURN_FAILURE = - 1,\n\n\t\t\t/* default error routine. change this to change error handling */\n\t\t\trgbe_read_error = 1,\n\t\t\trgbe_write_error = 2,\n\t\t\trgbe_format_error = 3,\n\t\t\trgbe_memory_error = 4,\n\t\t\trgbe_error = function ( rgbe_error_code, msg ) {\n\n\t\t\t\tswitch ( rgbe_error_code ) {\n\n\t\t\t\t\tcase rgbe_read_error: console.error( 'THREE.RGBELoader Read Error: ' + ( msg || '' ) );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase rgbe_write_error: console.error( 'THREE.RGBELoader Write Error: ' + ( msg || '' ) );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase rgbe_format_error: console.error( 'THREE.RGBELoader Bad File Format: ' + ( msg || '' ) );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\tcase rgbe_memory_error: console.error( 'THREE.RGBELoader: Error: ' + ( msg || '' ) );\n\n\t\t\t\t}\n\n\t\t\t\treturn RGBE_RETURN_FAILURE;\n\n\t\t\t},\n\n\t\t\t/* offsets to red, green, and blue components in a data (float) pixel */\n\t\t\t//RGBE_DATA_RED = 0,\n\t\t\t//RGBE_DATA_GREEN = 1,\n\t\t\t//RGBE_DATA_BLUE = 2,\n\n\t\t\t/* number of floats per pixel, use 4 since stored in rgba image format */\n\t\t\t//RGBE_DATA_SIZE = 4,\n\n\t\t\t/* flags indicating which fields in an rgbe_header_info are valid */\n\t\t\tRGBE_VALID_PROGRAMTYPE = 1,\n\t\t\tRGBE_VALID_FORMAT = 2,\n\t\t\tRGBE_VALID_DIMENSIONS = 4,\n\n\t\t\tNEWLINE = '\\n',\n\n\t\t\tfgets = function ( buffer, lineLimit, consume ) {\n\n\t\t\t\tconst chunkSize = 128;\n\n\t\t\t\tlineLimit = ! lineLimit ? 1024 : lineLimit;\n\t\t\t\tlet p = buffer.pos,\n\t\t\t\t\ti = - 1, len = 0, s = '',\n\t\t\t\t\tchunk = String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) );\n\n\t\t\t\twhile ( ( 0 > ( i = chunk.indexOf( NEWLINE ) ) ) && ( len < lineLimit ) && ( p < buffer.byteLength ) ) {\n\n\t\t\t\t\ts += chunk; len += chunk.length;\n\t\t\t\t\tp += chunkSize;\n\t\t\t\t\tchunk += String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) );\n\n\t\t\t\t}\n\n\t\t\t\tif ( - 1 < i ) {\n\n\t\t\t\t\t/*for (i=l-1; i>=0; i--) {\n\t\t\t\t\t\tbyteCode = m.charCodeAt(i);\n\t\t\t\t\t\tif (byteCode > 0x7f && byteCode <= 0x7ff) byteLen++;\n\t\t\t\t\t\telse if (byteCode > 0x7ff && byteCode <= 0xffff) byteLen += 2;\n\t\t\t\t\t\tif (byteCode >= 0xDC00 && byteCode <= 0xDFFF) i--; //trail surrogate\n\t\t\t\t\t}*/\n\t\t\t\t\tif ( false !== consume ) buffer.pos += len + i + 1;\n\t\t\t\t\treturn s + chunk.slice( 0, i );\n\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\n\t\t\t},\n\n\t\t\t/* minimal header reading. modify if you want to parse more information */\n\t\t\tRGBE_ReadHeader = function ( buffer ) {\n\n\n\t\t\t\t// regexes to parse header info fields\n\t\t\t\tconst magic_token_re = /^#\\?(\\S+)/,\n\t\t\t\t\tgamma_re = /^\\s*GAMMA\\s*=\\s*(\\d+(\\.\\d+)?)\\s*$/,\n\t\t\t\t\texposure_re = /^\\s*EXPOSURE\\s*=\\s*(\\d+(\\.\\d+)?)\\s*$/,\n\t\t\t\t\tformat_re = /^\\s*FORMAT=(\\S+)\\s*$/,\n\t\t\t\t\tdimensions_re = /^\\s*\\-Y\\s+(\\d+)\\s+\\+X\\s+(\\d+)\\s*$/,\n\n\t\t\t\t\t// RGBE format header struct\n\t\t\t\t\theader = {\n\n\t\t\t\t\t\tvalid: 0, /* indicate which fields are valid */\n\n\t\t\t\t\t\tstring: '', /* the actual header string */\n\n\t\t\t\t\t\tcomments: '', /* comments found in header */\n\n\t\t\t\t\t\tprogramtype: 'RGBE', /* listed at beginning of file to identify it after \"#?\". defaults to \"RGBE\" */\n\n\t\t\t\t\t\tformat: '', /* RGBE format, default 32-bit_rle_rgbe */\n\n\t\t\t\t\t\tgamma: 1.0, /* image has already been gamma corrected with given gamma. defaults to 1.0 (no correction) */\n\n\t\t\t\t\t\texposure: 1.0, /* a value of 1.0 in an image corresponds to watts/steradian/m^2. defaults to 1.0 */\n\n\t\t\t\t\t\twidth: 0, height: 0 /* image dimensions, width/height */\n\n\t\t\t\t\t};\n\n\t\t\t\tlet line, match;\n\n\t\t\t\tif ( buffer.pos >= buffer.byteLength || ! ( line = fgets( buffer ) ) ) {\n\n\t\t\t\t\treturn rgbe_error( rgbe_read_error, 'no header found' );\n\n\t\t\t\t}\n\n\t\t\t\t/* if you want to require the magic token then uncomment the next line */\n\t\t\t\tif ( ! ( match = line.match( magic_token_re ) ) ) {\n\n\t\t\t\t\treturn rgbe_error( rgbe_format_error, 'bad initial token' );\n\n\t\t\t\t}\n\n\t\t\t\theader.valid |= RGBE_VALID_PROGRAMTYPE;\n\t\t\t\theader.programtype = match[ 1 ];\n\t\t\t\theader.string += line + '\\n';\n\n\t\t\t\twhile ( true ) {\n\n\t\t\t\t\tline = fgets( buffer );\n\t\t\t\t\tif ( false === line ) break;\n\t\t\t\t\theader.string += line + '\\n';\n\n\t\t\t\t\tif ( '#' === line.charAt( 0 ) ) {\n\n\t\t\t\t\t\theader.comments += line + '\\n';\n\t\t\t\t\t\tcontinue; // comment line\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( match = line.match( gamma_re ) ) {\n\n\t\t\t\t\t\theader.gamma = parseFloat( match[ 1 ] );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( match = line.match( exposure_re ) ) {\n\n\t\t\t\t\t\theader.exposure = parseFloat( match[ 1 ] );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( match = line.match( format_re ) ) {\n\n\t\t\t\t\t\theader.valid |= RGBE_VALID_FORMAT;\n\t\t\t\t\t\theader.format = match[ 1 ];//'32-bit_rle_rgbe';\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( match = line.match( dimensions_re ) ) {\n\n\t\t\t\t\t\theader.valid |= RGBE_VALID_DIMENSIONS;\n\t\t\t\t\t\theader.height = parseInt( match[ 1 ], 10 );\n\t\t\t\t\t\theader.width = parseInt( match[ 2 ], 10 );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( ( header.valid & RGBE_VALID_FORMAT ) && ( header.valid & RGBE_VALID_DIMENSIONS ) ) break;\n\n\t\t\t\t}\n\n\t\t\t\tif ( ! ( header.valid & RGBE_VALID_FORMAT ) ) {\n\n\t\t\t\t\treturn rgbe_error( rgbe_format_error, 'missing format specifier' );\n\n\t\t\t\t}\n\n\t\t\t\tif ( ! ( header.valid & RGBE_VALID_DIMENSIONS ) ) {\n\n\t\t\t\t\treturn rgbe_error( rgbe_format_error, 'missing image size specifier' );\n\n\t\t\t\t}\n\n\t\t\t\treturn header;\n\n\t\t\t},\n\n\t\t\tRGBE_ReadPixels_RLE = function ( buffer, w, h ) {\n\n\t\t\t\tconst scanline_width = w;\n\n\t\t\t\tif (\n\t\t\t\t\t// run length encoding is not allowed so read flat\n\t\t\t\t\t( ( scanline_width < 8 ) || ( scanline_width > 0x7fff ) ) ||\n\t\t\t\t\t// this file is not run length encoded\n\t\t\t\t\t( ( 2 !== buffer[ 0 ] ) || ( 2 !== buffer[ 1 ] ) || ( buffer[ 2 ] & 0x80 ) )\n\t\t\t\t) {\n\n\t\t\t\t\t// return the flat buffer\n\t\t\t\t\treturn new Uint8Array( buffer );\n\n\t\t\t\t}\n\n\t\t\t\tif ( scanline_width !== ( ( buffer[ 2 ] << 8 ) | buffer[ 3 ] ) ) {\n\n\t\t\t\t\treturn rgbe_error( rgbe_format_error, 'wrong scanline width' );\n\n\t\t\t\t}\n\n\t\t\t\tconst data_rgba = new Uint8Array( 4 * w * h );\n\n\t\t\t\tif ( ! data_rgba.length ) {\n\n\t\t\t\t\treturn rgbe_error( rgbe_memory_error, 'unable to allocate buffer space' );\n\n\t\t\t\t}\n\n\t\t\t\tlet offset = 0, pos = 0;\n\n\t\t\t\tconst ptr_end = 4 * scanline_width;\n\t\t\t\tconst rgbeStart = new Uint8Array( 4 );\n\t\t\t\tconst scanline_buffer = new Uint8Array( ptr_end );\n\t\t\t\tlet num_scanlines = h;\n\n\t\t\t\t// read in each successive scanline\n\t\t\t\twhile ( ( num_scanlines > 0 ) && ( pos < buffer.byteLength ) ) {\n\n\t\t\t\t\tif ( pos + 4 > buffer.byteLength ) {\n\n\t\t\t\t\t\treturn rgbe_error( rgbe_read_error );\n\n\t\t\t\t\t}\n\n\t\t\t\t\trgbeStart[ 0 ] = buffer[ pos ++ ];\n\t\t\t\t\trgbeStart[ 1 ] = buffer[ pos ++ ];\n\t\t\t\t\trgbeStart[ 2 ] = buffer[ pos ++ ];\n\t\t\t\t\trgbeStart[ 3 ] = buffer[ pos ++ ];\n\n\t\t\t\t\tif ( ( 2 != rgbeStart[ 0 ] ) || ( 2 != rgbeStart[ 1 ] ) || ( ( ( rgbeStart[ 2 ] << 8 ) | rgbeStart[ 3 ] ) != scanline_width ) ) {\n\n\t\t\t\t\t\treturn rgbe_error( rgbe_format_error, 'bad rgbe scanline format' );\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// read each of the four channels for the scanline into the buffer\n\t\t\t\t\t// first red, then green, then blue, then exponent\n\t\t\t\t\tlet ptr = 0, count;\n\n\t\t\t\t\twhile ( ( ptr < ptr_end ) && ( pos < buffer.byteLength ) ) {\n\n\t\t\t\t\t\tcount = buffer[ pos ++ ];\n\t\t\t\t\t\tconst isEncodedRun = count > 128;\n\t\t\t\t\t\tif ( isEncodedRun ) count -= 128;\n\n\t\t\t\t\t\tif ( ( 0 === count ) || ( ptr + count > ptr_end ) ) {\n\n\t\t\t\t\t\t\treturn rgbe_error( rgbe_format_error, 'bad scanline data' );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ( isEncodedRun ) {\n\n\t\t\t\t\t\t\t// a (encoded) run of the same value\n\t\t\t\t\t\t\tconst byteValue = buffer[ pos ++ ];\n\t\t\t\t\t\t\tfor ( let i = 0; i < count; i ++ ) {\n\n\t\t\t\t\t\t\t\tscanline_buffer[ ptr ++ ] = byteValue;\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//ptr += count;\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t// a literal-run\n\t\t\t\t\t\t\tscanline_buffer.set( buffer.subarray( pos, pos + count ), ptr );\n\t\t\t\t\t\t\tptr += count; pos += count;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\n\t\t\t\t\t// now convert data from buffer into rgba\n\t\t\t\t\t// first red, then green, then blue, then exponent (alpha)\n\t\t\t\t\tconst l = scanline_width; //scanline_buffer.byteLength;\n\t\t\t\t\tfor ( let i = 0; i < l; i ++ ) {\n\n\t\t\t\t\t\tlet off = 0;\n\t\t\t\t\t\tdata_rgba[ offset ] = scanline_buffer[ i + off ];\n\t\t\t\t\t\toff += scanline_width; //1;\n\t\t\t\t\t\tdata_rgba[ offset + 1 ] = scanline_buffer[ i + off ];\n\t\t\t\t\t\toff += scanline_width; //1;\n\t\t\t\t\t\tdata_rgba[ offset + 2 ] = scanline_buffer[ i + off ];\n\t\t\t\t\t\toff += scanline_width; //1;\n\t\t\t\t\t\tdata_rgba[ offset + 3 ] = scanline_buffer[ i + off ];\n\t\t\t\t\t\toffset += 4;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tnum_scanlines --;\n\n\t\t\t\t}\n\n\t\t\t\treturn data_rgba;\n\n\t\t\t};\n\n\t\tconst RGBEByteToRGBFloat = function ( sourceArray, sourceOffset, destArray, destOffset ) {\n\n\t\t\tconst e = sourceArray[ sourceOffset + 3 ];\n\t\t\tconst scale = Math.pow( 2.0, e - 128.0 ) / 255.0;\n\n\t\t\tdestArray[ destOffset + 0 ] = sourceArray[ sourceOffset + 0 ] * scale;\n\t\t\tdestArray[ destOffset + 1 ] = sourceArray[ sourceOffset + 1 ] * scale;\n\t\t\tdestArray[ destOffset + 2 ] = sourceArray[ sourceOffset + 2 ] * scale;\n\t\t\tdestArray[ destOffset + 3 ] = 1;\n\n\t\t};\n\n\t\tconst RGBEByteToRGBHalf = function ( sourceArray, sourceOffset, destArray, destOffset ) {\n\n\t\t\tconst e = sourceArray[ sourceOffset + 3 ];\n\t\t\tconst scale = Math.pow( 2.0, e - 128.0 ) / 255.0;\n\n\t\t\t// clamping to 65504, the maximum representable value in float16\n\t\t\tdestArray[ destOffset + 0 ] = three__WEBPACK_IMPORTED_MODULE_0__.DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 0 ] * scale, 65504 ) );\n\t\t\tdestArray[ destOffset + 1 ] = three__WEBPACK_IMPORTED_MODULE_0__.DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 1 ] * scale, 65504 ) );\n\t\t\tdestArray[ destOffset + 2 ] = three__WEBPACK_IMPORTED_MODULE_0__.DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 2 ] * scale, 65504 ) );\n\t\t\tdestArray[ destOffset + 3 ] = three__WEBPACK_IMPORTED_MODULE_0__.DataUtils.toHalfFloat( 1 );\n\n\t\t};\n\n\t\tconst byteArray = new Uint8Array( buffer );\n\t\tbyteArray.pos = 0;\n\t\tconst rgbe_header_info = RGBE_ReadHeader( byteArray );\n\n\t\tif ( RGBE_RETURN_FAILURE !== rgbe_header_info ) {\n\n\t\t\tconst w = rgbe_header_info.width,\n\t\t\t\th = rgbe_header_info.height,\n\t\t\t\timage_rgba_data = RGBE_ReadPixels_RLE( byteArray.subarray( byteArray.pos ), w, h );\n\n\t\t\tif ( RGBE_RETURN_FAILURE !== image_rgba_data ) {\n\n\t\t\t\tlet data, type;\n\t\t\t\tlet numElements;\n\n\t\t\t\tswitch ( this.type ) {\n\n\t\t\t\t\tcase three__WEBPACK_IMPORTED_MODULE_0__.FloatType:\n\n\t\t\t\t\t\tnumElements = image_rgba_data.length / 4;\n\t\t\t\t\t\tconst floatArray = new Float32Array( numElements * 4 );\n\n\t\t\t\t\t\tfor ( let j = 0; j < numElements; j ++ ) {\n\n\t\t\t\t\t\t\tRGBEByteToRGBFloat( image_rgba_data, j * 4, floatArray, j * 4 );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdata = floatArray;\n\t\t\t\t\t\ttype = three__WEBPACK_IMPORTED_MODULE_0__.FloatType;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase three__WEBPACK_IMPORTED_MODULE_0__.HalfFloatType:\n\n\t\t\t\t\t\tnumElements = image_rgba_data.length / 4;\n\t\t\t\t\t\tconst halfArray = new Uint16Array( numElements * 4 );\n\n\t\t\t\t\t\tfor ( let j = 0; j < numElements; j ++ ) {\n\n\t\t\t\t\t\t\tRGBEByteToRGBHalf( image_rgba_data, j * 4, halfArray, j * 4 );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdata = halfArray;\n\t\t\t\t\t\ttype = three__WEBPACK_IMPORTED_MODULE_0__.HalfFloatType;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\n\t\t\t\t\t\tconsole.error( 'THREE.RGBELoader: unsupported type: ', this.type );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\twidth: w, height: h,\n\t\t\t\t\tdata: data,\n\t\t\t\t\theader: rgbe_header_info.string,\n\t\t\t\t\tgamma: rgbe_header_info.gamma,\n\t\t\t\t\texposure: rgbe_header_info.exposure,\n\t\t\t\t\ttype: type\n\t\t\t\t};\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn null;\n\n\t}\n\n\tsetDataType( value ) {\n\n\t\tthis.type = value;\n\t\treturn this;\n\n\t}\n\n\tload( url, onLoad, onProgress, onError ) {\n\n\t\tfunction onLoadCallback( texture, texData ) {\n\n\t\t\tswitch ( texture.type ) {\n\n\t\t\t\tcase three__WEBPACK_IMPORTED_MODULE_0__.FloatType:\n\t\t\t\tcase three__WEBPACK_IMPORTED_MODULE_0__.HalfFloatType:\n\n\t\t\t\t\ttexture.colorSpace = three__WEBPACK_IMPORTED_MODULE_0__.LinearSRGBColorSpace;\n\t\t\t\t\ttexture.minFilter = three__WEBPACK_IMPORTED_MODULE_0__.LinearFilter;\n\t\t\t\t\ttexture.magFilter = three__WEBPACK_IMPORTED_MODULE_0__.LinearFilter;\n\t\t\t\t\ttexture.generateMipmaps = false;\n\t\t\t\t\ttexture.flipY = true;\n\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\tif ( onLoad ) onLoad( texture, texData );\n\n\t\t}\n\n\t\treturn super.load( url, onLoadCallback, onProgress, onError );\n\n\t}\n\n}\n\n\n\n\n//# sourceURL=webpack://MaterialXView/./node_modules/three/examples/jsm/loaders/RGBELoader.js?"); + +/***/ }), + +/***/ "./node_modules/three/examples/jsm/utils/BufferGeometryUtils.js": +/*!**********************************************************************!*\ + !*** ./node_modules/three/examples/jsm/utils/BufferGeometryUtils.js ***! + \**********************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ computeMikkTSpaceTangents: () => (/* binding */ computeMikkTSpaceTangents),\n/* harmony export */ computeMorphedAttributes: () => (/* binding */ computeMorphedAttributes),\n/* harmony export */ deepCloneAttribute: () => (/* binding */ deepCloneAttribute),\n/* harmony export */ deinterleaveAttribute: () => (/* binding */ deinterleaveAttribute),\n/* harmony export */ deinterleaveGeometry: () => (/* binding */ deinterleaveGeometry),\n/* harmony export */ estimateBytesUsed: () => (/* binding */ estimateBytesUsed),\n/* harmony export */ interleaveAttributes: () => (/* binding */ interleaveAttributes),\n/* harmony export */ mergeAttributes: () => (/* binding */ mergeAttributes),\n/* harmony export */ mergeBufferAttributes: () => (/* binding */ mergeBufferAttributes),\n/* harmony export */ mergeBufferGeometries: () => (/* binding */ mergeBufferGeometries),\n/* harmony export */ mergeGeometries: () => (/* binding */ mergeGeometries),\n/* harmony export */ mergeGroups: () => (/* binding */ mergeGroups),\n/* harmony export */ mergeVertices: () => (/* binding */ mergeVertices),\n/* harmony export */ toCreasedNormals: () => (/* binding */ toCreasedNormals),\n/* harmony export */ toTrianglesDrawMode: () => (/* binding */ toTrianglesDrawMode)\n/* harmony export */ });\n/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! three */ \"./node_modules/three/build/three.module.js\");\n\n\nfunction computeMikkTSpaceTangents( geometry, MikkTSpace, negateSign = true ) {\n\n\tif ( ! MikkTSpace || ! MikkTSpace.isReady ) {\n\n\t\tthrow new Error( 'BufferGeometryUtils: Initialized MikkTSpace library required.' );\n\n\t}\n\n\tif ( ! geometry.hasAttribute( 'position' ) || ! geometry.hasAttribute( 'normal' ) || ! geometry.hasAttribute( 'uv' ) ) {\n\n\t\tthrow new Error( 'BufferGeometryUtils: Tangents require \"position\", \"normal\", and \"uv\" attributes.' );\n\n\t}\n\n\tfunction getAttributeArray( attribute ) {\n\n\t\tif ( attribute.normalized || attribute.isInterleavedBufferAttribute ) {\n\n\t\t\tconst dstArray = new Float32Array( attribute.count * attribute.itemSize );\n\n\t\t\tfor ( let i = 0, j = 0; i < attribute.count; i ++ ) {\n\n\t\t\t\tdstArray[ j ++ ] = attribute.getX( i );\n\t\t\t\tdstArray[ j ++ ] = attribute.getY( i );\n\n\t\t\t\tif ( attribute.itemSize > 2 ) {\n\n\t\t\t\t\tdstArray[ j ++ ] = attribute.getZ( i );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn dstArray;\n\n\t\t}\n\n\t\tif ( attribute.array instanceof Float32Array ) {\n\n\t\t\treturn attribute.array;\n\n\t\t}\n\n\t\treturn new Float32Array( attribute.array );\n\n\t}\n\n\t// MikkTSpace algorithm requires non-indexed input.\n\n\tconst _geometry = geometry.index ? geometry.toNonIndexed() : geometry;\n\n\t// Compute vertex tangents.\n\n\tconst tangents = MikkTSpace.generateTangents(\n\n\t\tgetAttributeArray( _geometry.attributes.position ),\n\t\tgetAttributeArray( _geometry.attributes.normal ),\n\t\tgetAttributeArray( _geometry.attributes.uv )\n\n\t);\n\n\t// Texture coordinate convention of glTF differs from the apparent\n\t// default of the MikkTSpace library; .w component must be flipped.\n\n\tif ( negateSign ) {\n\n\t\tfor ( let i = 3; i < tangents.length; i += 4 ) {\n\n\t\t\ttangents[ i ] *= - 1;\n\n\t\t}\n\n\t}\n\n\t//\n\n\t_geometry.setAttribute( 'tangent', new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute( tangents, 4 ) );\n\n\tif ( geometry !== _geometry ) {\n\n\t\tgeometry.copy( _geometry );\n\n\t}\n\n\treturn geometry;\n\n}\n\n/**\n * @param {Array} geometries\n * @param {Boolean} useGroups\n * @return {BufferGeometry}\n */\nfunction mergeGeometries( geometries, useGroups = false ) {\n\n\tconst isIndexed = geometries[ 0 ].index !== null;\n\n\tconst attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );\n\tconst morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );\n\n\tconst attributes = {};\n\tconst morphAttributes = {};\n\n\tconst morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;\n\n\tconst mergedGeometry = new three__WEBPACK_IMPORTED_MODULE_0__.BufferGeometry();\n\n\tlet offset = 0;\n\n\tfor ( let i = 0; i < geometries.length; ++ i ) {\n\n\t\tconst geometry = geometries[ i ];\n\t\tlet attributesCount = 0;\n\n\t\t// ensure that all geometries are indexed, or none\n\n\t\tif ( isIndexed !== ( geometry.index !== null ) ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.' );\n\t\t\treturn null;\n\n\t\t}\n\n\t\t// gather attributes, exit early if they're different\n\n\t\tfor ( const name in geometry.attributes ) {\n\n\t\t\tif ( ! attributesUsed.has( name ) ) {\n\n\t\t\t\tconsole.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure \"' + name + '\" attribute exists among all geometries, or in none of them.' );\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t\tif ( attributes[ name ] === undefined ) attributes[ name ] = [];\n\n\t\t\tattributes[ name ].push( geometry.attributes[ name ] );\n\n\t\t\tattributesCount ++;\n\n\t\t}\n\n\t\t// ensure geometries have the same number of attributes\n\n\t\tif ( attributesCount !== attributesUsed.size ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' );\n\t\t\treturn null;\n\n\t\t}\n\n\t\t// gather morph attributes, exit early if they're different\n\n\t\tif ( morphTargetsRelative !== geometry.morphTargetsRelative ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );\n\t\t\treturn null;\n\n\t\t}\n\n\t\tfor ( const name in geometry.morphAttributes ) {\n\n\t\t\tif ( ! morphAttributesUsed.has( name ) ) {\n\n\t\t\t\tconsole.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t\tif ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];\n\n\t\t\tmorphAttributes[ name ].push( geometry.morphAttributes[ name ] );\n\n\t\t}\n\n\t\tif ( useGroups ) {\n\n\t\t\tlet count;\n\n\t\t\tif ( isIndexed ) {\n\n\t\t\t\tcount = geometry.index.count;\n\n\t\t\t} else if ( geometry.attributes.position !== undefined ) {\n\n\t\t\t\tcount = geometry.attributes.position.count;\n\n\t\t\t} else {\n\n\t\t\t\tconsole.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t\tmergedGeometry.addGroup( offset, count, i );\n\n\t\t\toffset += count;\n\n\t\t}\n\n\t}\n\n\t// merge indices\n\n\tif ( isIndexed ) {\n\n\t\tlet indexOffset = 0;\n\t\tconst mergedIndex = [];\n\n\t\tfor ( let i = 0; i < geometries.length; ++ i ) {\n\n\t\t\tconst index = geometries[ i ].index;\n\n\t\t\tfor ( let j = 0; j < index.count; ++ j ) {\n\n\t\t\t\tmergedIndex.push( index.getX( j ) + indexOffset );\n\n\t\t\t}\n\n\t\t\tindexOffset += geometries[ i ].attributes.position.count;\n\n\t\t}\n\n\t\tmergedGeometry.setIndex( mergedIndex );\n\n\t}\n\n\t// merge attributes\n\n\tfor ( const name in attributes ) {\n\n\t\tconst mergedAttribute = mergeAttributes( attributes[ name ] );\n\n\t\tif ( ! mergedAttribute ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + name + ' attribute.' );\n\t\t\treturn null;\n\n\t\t}\n\n\t\tmergedGeometry.setAttribute( name, mergedAttribute );\n\n\t}\n\n\t// merge morph attributes\n\n\tfor ( const name in morphAttributes ) {\n\n\t\tconst numMorphTargets = morphAttributes[ name ][ 0 ].length;\n\n\t\tif ( numMorphTargets === 0 ) break;\n\n\t\tmergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};\n\t\tmergedGeometry.morphAttributes[ name ] = [];\n\n\t\tfor ( let i = 0; i < numMorphTargets; ++ i ) {\n\n\t\t\tconst morphAttributesToMerge = [];\n\n\t\t\tfor ( let j = 0; j < morphAttributes[ name ].length; ++ j ) {\n\n\t\t\t\tmorphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );\n\n\t\t\t}\n\n\t\t\tconst mergedMorphAttribute = mergeAttributes( morphAttributesToMerge );\n\n\t\t\tif ( ! mergedMorphAttribute ) {\n\n\t\t\t\tconsole.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );\n\t\t\t\treturn null;\n\n\t\t\t}\n\n\t\t\tmergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );\n\n\t\t}\n\n\t}\n\n\treturn mergedGeometry;\n\n}\n\n/**\n * @param {Array} attributes\n * @return {BufferAttribute}\n */\nfunction mergeAttributes( attributes ) {\n\n\tlet TypedArray;\n\tlet itemSize;\n\tlet normalized;\n\tlet arrayLength = 0;\n\n\tfor ( let i = 0; i < attributes.length; ++ i ) {\n\n\t\tconst attribute = attributes[ i ];\n\n\t\tif ( attribute.isInterleavedBufferAttribute ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. InterleavedBufferAttributes are not supported.' );\n\t\t\treturn null;\n\n\t\t}\n\n\t\tif ( TypedArray === undefined ) TypedArray = attribute.array.constructor;\n\t\tif ( TypedArray !== attribute.array.constructor ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' );\n\t\t\treturn null;\n\n\t\t}\n\n\t\tif ( itemSize === undefined ) itemSize = attribute.itemSize;\n\t\tif ( itemSize !== attribute.itemSize ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' );\n\t\t\treturn null;\n\n\t\t}\n\n\t\tif ( normalized === undefined ) normalized = attribute.normalized;\n\t\tif ( normalized !== attribute.normalized ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' );\n\t\t\treturn null;\n\n\t\t}\n\n\t\tarrayLength += attribute.array.length;\n\n\t}\n\n\tconst array = new TypedArray( arrayLength );\n\tlet offset = 0;\n\n\tfor ( let i = 0; i < attributes.length; ++ i ) {\n\n\t\tarray.set( attributes[ i ].array, offset );\n\n\t\toffset += attributes[ i ].array.length;\n\n\t}\n\n\treturn new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute( array, itemSize, normalized );\n\n}\n\n/**\n * @param {BufferAttribute}\n * @return {BufferAttribute}\n */\nfunction deepCloneAttribute( attribute ) {\n\n\tif ( attribute.isInstancedInterleavedBufferAttribute || attribute.isInterleavedBufferAttribute ) {\n\n\t\treturn deinterleaveAttribute( attribute );\n\n\t}\n\n\tif ( attribute.isInstancedBufferAttribute ) {\n\n\t\treturn new three__WEBPACK_IMPORTED_MODULE_0__.InstancedBufferAttribute().copy( attribute );\n\n\t}\n\n\treturn new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute().copy( attribute );\n\n}\n\n/**\n * @param {Array} attributes\n * @return {Array}\n */\nfunction interleaveAttributes( attributes ) {\n\n\t// Interleaves the provided attributes into an InterleavedBuffer and returns\n\t// a set of InterleavedBufferAttributes for each attribute\n\tlet TypedArray;\n\tlet arrayLength = 0;\n\tlet stride = 0;\n\n\t// calculate the length and type of the interleavedBuffer\n\tfor ( let i = 0, l = attributes.length; i < l; ++ i ) {\n\n\t\tconst attribute = attributes[ i ];\n\n\t\tif ( TypedArray === undefined ) TypedArray = attribute.array.constructor;\n\t\tif ( TypedArray !== attribute.array.constructor ) {\n\n\t\t\tconsole.error( 'AttributeBuffers of different types cannot be interleaved' );\n\t\t\treturn null;\n\n\t\t}\n\n\t\tarrayLength += attribute.array.length;\n\t\tstride += attribute.itemSize;\n\n\t}\n\n\t// Create the set of buffer attributes\n\tconst interleavedBuffer = new three__WEBPACK_IMPORTED_MODULE_0__.InterleavedBuffer( new TypedArray( arrayLength ), stride );\n\tlet offset = 0;\n\tconst res = [];\n\tconst getters = [ 'getX', 'getY', 'getZ', 'getW' ];\n\tconst setters = [ 'setX', 'setY', 'setZ', 'setW' ];\n\n\tfor ( let j = 0, l = attributes.length; j < l; j ++ ) {\n\n\t\tconst attribute = attributes[ j ];\n\t\tconst itemSize = attribute.itemSize;\n\t\tconst count = attribute.count;\n\t\tconst iba = new three__WEBPACK_IMPORTED_MODULE_0__.InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );\n\t\tres.push( iba );\n\n\t\toffset += itemSize;\n\n\t\t// Move the data for each attribute into the new interleavedBuffer\n\t\t// at the appropriate offset\n\t\tfor ( let c = 0; c < count; c ++ ) {\n\n\t\t\tfor ( let k = 0; k < itemSize; k ++ ) {\n\n\t\t\t\tiba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn res;\n\n}\n\n// returns a new, non-interleaved version of the provided attribute\nfunction deinterleaveAttribute( attribute ) {\n\n\tconst cons = attribute.data.array.constructor;\n\tconst count = attribute.count;\n\tconst itemSize = attribute.itemSize;\n\tconst normalized = attribute.normalized;\n\n\tconst array = new cons( count * itemSize );\n\tlet newAttribute;\n\tif ( attribute.isInstancedInterleavedBufferAttribute ) {\n\n\t\tnewAttribute = new three__WEBPACK_IMPORTED_MODULE_0__.InstancedBufferAttribute( array, itemSize, normalized, attribute.meshPerAttribute );\n\n\t} else {\n\n\t\tnewAttribute = new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute( array, itemSize, normalized );\n\n\t}\n\n\tfor ( let i = 0; i < count; i ++ ) {\n\n\t\tnewAttribute.setX( i, attribute.getX( i ) );\n\n\t\tif ( itemSize >= 2 ) {\n\n\t\t\tnewAttribute.setY( i, attribute.getY( i ) );\n\n\t\t}\n\n\t\tif ( itemSize >= 3 ) {\n\n\t\t\tnewAttribute.setZ( i, attribute.getZ( i ) );\n\n\t\t}\n\n\t\tif ( itemSize >= 4 ) {\n\n\t\t\tnewAttribute.setW( i, attribute.getW( i ) );\n\n\t\t}\n\n\t}\n\n\treturn newAttribute;\n\n}\n\n// deinterleaves all attributes on the geometry\nfunction deinterleaveGeometry( geometry ) {\n\n\tconst attributes = geometry.attributes;\n\tconst morphTargets = geometry.morphTargets;\n\tconst attrMap = new Map();\n\n\tfor ( const key in attributes ) {\n\n\t\tconst attr = attributes[ key ];\n\t\tif ( attr.isInterleavedBufferAttribute ) {\n\n\t\t\tif ( ! attrMap.has( attr ) ) {\n\n\t\t\t\tattrMap.set( attr, deinterleaveAttribute( attr ) );\n\n\t\t\t}\n\n\t\t\tattributes[ key ] = attrMap.get( attr );\n\n\t\t}\n\n\t}\n\n\tfor ( const key in morphTargets ) {\n\n\t\tconst attr = morphTargets[ key ];\n\t\tif ( attr.isInterleavedBufferAttribute ) {\n\n\t\t\tif ( ! attrMap.has( attr ) ) {\n\n\t\t\t\tattrMap.set( attr, deinterleaveAttribute( attr ) );\n\n\t\t\t}\n\n\t\t\tmorphTargets[ key ] = attrMap.get( attr );\n\n\t\t}\n\n\t}\n\n}\n\n/**\n * @param {Array} geometry\n * @return {number}\n */\nfunction estimateBytesUsed( geometry ) {\n\n\t// Return the estimated memory used by this geometry in bytes\n\t// Calculate using itemSize, count, and BYTES_PER_ELEMENT to account\n\t// for InterleavedBufferAttributes.\n\tlet mem = 0;\n\tfor ( const name in geometry.attributes ) {\n\n\t\tconst attr = geometry.getAttribute( name );\n\t\tmem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;\n\n\t}\n\n\tconst indices = geometry.getIndex();\n\tmem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;\n\treturn mem;\n\n}\n\n/**\n * @param {BufferGeometry} geometry\n * @param {number} tolerance\n * @return {BufferGeometry}\n */\nfunction mergeVertices( geometry, tolerance = 1e-4 ) {\n\n\ttolerance = Math.max( tolerance, Number.EPSILON );\n\n\t// Generate an index buffer if the geometry doesn't have one, or optimize it\n\t// if it's already available.\n\tconst hashToIndex = {};\n\tconst indices = geometry.getIndex();\n\tconst positions = geometry.getAttribute( 'position' );\n\tconst vertexCount = indices ? indices.count : positions.count;\n\n\t// next value for triangle indices\n\tlet nextIndex = 0;\n\n\t// attributes and new attribute arrays\n\tconst attributeNames = Object.keys( geometry.attributes );\n\tconst tmpAttributes = {};\n\tconst tmpMorphAttributes = {};\n\tconst newIndices = [];\n\tconst getters = [ 'getX', 'getY', 'getZ', 'getW' ];\n\tconst setters = [ 'setX', 'setY', 'setZ', 'setW' ];\n\n\t// Initialize the arrays, allocating space conservatively. Extra\n\t// space will be trimmed in the last step.\n\tfor ( let i = 0, l = attributeNames.length; i < l; i ++ ) {\n\n\t\tconst name = attributeNames[ i ];\n\t\tconst attr = geometry.attributes[ name ];\n\n\t\ttmpAttributes[ name ] = new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute(\n\t\t\tnew attr.array.constructor( attr.count * attr.itemSize ),\n\t\t\tattr.itemSize,\n\t\t\tattr.normalized\n\t\t);\n\n\t\tconst morphAttr = geometry.morphAttributes[ name ];\n\t\tif ( morphAttr ) {\n\n\t\t\ttmpMorphAttributes[ name ] = new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute(\n\t\t\t\tnew morphAttr.array.constructor( morphAttr.count * morphAttr.itemSize ),\n\t\t\t\tmorphAttr.itemSize,\n\t\t\t\tmorphAttr.normalized\n\t\t\t);\n\n\t\t}\n\n\t}\n\n\t// convert the error tolerance to an amount of decimal places to truncate to\n\tconst decimalShift = Math.log10( 1 / tolerance );\n\tconst shiftMultiplier = Math.pow( 10, decimalShift );\n\tfor ( let i = 0; i < vertexCount; i ++ ) {\n\n\t\tconst index = indices ? indices.getX( i ) : i;\n\n\t\t// Generate a hash for the vertex attributes at the current index 'i'\n\t\tlet hash = '';\n\t\tfor ( let j = 0, l = attributeNames.length; j < l; j ++ ) {\n\n\t\t\tconst name = attributeNames[ j ];\n\t\t\tconst attribute = geometry.getAttribute( name );\n\t\t\tconst itemSize = attribute.itemSize;\n\n\t\t\tfor ( let k = 0; k < itemSize; k ++ ) {\n\n\t\t\t\t// double tilde truncates the decimal value\n\t\t\t\thash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// Add another reference to the vertex if it's already\n\t\t// used by another index\n\t\tif ( hash in hashToIndex ) {\n\n\t\t\tnewIndices.push( hashToIndex[ hash ] );\n\n\t\t} else {\n\n\t\t\t// copy data to the new index in the temporary attributes\n\t\t\tfor ( let j = 0, l = attributeNames.length; j < l; j ++ ) {\n\n\t\t\t\tconst name = attributeNames[ j ];\n\t\t\t\tconst attribute = geometry.getAttribute( name );\n\t\t\t\tconst morphAttr = geometry.morphAttributes[ name ];\n\t\t\t\tconst itemSize = attribute.itemSize;\n\t\t\t\tconst newarray = tmpAttributes[ name ];\n\t\t\t\tconst newMorphArrays = tmpMorphAttributes[ name ];\n\n\t\t\t\tfor ( let k = 0; k < itemSize; k ++ ) {\n\n\t\t\t\t\tconst getterFunc = getters[ k ];\n\t\t\t\t\tconst setterFunc = setters[ k ];\n\t\t\t\t\tnewarray[ setterFunc ]( nextIndex, attribute[ getterFunc ]( index ) );\n\n\t\t\t\t\tif ( morphAttr ) {\n\n\t\t\t\t\t\tfor ( let m = 0, ml = morphAttr.length; m < ml; m ++ ) {\n\n\t\t\t\t\t\t\tnewMorphArrays[ m ][ setterFunc ]( nextIndex, morphAttr[ m ][ getterFunc ]( index ) );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\thashToIndex[ hash ] = nextIndex;\n\t\t\tnewIndices.push( nextIndex );\n\t\t\tnextIndex ++;\n\n\t\t}\n\n\t}\n\n\t// generate result BufferGeometry\n\tconst result = geometry.clone();\n\tfor ( const name in geometry.attributes ) {\n\n\t\tconst tmpAttribute = tmpAttributes[ name ];\n\n\t\tresult.setAttribute( name, new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute(\n\t\t\ttmpAttribute.array.slice( 0, nextIndex * tmpAttribute.itemSize ),\n\t\t\ttmpAttribute.itemSize,\n\t\t\ttmpAttribute.normalized,\n\t\t) );\n\n\t\tif ( ! ( name in tmpMorphAttributes ) ) continue;\n\n\t\tfor ( let j = 0; j < tmpMorphAttributes[ name ].length; j ++ ) {\n\n\t\t\tconst tmpMorphAttribute = tmpMorphAttributes[ name ][ j ];\n\n\t\t\tresult.morphAttributes[ name ][ j ] = new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute(\n\t\t\t\ttmpMorphAttribute.array.slice( 0, nextIndex * tmpMorphAttribute.itemSize ),\n\t\t\t\ttmpMorphAttribute.itemSize,\n\t\t\t\ttmpMorphAttribute.normalized,\n\t\t\t);\n\n\t\t}\n\n\t}\n\n\t// indices\n\n\tresult.setIndex( newIndices );\n\n\treturn result;\n\n}\n\n/**\n * @param {BufferGeometry} geometry\n * @param {number} drawMode\n * @return {BufferGeometry}\n */\nfunction toTrianglesDrawMode( geometry, drawMode ) {\n\n\tif ( drawMode === three__WEBPACK_IMPORTED_MODULE_0__.TrianglesDrawMode ) {\n\n\t\tconsole.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );\n\t\treturn geometry;\n\n\t}\n\n\tif ( drawMode === three__WEBPACK_IMPORTED_MODULE_0__.TriangleFanDrawMode || drawMode === three__WEBPACK_IMPORTED_MODULE_0__.TriangleStripDrawMode ) {\n\n\t\tlet index = geometry.getIndex();\n\n\t\t// generate index if not present\n\n\t\tif ( index === null ) {\n\n\t\t\tconst indices = [];\n\n\t\t\tconst position = geometry.getAttribute( 'position' );\n\n\t\t\tif ( position !== undefined ) {\n\n\t\t\t\tfor ( let i = 0; i < position.count; i ++ ) {\n\n\t\t\t\t\tindices.push( i );\n\n\t\t\t\t}\n\n\t\t\t\tgeometry.setIndex( indices );\n\t\t\t\tindex = geometry.getIndex();\n\n\t\t\t} else {\n\n\t\t\t\tconsole.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );\n\t\t\t\treturn geometry;\n\n\t\t\t}\n\n\t\t}\n\n\t\t//\n\n\t\tconst numberOfTriangles = index.count - 2;\n\t\tconst newIndices = [];\n\n\t\tif ( drawMode === three__WEBPACK_IMPORTED_MODULE_0__.TriangleFanDrawMode ) {\n\n\t\t\t// gl.TRIANGLE_FAN\n\n\t\t\tfor ( let i = 1; i <= numberOfTriangles; i ++ ) {\n\n\t\t\t\tnewIndices.push( index.getX( 0 ) );\n\t\t\t\tnewIndices.push( index.getX( i ) );\n\t\t\t\tnewIndices.push( index.getX( i + 1 ) );\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\t// gl.TRIANGLE_STRIP\n\n\t\t\tfor ( let i = 0; i < numberOfTriangles; i ++ ) {\n\n\t\t\t\tif ( i % 2 === 0 ) {\n\n\t\t\t\t\tnewIndices.push( index.getX( i ) );\n\t\t\t\t\tnewIndices.push( index.getX( i + 1 ) );\n\t\t\t\t\tnewIndices.push( index.getX( i + 2 ) );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tnewIndices.push( index.getX( i + 2 ) );\n\t\t\t\t\tnewIndices.push( index.getX( i + 1 ) );\n\t\t\t\t\tnewIndices.push( index.getX( i ) );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( ( newIndices.length / 3 ) !== numberOfTriangles ) {\n\n\t\t\tconsole.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );\n\n\t\t}\n\n\t\t// build final geometry\n\n\t\tconst newGeometry = geometry.clone();\n\t\tnewGeometry.setIndex( newIndices );\n\t\tnewGeometry.clearGroups();\n\n\t\treturn newGeometry;\n\n\t} else {\n\n\t\tconsole.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );\n\t\treturn geometry;\n\n\t}\n\n}\n\n/**\n * Calculates the morphed attributes of a morphed/skinned BufferGeometry.\n * Helpful for Raytracing or Decals.\n * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points.\n * @return {Object} An Object with original position/normal attributes and morphed ones.\n */\nfunction computeMorphedAttributes( object ) {\n\n\tconst _vA = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\tconst _vB = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\tconst _vC = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\n\tconst _tempA = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\tconst _tempB = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\tconst _tempC = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\n\tconst _morphA = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\tconst _morphB = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\tconst _morphC = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\n\tfunction _calculateMorphedAttributeData(\n\t\tobject,\n\t\tattribute,\n\t\tmorphAttribute,\n\t\tmorphTargetsRelative,\n\t\ta,\n\t\tb,\n\t\tc,\n\t\tmodifiedAttributeArray\n\t) {\n\n\t\t_vA.fromBufferAttribute( attribute, a );\n\t\t_vB.fromBufferAttribute( attribute, b );\n\t\t_vC.fromBufferAttribute( attribute, c );\n\n\t\tconst morphInfluences = object.morphTargetInfluences;\n\n\t\tif ( morphAttribute && morphInfluences ) {\n\n\t\t\t_morphA.set( 0, 0, 0 );\n\t\t\t_morphB.set( 0, 0, 0 );\n\t\t\t_morphC.set( 0, 0, 0 );\n\n\t\t\tfor ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {\n\n\t\t\t\tconst influence = morphInfluences[ i ];\n\t\t\t\tconst morph = morphAttribute[ i ];\n\n\t\t\t\tif ( influence === 0 ) continue;\n\n\t\t\t\t_tempA.fromBufferAttribute( morph, a );\n\t\t\t\t_tempB.fromBufferAttribute( morph, b );\n\t\t\t\t_tempC.fromBufferAttribute( morph, c );\n\n\t\t\t\tif ( morphTargetsRelative ) {\n\n\t\t\t\t\t_morphA.addScaledVector( _tempA, influence );\n\t\t\t\t\t_morphB.addScaledVector( _tempB, influence );\n\t\t\t\t\t_morphC.addScaledVector( _tempC, influence );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t_morphA.addScaledVector( _tempA.sub( _vA ), influence );\n\t\t\t\t\t_morphB.addScaledVector( _tempB.sub( _vB ), influence );\n\t\t\t\t\t_morphC.addScaledVector( _tempC.sub( _vC ), influence );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t_vA.add( _morphA );\n\t\t\t_vB.add( _morphB );\n\t\t\t_vC.add( _morphC );\n\n\t\t}\n\n\t\tif ( object.isSkinnedMesh ) {\n\n\t\t\tobject.applyBoneTransform( a, _vA );\n\t\t\tobject.applyBoneTransform( b, _vB );\n\t\t\tobject.applyBoneTransform( c, _vC );\n\n\t\t}\n\n\t\tmodifiedAttributeArray[ a * 3 + 0 ] = _vA.x;\n\t\tmodifiedAttributeArray[ a * 3 + 1 ] = _vA.y;\n\t\tmodifiedAttributeArray[ a * 3 + 2 ] = _vA.z;\n\t\tmodifiedAttributeArray[ b * 3 + 0 ] = _vB.x;\n\t\tmodifiedAttributeArray[ b * 3 + 1 ] = _vB.y;\n\t\tmodifiedAttributeArray[ b * 3 + 2 ] = _vB.z;\n\t\tmodifiedAttributeArray[ c * 3 + 0 ] = _vC.x;\n\t\tmodifiedAttributeArray[ c * 3 + 1 ] = _vC.y;\n\t\tmodifiedAttributeArray[ c * 3 + 2 ] = _vC.z;\n\n\t}\n\n\tconst geometry = object.geometry;\n\tconst material = object.material;\n\n\tlet a, b, c;\n\tconst index = geometry.index;\n\tconst positionAttribute = geometry.attributes.position;\n\tconst morphPosition = geometry.morphAttributes.position;\n\tconst morphTargetsRelative = geometry.morphTargetsRelative;\n\tconst normalAttribute = geometry.attributes.normal;\n\tconst morphNormal = geometry.morphAttributes.position;\n\n\tconst groups = geometry.groups;\n\tconst drawRange = geometry.drawRange;\n\tlet i, j, il, jl;\n\tlet group;\n\tlet start, end;\n\n\tconst modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );\n\tconst modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );\n\n\tif ( index !== null ) {\n\n\t\t// indexed buffer geometry\n\n\t\tif ( Array.isArray( material ) ) {\n\n\t\t\tfor ( i = 0, il = groups.length; i < il; i ++ ) {\n\n\t\t\t\tgroup = groups[ i ];\n\n\t\t\t\tstart = Math.max( group.start, drawRange.start );\n\t\t\t\tend = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );\n\n\t\t\t\tfor ( j = start, jl = end; j < jl; j += 3 ) {\n\n\t\t\t\t\ta = index.getX( j );\n\t\t\t\t\tb = index.getX( j + 1 );\n\t\t\t\t\tc = index.getX( j + 2 );\n\n\t\t\t\t\t_calculateMorphedAttributeData(\n\t\t\t\t\t\tobject,\n\t\t\t\t\t\tpositionAttribute,\n\t\t\t\t\t\tmorphPosition,\n\t\t\t\t\t\tmorphTargetsRelative,\n\t\t\t\t\t\ta, b, c,\n\t\t\t\t\t\tmodifiedPosition\n\t\t\t\t\t);\n\n\t\t\t\t\t_calculateMorphedAttributeData(\n\t\t\t\t\t\tobject,\n\t\t\t\t\t\tnormalAttribute,\n\t\t\t\t\t\tmorphNormal,\n\t\t\t\t\t\tmorphTargetsRelative,\n\t\t\t\t\t\ta, b, c,\n\t\t\t\t\t\tmodifiedNormal\n\t\t\t\t\t);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tstart = Math.max( 0, drawRange.start );\n\t\t\tend = Math.min( index.count, ( drawRange.start + drawRange.count ) );\n\n\t\t\tfor ( i = start, il = end; i < il; i += 3 ) {\n\n\t\t\t\ta = index.getX( i );\n\t\t\t\tb = index.getX( i + 1 );\n\t\t\t\tc = index.getX( i + 2 );\n\n\t\t\t\t_calculateMorphedAttributeData(\n\t\t\t\t\tobject,\n\t\t\t\t\tpositionAttribute,\n\t\t\t\t\tmorphPosition,\n\t\t\t\t\tmorphTargetsRelative,\n\t\t\t\t\ta, b, c,\n\t\t\t\t\tmodifiedPosition\n\t\t\t\t);\n\n\t\t\t\t_calculateMorphedAttributeData(\n\t\t\t\t\tobject,\n\t\t\t\t\tnormalAttribute,\n\t\t\t\t\tmorphNormal,\n\t\t\t\t\tmorphTargetsRelative,\n\t\t\t\t\ta, b, c,\n\t\t\t\t\tmodifiedNormal\n\t\t\t\t);\n\n\t\t\t}\n\n\t\t}\n\n\t} else {\n\n\t\t// non-indexed buffer geometry\n\n\t\tif ( Array.isArray( material ) ) {\n\n\t\t\tfor ( i = 0, il = groups.length; i < il; i ++ ) {\n\n\t\t\t\tgroup = groups[ i ];\n\n\t\t\t\tstart = Math.max( group.start, drawRange.start );\n\t\t\t\tend = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );\n\n\t\t\t\tfor ( j = start, jl = end; j < jl; j += 3 ) {\n\n\t\t\t\t\ta = j;\n\t\t\t\t\tb = j + 1;\n\t\t\t\t\tc = j + 2;\n\n\t\t\t\t\t_calculateMorphedAttributeData(\n\t\t\t\t\t\tobject,\n\t\t\t\t\t\tpositionAttribute,\n\t\t\t\t\t\tmorphPosition,\n\t\t\t\t\t\tmorphTargetsRelative,\n\t\t\t\t\t\ta, b, c,\n\t\t\t\t\t\tmodifiedPosition\n\t\t\t\t\t);\n\n\t\t\t\t\t_calculateMorphedAttributeData(\n\t\t\t\t\t\tobject,\n\t\t\t\t\t\tnormalAttribute,\n\t\t\t\t\t\tmorphNormal,\n\t\t\t\t\t\tmorphTargetsRelative,\n\t\t\t\t\t\ta, b, c,\n\t\t\t\t\t\tmodifiedNormal\n\t\t\t\t\t);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tstart = Math.max( 0, drawRange.start );\n\t\t\tend = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );\n\n\t\t\tfor ( i = start, il = end; i < il; i += 3 ) {\n\n\t\t\t\ta = i;\n\t\t\t\tb = i + 1;\n\t\t\t\tc = i + 2;\n\n\t\t\t\t_calculateMorphedAttributeData(\n\t\t\t\t\tobject,\n\t\t\t\t\tpositionAttribute,\n\t\t\t\t\tmorphPosition,\n\t\t\t\t\tmorphTargetsRelative,\n\t\t\t\t\ta, b, c,\n\t\t\t\t\tmodifiedPosition\n\t\t\t\t);\n\n\t\t\t\t_calculateMorphedAttributeData(\n\t\t\t\t\tobject,\n\t\t\t\t\tnormalAttribute,\n\t\t\t\t\tmorphNormal,\n\t\t\t\t\tmorphTargetsRelative,\n\t\t\t\t\ta, b, c,\n\t\t\t\t\tmodifiedNormal\n\t\t\t\t);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tconst morphedPositionAttribute = new three__WEBPACK_IMPORTED_MODULE_0__.Float32BufferAttribute( modifiedPosition, 3 );\n\tconst morphedNormalAttribute = new three__WEBPACK_IMPORTED_MODULE_0__.Float32BufferAttribute( modifiedNormal, 3 );\n\n\treturn {\n\n\t\tpositionAttribute: positionAttribute,\n\t\tnormalAttribute: normalAttribute,\n\t\tmorphedPositionAttribute: morphedPositionAttribute,\n\t\tmorphedNormalAttribute: morphedNormalAttribute\n\n\t};\n\n}\n\nfunction mergeGroups( geometry ) {\n\n\tif ( geometry.groups.length === 0 ) {\n\n\t\tconsole.warn( 'THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.' );\n\t\treturn geometry;\n\n\t}\n\n\tlet groups = geometry.groups;\n\n\t// sort groups by material index\n\n\tgroups = groups.sort( ( a, b ) => {\n\n\t\tif ( a.materialIndex !== b.materialIndex ) return a.materialIndex - b.materialIndex;\n\n\t\treturn a.start - b.start;\n\n\t} );\n\n\t// create index for non-indexed geometries\n\n\tif ( geometry.getIndex() === null ) {\n\n\t\tconst positionAttribute = geometry.getAttribute( 'position' );\n\t\tconst indices = [];\n\n\t\tfor ( let i = 0; i < positionAttribute.count; i += 3 ) {\n\n\t\t\tindices.push( i, i + 1, i + 2 );\n\n\t\t}\n\n\t\tgeometry.setIndex( indices );\n\n\t}\n\n\t// sort index\n\n\tconst index = geometry.getIndex();\n\n\tconst newIndices = [];\n\n\tfor ( let i = 0; i < groups.length; i ++ ) {\n\n\t\tconst group = groups[ i ];\n\n\t\tconst groupStart = group.start;\n\t\tconst groupLength = groupStart + group.count;\n\n\t\tfor ( let j = groupStart; j < groupLength; j ++ ) {\n\n\t\t\tnewIndices.push( index.getX( j ) );\n\n\t\t}\n\n\t}\n\n\tgeometry.dispose(); // Required to force buffer recreation\n\tgeometry.setIndex( newIndices );\n\n\t// update groups indices\n\n\tlet start = 0;\n\n\tfor ( let i = 0; i < groups.length; i ++ ) {\n\n\t\tconst group = groups[ i ];\n\n\t\tgroup.start = start;\n\t\tstart += group.count;\n\n\t}\n\n\t// merge groups\n\n\tlet currentGroup = groups[ 0 ];\n\n\tgeometry.groups = [ currentGroup ];\n\n\tfor ( let i = 1; i < groups.length; i ++ ) {\n\n\t\tconst group = groups[ i ];\n\n\t\tif ( currentGroup.materialIndex === group.materialIndex ) {\n\n\t\t\tcurrentGroup.count += group.count;\n\n\t\t} else {\n\n\t\t\tcurrentGroup = group;\n\t\t\tgeometry.groups.push( currentGroup );\n\n\t\t}\n\n\t}\n\n\treturn geometry;\n\n}\n\n\n// Creates a new, non-indexed geometry with smooth normals everywhere except faces that meet at\n// an angle greater than the crease angle.\nfunction toCreasedNormals( geometry, creaseAngle = Math.PI / 3 /* 60 degrees */ ) {\n\n\tconst creaseDot = Math.cos( creaseAngle );\n\tconst hashMultiplier = ( 1 + 1e-10 ) * 1e2;\n\n\t// reusable vertors\n\tconst verts = [ new three__WEBPACK_IMPORTED_MODULE_0__.Vector3(), new three__WEBPACK_IMPORTED_MODULE_0__.Vector3(), new three__WEBPACK_IMPORTED_MODULE_0__.Vector3() ];\n\tconst tempVec1 = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\tconst tempVec2 = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\tconst tempNorm = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\tconst tempNorm2 = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();\n\n\t// hashes a vector\n\tfunction hashVertex( v ) {\n\n\t\tconst x = ~ ~ ( v.x * hashMultiplier );\n\t\tconst y = ~ ~ ( v.y * hashMultiplier );\n\t\tconst z = ~ ~ ( v.z * hashMultiplier );\n\t\treturn `${x},${y},${z}`;\n\n\t}\n\n\tconst resultGeometry = geometry.toNonIndexed();\n\tconst posAttr = resultGeometry.attributes.position;\n\tconst vertexMap = {};\n\n\t// find all the normals shared by commonly located vertices\n\tfor ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {\n\n\t\tconst i3 = 3 * i;\n\t\tconst a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 );\n\t\tconst b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 );\n\t\tconst c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );\n\n\t\ttempVec1.subVectors( c, b );\n\t\ttempVec2.subVectors( a, b );\n\n\t\t// add the normal to the map for all vertices\n\t\tconst normal = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3().crossVectors( tempVec1, tempVec2 ).normalize();\n\t\tfor ( let n = 0; n < 3; n ++ ) {\n\n\t\t\tconst vert = verts[ n ];\n\t\t\tconst hash = hashVertex( vert );\n\t\t\tif ( ! ( hash in vertexMap ) ) {\n\n\t\t\t\tvertexMap[ hash ] = [];\n\n\t\t\t}\n\n\t\t\tvertexMap[ hash ].push( normal );\n\n\t\t}\n\n\t}\n\n\t// average normals from all vertices that share a common location if they are within the\n\t// provided crease threshold\n\tconst normalArray = new Float32Array( posAttr.count * 3 );\n\tconst normAttr = new three__WEBPACK_IMPORTED_MODULE_0__.BufferAttribute( normalArray, 3, false );\n\tfor ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {\n\n\t\t// get the face normal for this vertex\n\t\tconst i3 = 3 * i;\n\t\tconst a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 );\n\t\tconst b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 );\n\t\tconst c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );\n\n\t\ttempVec1.subVectors( c, b );\n\t\ttempVec2.subVectors( a, b );\n\n\t\ttempNorm.crossVectors( tempVec1, tempVec2 ).normalize();\n\n\t\t// average all normals that meet the threshold and set the normal value\n\t\tfor ( let n = 0; n < 3; n ++ ) {\n\n\t\t\tconst vert = verts[ n ];\n\t\t\tconst hash = hashVertex( vert );\n\t\t\tconst otherNormals = vertexMap[ hash ];\n\t\t\ttempNorm2.set( 0, 0, 0 );\n\n\t\t\tfor ( let k = 0, lk = otherNormals.length; k < lk; k ++ ) {\n\n\t\t\t\tconst otherNorm = otherNormals[ k ];\n\t\t\t\tif ( tempNorm.dot( otherNorm ) > creaseDot ) {\n\n\t\t\t\t\ttempNorm2.add( otherNorm );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\ttempNorm2.normalize();\n\t\t\tnormAttr.setXYZ( i3 + n, tempNorm2.x, tempNorm2.y, tempNorm2.z );\n\n\t\t}\n\n\t}\n\n\tresultGeometry.setAttribute( 'normal', normAttr );\n\treturn resultGeometry;\n\n}\n\nfunction mergeBufferGeometries( geometries, useGroups = false ) {\n\n\tconsole.warn( 'THREE.BufferGeometryUtils: mergeBufferGeometries() has been renamed to mergeGeometries().' ); // @deprecated, r151\n\treturn mergeGeometries( geometries, useGroups );\n\n}\n\nfunction mergeBufferAttributes( attributes ) {\n\n\tconsole.warn( 'THREE.BufferGeometryUtils: mergeBufferAttributes() has been renamed to mergeAttributes().' ); // @deprecated, r151\n\treturn mergeAttributes( attributes );\n\n}\n\n\n\n\n//# sourceURL=webpack://MaterialXView/./node_modules/three/examples/jsm/utils/BufferGeometryUtils.js?"); + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module can't be inlined because the eval devtool is used. +/******/ var __webpack_exports__ = __webpack_require__("./source/index.js"); +/******/ +/******/ })() +; \ No newline at end of file diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000000..d21a647c39 Binary files /dev/null and b/public/favicon.ico differ diff --git a/public/shader_ball.svg b/public/shader_ball.svg new file mode 100644 index 0000000000..2b51705a42 --- /dev/null +++ b/public/shader_ball.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/shader_ball2.svg b/public/shader_ball2.svg new file mode 100644 index 0000000000..62907b5df8 --- /dev/null +++ b/public/shader_ball2.svg @@ -0,0 +1,8 @@ + + + + + + + +